blob: 8e1e0afaa64393a0e443bac46bbaa6b71b8f5c00 [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) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000420 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
421 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000422 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000423 << D->getDeclName();
424 return ExprError();
425 }
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Anders Carlssone41590d2009-06-24 00:10:43 +0000427 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
428 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
429 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
430 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000431 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000432 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000433 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000434 << D->getIdentifier();
435 return ExprError();
436 }
437 }
438 }
439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregore0762c92009-06-19 23:52:42 +0000441 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregora2813ce2009-10-23 18:54:35 +0000443 return Owned(DeclRefExpr::Create(Context,
444 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
445 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000446 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000447}
448
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000449/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
450/// variable corresponding to the anonymous union or struct whose type
451/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000452static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
453 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000454 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000455 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Mike Stump390b4cc2009-05-16 07:39:55 +0000457 // FIXME: Once Decls are directly linked together, this will be an O(1)
458 // operation rather than a slow walk through DeclContext's vector (which
459 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000460 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000461 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000462 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000463 D != DEnd; ++D) {
464 if (*D == Record) {
465 // The object for the anonymous struct/union directly
466 // follows its type in the list of declarations.
467 ++D;
468 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000469 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000470 return *D;
471 }
472 }
473
474 assert(false && "Missing object for anonymous record");
475 return 0;
476}
477
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000478/// \brief Given a field that represents a member of an anonymous
479/// struct/union, build the path from that field's context to the
480/// actual member.
481///
482/// Construct the sequence of field member references we'll have to
483/// perform to get to the field in the anonymous union/struct. The
484/// list of members is built from the field outward, so traverse it
485/// backwards to go from an object in the current context to the field
486/// we found.
487///
488/// \returns The variable from which the field access should begin,
489/// for an anonymous struct/union that is not a member of another
490/// class. Otherwise, returns NULL.
491VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
492 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000493 assert(Field->getDeclContext()->isRecord() &&
494 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
495 && "Field must be stored inside an anonymous struct or union");
496
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000497 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000498 VarDecl *BaseObject = 0;
499 DeclContext *Ctx = Field->getDeclContext();
500 do {
501 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000502 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000503 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000504 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000505 else {
506 BaseObject = cast<VarDecl>(AnonObject);
507 break;
508 }
509 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000510 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000511 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000512
513 return BaseObject;
514}
515
516Sema::OwningExprResult
517Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
518 FieldDecl *Field,
519 Expr *BaseObjectExpr,
520 SourceLocation OpLoc) {
521 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000522 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000523 AnonFields);
524
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000525 // Build the expression that refers to the base object, from
526 // which we will build a sequence of member references to each
527 // of the anonymous union objects and, eventually, the field we
528 // found via name lookup.
529 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000530 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000531 if (BaseObject) {
532 // BaseObject is an anonymous struct/union variable (and is,
533 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000534 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000535 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000536 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000537 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000538 BaseQuals
539 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000540 } else if (BaseObjectExpr) {
541 // The caller provided the base object expression. Determine
542 // whether its a pointer and whether it adds any qualifiers to the
543 // anonymous struct/union fields we're looking into.
544 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000545 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000546 BaseObjectIsPointer = true;
547 ObjectType = ObjectPtr->getPointeeType();
548 }
John McCall0953e762009-09-24 19:53:00 +0000549 BaseQuals
550 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000551 } else {
552 // We've found a member of an anonymous struct/union that is
553 // inside a non-anonymous struct/union, so in a well-formed
554 // program our base object expression is "this".
555 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
556 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000557 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000558 = Context.getTagDeclType(
559 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
560 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000561 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000562 == Context.getCanonicalType(ThisType)) ||
563 IsDerivedFrom(ThisType, AnonFieldType)) {
564 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000566 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000567 BaseObjectIsPointer = true;
568 }
569 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000570 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
571 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000572 }
John McCall0953e762009-09-24 19:53:00 +0000573 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000574 }
575
Mike Stump1eb44332009-09-09 15:08:12 +0000576 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000577 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
578 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000579 }
580
581 // Build the implicit member references to the field of the
582 // anonymous struct/union.
583 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000584 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000585 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
586 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
587 FI != FIEnd; ++FI) {
588 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000589 Qualifiers MemberTypeQuals =
590 Context.getCanonicalType(MemberType).getQualifiers();
591
592 // CVR attributes from the base are picked up by members,
593 // except that 'mutable' members don't pick up 'const'.
594 if ((*FI)->isMutable())
595 ResultQuals.removeConst();
596
597 // GC attributes are never picked up by members.
598 ResultQuals.removeObjCGCAttr();
599
600 // TR 18037 does not allow fields to be declared with address spaces.
601 assert(!MemberTypeQuals.hasAddressSpace());
602
603 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
604 if (NewQuals != MemberTypeQuals)
605 MemberType = Context.getQualifiedType(MemberType, NewQuals);
606
Douglas Gregore0762c92009-06-19 23:52:42 +0000607 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000608 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000609 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
610 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000611 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000612 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000613 }
614
Sebastian Redlcd965b92009-01-18 18:53:16 +0000615 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000616}
617
John McCall129e2df2009-11-30 22:42:35 +0000618/// Decomposes the given name into a DeclarationName, its location, and
619/// possibly a list of template arguments.
620///
621/// If this produces template arguments, it is permitted to call
622/// DecomposeTemplateName.
623///
624/// This actually loses a lot of source location information for
625/// non-standard name kinds; we should consider preserving that in
626/// some way.
627static void DecomposeUnqualifiedId(Sema &SemaRef,
628 const UnqualifiedId &Id,
629 TemplateArgumentListInfo &Buffer,
630 DeclarationName &Name,
631 SourceLocation &NameLoc,
632 const TemplateArgumentListInfo *&TemplateArgs) {
633 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
634 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
635 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
636
637 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
638 Id.TemplateId->getTemplateArgs(),
639 Id.TemplateId->NumArgs);
640 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
641 TemplateArgsPtr.release();
642
643 TemplateName TName =
644 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
645
646 Name = SemaRef.Context.getNameForTemplate(TName);
647 NameLoc = Id.TemplateId->TemplateNameLoc;
648 TemplateArgs = &Buffer;
649 } else {
650 Name = SemaRef.GetNameFromUnqualifiedId(Id);
651 NameLoc = Id.StartLocation;
652 TemplateArgs = 0;
653 }
654}
655
656/// Decompose the given template name into a list of lookup results.
657///
658/// The unqualified ID must name a non-dependent template, which can
659/// be more easily tested by checking whether DecomposeUnqualifiedId
660/// found template arguments.
661static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
662 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
663 TemplateName TName =
664 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
665
John McCallf7a1a742009-11-24 19:00:30 +0000666 if (TemplateDecl *TD = TName.getAsTemplateDecl())
667 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000668 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
669 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
670 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000671 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000672
John McCallf7a1a742009-11-24 19:00:30 +0000673 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000674}
675
John McCall129e2df2009-11-30 22:42:35 +0000676static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
677 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
678 E = Record->bases_end(); I != E; ++I) {
679 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
680 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
681 if (!BaseRT) return false;
682
683 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
684 if (!BaseRecord->isDefinition() ||
685 !IsFullyFormedScope(SemaRef, BaseRecord))
686 return false;
687 }
688
689 return true;
690}
691
John McCalle1599ce2009-11-30 23:50:49 +0000692/// Determines whether we can lookup this id-expression now or whether
693/// we have to wait until template instantiation is complete.
694static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000695 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000696
John McCalle1599ce2009-11-30 23:50:49 +0000697 // If the qualifier scope isn't computable, it's definitely dependent.
698 if (!DC) return true;
699
700 // If the qualifier scope doesn't name a record, we can always look into it.
701 if (!isa<CXXRecordDecl>(DC)) return false;
702
703 // We can't look into record types unless they're fully-formed.
704 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
705
John McCallaa81e162009-12-01 22:10:20 +0000706 return false;
707}
John McCalle1599ce2009-11-30 23:50:49 +0000708
John McCallaa81e162009-12-01 22:10:20 +0000709/// Determines if the given class is provably not derived from all of
710/// the prospective base classes.
711static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
712 CXXRecordDecl *Record,
713 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000714 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000715 return false;
716
John McCallb1b42562009-12-01 22:28:41 +0000717 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
718 if (!RD) return false;
719 Record = cast<CXXRecordDecl>(RD);
720
John McCallaa81e162009-12-01 22:10:20 +0000721 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
722 E = Record->bases_end(); I != E; ++I) {
723 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
724 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
725 if (!BaseRT) return false;
726
727 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000728 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
729 return false;
730 }
731
732 return true;
733}
734
735static bool IsInstanceMember(NamedDecl *D) {
John McCall336e7742009-12-02 19:59:55 +0000736 if (isa<EnumConstantDecl>(D))
737 return false;
738
John McCallaa81e162009-12-01 22:10:20 +0000739 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
740 "checking whether non-member is instance member");
741
742 if (isa<FieldDecl>(D)) return true;
743
744 if (isa<CXXMethodDecl>(D))
745 return !cast<CXXMethodDecl>(D)->isStatic();
746
747 if (isa<FunctionTemplateDecl>(D)) {
748 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
749 return !cast<CXXMethodDecl>(D)->isStatic();
750 }
751
752 return false;
753}
754
755enum IMAKind {
756 /// The reference is definitely not an instance member access.
757 IMA_Static,
758
759 /// The reference may be an implicit instance member access.
760 IMA_Mixed,
761
762 /// The reference may be to an instance member, but it is invalid if
763 /// so, because the context is not an instance method.
764 IMA_Mixed_StaticContext,
765
766 /// The reference may be to an instance member, but it is invalid if
767 /// so, because the context is from an unrelated class.
768 IMA_Mixed_Unrelated,
769
770 /// The reference is definitely an implicit instance member access.
771 IMA_Instance,
772
773 /// The reference may be to an unresolved using declaration.
774 IMA_Unresolved,
775
776 /// The reference may be to an unresolved using declaration and the
777 /// context is not an instance method.
778 IMA_Unresolved_StaticContext,
779
780 /// The reference is to a member of an anonymous structure in a
781 /// non-class context.
782 IMA_AnonymousMember,
783
784 /// All possible referrents are instance members and the current
785 /// context is not an instance method.
786 IMA_Error_StaticContext,
787
788 /// All possible referrents are instance members of an unrelated
789 /// class.
790 IMA_Error_Unrelated
791};
792
793/// The given lookup names class member(s) and is not being used for
794/// an address-of-member expression. Classify the type of access
795/// according to whether it's possible that this reference names an
796/// instance member. This is best-effort; it is okay to
797/// conservatively answer "yes", in which case some errors will simply
798/// not be caught until template-instantiation.
799static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
800 const LookupResult &R) {
801 assert(!R.empty() && isa<CXXRecordDecl>((*R.begin())->getDeclContext()));
802
803 bool isStaticContext =
804 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
805 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
806
807 if (R.isUnresolvableResult())
808 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
809
810 // Collect all the declaring classes of instance members we find.
811 bool hasNonInstance = false;
812 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
813 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
814 NamedDecl *D = (*I)->getUnderlyingDecl();
815 if (IsInstanceMember(D)) {
816 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
817
818 // If this is a member of an anonymous record, move out to the
819 // innermost non-anonymous struct or union. If there isn't one,
820 // that's a special case.
821 while (R->isAnonymousStructOrUnion()) {
822 R = dyn_cast<CXXRecordDecl>(R->getParent());
823 if (!R) return IMA_AnonymousMember;
824 }
825 Classes.insert(R->getCanonicalDecl());
826 }
827 else
828 hasNonInstance = true;
829 }
830
831 // If we didn't find any instance members, it can't be an implicit
832 // member reference.
833 if (Classes.empty())
834 return IMA_Static;
835
836 // If the current context is not an instance method, it can't be
837 // an implicit member reference.
838 if (isStaticContext)
839 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
840
841 // If we can prove that the current context is unrelated to all the
842 // declaring classes, it can't be an implicit member reference (in
843 // which case it's an error if any of those members are selected).
844 if (IsProvablyNotDerivedFrom(SemaRef,
845 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
846 Classes))
847 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
848
849 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
850}
851
852/// Diagnose a reference to a field with no object available.
853static void DiagnoseInstanceReference(Sema &SemaRef,
854 const CXXScopeSpec &SS,
855 const LookupResult &R) {
856 SourceLocation Loc = R.getNameLoc();
857 SourceRange Range(Loc);
858 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
859
860 if (R.getAsSingle<FieldDecl>()) {
861 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
862 if (MD->isStatic()) {
863 // "invalid use of member 'x' in static member function"
864 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
865 << Range << R.getLookupName();
866 return;
867 }
868 }
869
870 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
871 << R.getLookupName() << Range;
872 return;
873 }
874
875 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000876}
877
John McCallf7a1a742009-11-24 19:00:30 +0000878Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
879 const CXXScopeSpec &SS,
880 UnqualifiedId &Id,
881 bool HasTrailingLParen,
882 bool isAddressOfOperand) {
883 assert(!(isAddressOfOperand && HasTrailingLParen) &&
884 "cannot be direct & operand and have a trailing lparen");
885
886 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000887 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000888
John McCall129e2df2009-11-30 22:42:35 +0000889 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +0000890
891 // Decompose the UnqualifiedId into the following data.
892 DeclarationName Name;
893 SourceLocation NameLoc;
894 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +0000895 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
896 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000897
Douglas Gregor10c42622008-11-18 15:03:34 +0000898 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +0000899
John McCallf7a1a742009-11-24 19:00:30 +0000900 // C++ [temp.dep.expr]p3:
901 // An id-expression is type-dependent if it contains:
902 // -- a nested-name-specifier that contains a class-name that
903 // names a dependent type.
904 // Determine whether this is a member of an unknown specialization;
905 // we need to handle these differently.
John McCalle1599ce2009-11-30 23:50:49 +0000906 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCallf7a1a742009-11-24 19:00:30 +0000907 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000908 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000909 TemplateArgs);
910 }
John McCallba135432009-11-21 08:51:07 +0000911
John McCallf7a1a742009-11-24 19:00:30 +0000912 // Perform the required lookup.
913 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
914 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +0000915 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +0000916 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +0000917 } else {
918 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +0000919
John McCallf7a1a742009-11-24 19:00:30 +0000920 // If this reference is in an Objective-C method, then we need to do
921 // some special Objective-C lookup, too.
922 if (!SS.isSet() && II && getCurMethodDecl()) {
923 OwningExprResult E(LookupInObjCMethod(R, S, II));
924 if (E.isInvalid())
925 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000926
John McCallf7a1a742009-11-24 19:00:30 +0000927 Expr *Ex = E.takeAs<Expr>();
928 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000929 }
Chris Lattner8a934232008-03-31 00:36:02 +0000930 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000931
John McCallf7a1a742009-11-24 19:00:30 +0000932 if (R.isAmbiguous())
933 return ExprError();
934
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000935 // Determine whether this name might be a candidate for
936 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +0000937 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000938
John McCallf7a1a742009-11-24 19:00:30 +0000939 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +0000941 // in C90, extension in C99, forbidden in C++).
942 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
943 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
944 if (D) R.addDecl(D);
945 }
946
947 // If this name wasn't predeclared and if this is not a function
948 // call, diagnose the problem.
949 if (R.empty()) {
950 if (!SS.isEmpty())
951 return ExprError(Diag(NameLoc, diag::err_no_member)
952 << Name << computeDeclContext(SS, false)
953 << SS.getRange());
Douglas Gregor3f093272009-10-13 21:16:44 +0000954 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Sean Hunt3e518bd2009-11-29 07:34:05 +0000955 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000956 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCallf7a1a742009-11-24 19:00:30 +0000957 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
958 << Name);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000959 else
John McCallf7a1a742009-11-24 19:00:30 +0000960 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000961 }
962 }
Mike Stump1eb44332009-09-09 15:08:12 +0000963
John McCallf7a1a742009-11-24 19:00:30 +0000964 // This is guaranteed from this point on.
965 assert(!R.empty() || ADL);
966
967 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000968 // Warn about constructs like:
969 // if (void *X = foo()) { ... } else { X }.
970 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Douglas Gregor751f9a42009-06-30 15:47:41 +0000972 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
973 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000974 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000975 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000976 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +0000977 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000978 << Var->getDeclName()
979 << (Var->getType()->isPointerType()? 2 :
980 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +0000981 break;
982 }
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000984 // Move to the parent of this scope.
985 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +0000986 }
987 }
John McCallf7a1a742009-11-24 19:00:30 +0000988 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000989 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
990 // C99 DR 316 says that, if a function type comes from a
991 // function definition (without a prototype), that type is only
992 // used for checking compatibility. Therefore, when referencing
993 // the function, we pretend that we don't have the full function
994 // type.
John McCallf7a1a742009-11-24 19:00:30 +0000995 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +0000996 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000997
Douglas Gregor751f9a42009-06-30 15:47:41 +0000998 QualType T = Func->getType();
999 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001000 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001001 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001002 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001003 }
1004 }
Mike Stump1eb44332009-09-09 15:08:12 +00001005
John McCallaa81e162009-12-01 22:10:20 +00001006 // Check whether this might be a C++ implicit instance member access.
1007 // C++ [expr.prim.general]p6:
1008 // Within the definition of a non-static member function, an
1009 // identifier that names a non-static member is transformed to a
1010 // class member access expression.
1011 // But note that &SomeClass::foo is grammatically distinct, even
1012 // though we don't parse it that way.
1013 if (!R.empty() && (*R.begin())->getDeclContext()->isRecord()) {
John McCallf7a1a742009-11-24 19:00:30 +00001014 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall5b3f9132009-11-22 01:44:31 +00001015
John McCallaa81e162009-12-01 22:10:20 +00001016 if (!isAbstractMemberPointer) {
1017 switch (ClassifyImplicitMemberAccess(*this, R)) {
1018 case IMA_Instance:
1019 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1020
1021 case IMA_AnonymousMember:
1022 assert(R.isSingleResult());
1023 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1024 R.getAsSingle<FieldDecl>());
1025
1026 case IMA_Mixed:
1027 case IMA_Mixed_Unrelated:
1028 case IMA_Unresolved:
1029 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1030
1031 case IMA_Static:
1032 case IMA_Mixed_StaticContext:
1033 case IMA_Unresolved_StaticContext:
1034 break;
1035
1036 case IMA_Error_StaticContext:
1037 case IMA_Error_Unrelated:
1038 DiagnoseInstanceReference(*this, SS, R);
1039 return ExprError();
1040 }
John McCall5b3f9132009-11-22 01:44:31 +00001041 }
1042 }
1043
John McCallf7a1a742009-11-24 19:00:30 +00001044 if (TemplateArgs)
1045 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001046
John McCallf7a1a742009-11-24 19:00:30 +00001047 return BuildDeclarationNameExpr(SS, R, ADL);
1048}
1049
John McCall129e2df2009-11-30 22:42:35 +00001050/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1051/// declaration name, generally during template instantiation.
1052/// There's a large number of things which don't need to be done along
1053/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001054Sema::OwningExprResult
1055Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1056 DeclarationName Name,
1057 SourceLocation NameLoc) {
1058 DeclContext *DC;
1059 if (!(DC = computeDeclContext(SS, false)) ||
1060 DC->isDependentContext() ||
1061 RequireCompleteDeclContext(SS))
1062 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1063
1064 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1065 LookupQualifiedName(R, DC);
1066
1067 if (R.isAmbiguous())
1068 return ExprError();
1069
1070 if (R.empty()) {
1071 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1072 return ExprError();
1073 }
1074
1075 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1076}
1077
1078/// LookupInObjCMethod - The parser has read a name in, and Sema has
1079/// detected that we're currently inside an ObjC method. Perform some
1080/// additional lookup.
1081///
1082/// Ideally, most of this would be done by lookup, but there's
1083/// actually quite a lot of extra work involved.
1084///
1085/// Returns a null sentinel to indicate trivial success.
1086Sema::OwningExprResult
1087Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1088 IdentifierInfo *II) {
1089 SourceLocation Loc = Lookup.getNameLoc();
1090
1091 // There are two cases to handle here. 1) scoped lookup could have failed,
1092 // in which case we should look for an ivar. 2) scoped lookup could have
1093 // found a decl, but that decl is outside the current instance method (i.e.
1094 // a global variable). In these two cases, we do a lookup for an ivar with
1095 // this name, if the lookup sucedes, we replace it our current decl.
1096
1097 // If we're in a class method, we don't normally want to look for
1098 // ivars. But if we don't find anything else, and there's an
1099 // ivar, that's an error.
1100 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1101
1102 bool LookForIvars;
1103 if (Lookup.empty())
1104 LookForIvars = true;
1105 else if (IsClassMethod)
1106 LookForIvars = false;
1107 else
1108 LookForIvars = (Lookup.isSingleResult() &&
1109 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1110
1111 if (LookForIvars) {
1112 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1113 ObjCInterfaceDecl *ClassDeclared;
1114 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1115 // Diagnose using an ivar in a class method.
1116 if (IsClassMethod)
1117 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1118 << IV->getDeclName());
1119
1120 // If we're referencing an invalid decl, just return this as a silent
1121 // error node. The error diagnostic was already emitted on the decl.
1122 if (IV->isInvalidDecl())
1123 return ExprError();
1124
1125 // Check if referencing a field with __attribute__((deprecated)).
1126 if (DiagnoseUseOfDecl(IV, Loc))
1127 return ExprError();
1128
1129 // Diagnose the use of an ivar outside of the declaring class.
1130 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1131 ClassDeclared != IFace)
1132 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1133
1134 // FIXME: This should use a new expr for a direct reference, don't
1135 // turn this into Self->ivar, just return a BareIVarExpr or something.
1136 IdentifierInfo &II = Context.Idents.get("self");
1137 UnqualifiedId SelfName;
1138 SelfName.setIdentifier(&II, SourceLocation());
1139 CXXScopeSpec SelfScopeSpec;
1140 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1141 SelfName, false, false);
1142 MarkDeclarationReferenced(Loc, IV);
1143 return Owned(new (Context)
1144 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1145 SelfExpr.takeAs<Expr>(), true, true));
1146 }
1147 } else if (getCurMethodDecl()->isInstanceMethod()) {
1148 // We should warn if a local variable hides an ivar.
1149 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1150 ObjCInterfaceDecl *ClassDeclared;
1151 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1152 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1153 IFace == ClassDeclared)
1154 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1155 }
1156 }
1157
1158 // Needed to implement property "super.method" notation.
1159 if (Lookup.empty() && II->isStr("super")) {
1160 QualType T;
1161
1162 if (getCurMethodDecl()->isInstanceMethod())
1163 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1164 getCurMethodDecl()->getClassInterface()));
1165 else
1166 T = Context.getObjCClassType();
1167 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1168 }
1169
1170 // Sentinel value saying that we didn't do anything special.
1171 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001172}
John McCallba135432009-11-21 08:51:07 +00001173
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001174/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001175bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001176Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1177 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001178 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001179 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001180 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001181 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001182 if (DestType->isDependentType() || From->getType()->isDependentType())
1183 return false;
1184 QualType FromRecordType = From->getType();
1185 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001186 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001187 DestType = Context.getPointerType(DestType);
1188 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001189 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001190 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1191 CheckDerivedToBaseConversion(FromRecordType,
1192 DestRecordType,
1193 From->getSourceRange().getBegin(),
1194 From->getSourceRange()))
1195 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001196 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1197 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001198 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001199 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001200}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001201
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001202/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001203static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
John McCall129e2df2009-11-30 22:42:35 +00001204 const CXXScopeSpec &SS, NamedDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001205 SourceLocation Loc, QualType Ty,
1206 const TemplateArgumentListInfo *TemplateArgs = 0) {
1207 NestedNameSpecifier *Qualifier = 0;
1208 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001209 if (SS.isSet()) {
1210 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1211 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001212 }
Mike Stump1eb44332009-09-09 15:08:12 +00001213
John McCallf7a1a742009-11-24 19:00:30 +00001214 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1215 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001216}
1217
John McCallaa81e162009-12-01 22:10:20 +00001218/// Builds an implicit member access expression. The current context
1219/// is known to be an instance method, and the given unqualified lookup
1220/// set is known to contain only instance members, at least one of which
1221/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001222Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001223Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1224 LookupResult &R,
1225 const TemplateArgumentListInfo *TemplateArgs,
1226 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001227 assert(!R.empty() && !R.isAmbiguous());
1228
John McCallba135432009-11-21 08:51:07 +00001229 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001230
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001231 // We may have found a field within an anonymous union or struct
1232 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001233 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001234 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001235 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001236 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001237 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001238
John McCallaa81e162009-12-01 22:10:20 +00001239 // If this is known to be an instance access, go ahead and build a
1240 // 'this' expression now.
1241 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1242 Expr *This = 0; // null signifies implicit access
1243 if (IsKnownInstance) {
1244 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001245 }
1246
John McCallaa81e162009-12-01 22:10:20 +00001247 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1248 /*OpLoc*/ SourceLocation(),
1249 /*IsArrow*/ true,
1250 SS, R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001251}
1252
John McCallf7a1a742009-11-24 19:00:30 +00001253bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001254 const LookupResult &R,
1255 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001256 // Only when used directly as the postfix-expression of a call.
1257 if (!HasTrailingLParen)
1258 return false;
1259
1260 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001261 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001262 return false;
1263
1264 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001265 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001266 return false;
1267
1268 // Turn off ADL when we find certain kinds of declarations during
1269 // normal lookup:
1270 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1271 NamedDecl *D = *I;
1272
1273 // C++0x [basic.lookup.argdep]p3:
1274 // -- a declaration of a class member
1275 // Since using decls preserve this property, we check this on the
1276 // original decl.
1277 if (D->getDeclContext()->isRecord())
1278 return false;
1279
1280 // C++0x [basic.lookup.argdep]p3:
1281 // -- a block-scope function declaration that is not a
1282 // using-declaration
1283 // NOTE: we also trigger this for function templates (in fact, we
1284 // don't check the decl type at all, since all other decl types
1285 // turn off ADL anyway).
1286 if (isa<UsingShadowDecl>(D))
1287 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1288 else if (D->getDeclContext()->isFunctionOrMethod())
1289 return false;
1290
1291 // C++0x [basic.lookup.argdep]p3:
1292 // -- a declaration that is neither a function or a function
1293 // template
1294 // And also for builtin functions.
1295 if (isa<FunctionDecl>(D)) {
1296 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1297
1298 // But also builtin functions.
1299 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1300 return false;
1301 } else if (!isa<FunctionTemplateDecl>(D))
1302 return false;
1303 }
1304
1305 return true;
1306}
1307
1308
John McCallba135432009-11-21 08:51:07 +00001309/// Diagnoses obvious problems with the use of the given declaration
1310/// as an expression. This is only actually called for lookups that
1311/// were not overloaded, and it doesn't promise that the declaration
1312/// will in fact be used.
1313static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1314 if (isa<TypedefDecl>(D)) {
1315 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1316 return true;
1317 }
1318
1319 if (isa<ObjCInterfaceDecl>(D)) {
1320 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1321 return true;
1322 }
1323
1324 if (isa<NamespaceDecl>(D)) {
1325 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1326 return true;
1327 }
1328
1329 return false;
1330}
1331
1332Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001333Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001334 LookupResult &R,
1335 bool NeedsADL) {
John McCallf7a1a742009-11-24 19:00:30 +00001336 // If this isn't an overloaded result and we don't need ADL, just
1337 // build an ordinary singleton decl ref.
John McCall5b3f9132009-11-22 01:44:31 +00001338 if (!NeedsADL && !R.isOverloadedResult())
1339 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001340
1341 // We only need to check the declaration if there's exactly one
1342 // result, because in the overloaded case the results can only be
1343 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001344 if (R.isSingleResult() &&
1345 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001346 return ExprError();
1347
John McCallf7a1a742009-11-24 19:00:30 +00001348 bool Dependent
1349 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001350 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001351 = UnresolvedLookupExpr::Create(Context, Dependent,
1352 (NestedNameSpecifier*) SS.getScopeRep(),
1353 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001354 R.getLookupName(), R.getNameLoc(),
1355 NeedsADL, R.isOverloadedResult());
1356 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1357 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001358
1359 return Owned(ULE);
1360}
1361
1362
1363/// \brief Complete semantic analysis for a reference to the given declaration.
1364Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001365Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001366 SourceLocation Loc, NamedDecl *D) {
1367 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001368 assert(!isa<FunctionTemplateDecl>(D) &&
1369 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001370 DeclarationName Name = D->getDeclName();
1371
1372 if (CheckDeclInExpr(*this, Loc, D))
1373 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001374
Douglas Gregor9af2f522009-12-01 16:58:18 +00001375 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1376 // Specifically diagnose references to class templates that are missing
1377 // a template argument list.
1378 Diag(Loc, diag::err_template_decl_ref)
1379 << Template << SS.getRange();
1380 Diag(Template->getLocation(), diag::note_template_decl_here);
1381 return ExprError();
1382 }
1383
1384 // Make sure that we're referring to a value.
1385 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1386 if (!VD) {
1387 Diag(Loc, diag::err_ref_non_value)
1388 << D << SS.getRange();
1389 Diag(D->getLocation(), diag::note_previous_decl);
1390 return ExprError();
1391 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001392
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001393 // Check whether this declaration can be used. Note that we suppress
1394 // this check when we're going to perform argument-dependent lookup
1395 // on this function name, because this might not be the function
1396 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001397 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001398 return ExprError();
1399
Steve Naroffdd972f22008-09-05 22:11:13 +00001400 // Only create DeclRefExpr's for valid Decl's.
1401 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001402 return ExprError();
1403
Chris Lattner639e2d32008-10-20 05:16:36 +00001404 // If the identifier reference is inside a block, and it refers to a value
1405 // that is outside the block, create a BlockDeclRefExpr instead of a
1406 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1407 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001408 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001409 // We do not do this for things like enum constants, global variables, etc,
1410 // as they do not get snapshotted.
1411 //
1412 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001413 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001414 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001415 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001416 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001417 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001418 // This is to record that a 'const' was actually synthesize and added.
1419 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001420 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Eli Friedman5fdeae12009-03-22 23:00:19 +00001422 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001423 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001424 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001425 }
1426 // If this reference is not in a block or if the referenced variable is
1427 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001428
John McCallf7a1a742009-11-24 19:00:30 +00001429 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001430}
1431
Sebastian Redlcd965b92009-01-18 18:53:16 +00001432Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1433 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001434 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001435
Reid Spencer5f016e22007-07-11 17:01:13 +00001436 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001437 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001438 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1439 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1440 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001442
Chris Lattnerfa28b302008-01-12 08:14:25 +00001443 // Pre-defined identifiers are of type char[x], where x is the length of the
1444 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Anders Carlsson3a082d82009-09-08 18:24:21 +00001446 Decl *currentDecl = getCurFunctionOrMethodDecl();
1447 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001448 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001449 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001450 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001451
Anders Carlsson773f3972009-09-11 01:22:35 +00001452 QualType ResTy;
1453 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1454 ResTy = Context.DependentTy;
1455 } else {
1456 unsigned Length =
1457 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001458
Anders Carlsson773f3972009-09-11 01:22:35 +00001459 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001460 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001461 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1462 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001463 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001464}
1465
Sebastian Redlcd965b92009-01-18 18:53:16 +00001466Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 llvm::SmallString<16> CharBuffer;
1468 CharBuffer.resize(Tok.getLength());
1469 const char *ThisTokBegin = &CharBuffer[0];
1470 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001471
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1473 Tok.getLocation(), PP);
1474 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001475 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001476
1477 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1478
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001479 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1480 Literal.isWide(),
1481 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001482}
1483
Sebastian Redlcd965b92009-01-18 18:53:16 +00001484Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1485 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1487 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001488 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001489 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001490 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001491 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 }
Ted Kremenek28396602009-01-13 23:19:12 +00001493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001495 // Add padding so that NumericLiteralParser can overread by one character.
1496 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001498
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 // Get the spelling of the token, which eliminates trigraphs, etc.
1500 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001501
Mike Stump1eb44332009-09-09 15:08:12 +00001502 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 Tok.getLocation(), PP);
1504 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001505 return ExprError();
1506
Chris Lattner5d661452007-08-26 03:42:43 +00001507 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001508
Chris Lattner5d661452007-08-26 03:42:43 +00001509 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001510 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001511 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001512 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001513 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001514 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001515 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001516 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001517
1518 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1519
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001520 // isExact will be set by GetFloatValue().
1521 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001522 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1523 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001524
Chris Lattner5d661452007-08-26 03:42:43 +00001525 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001526 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001527 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001528 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001529
Neil Boothb9449512007-08-29 22:00:19 +00001530 // long long is a C99 feature.
1531 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001532 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001533 Diag(Tok.getLocation(), diag::ext_longlong);
1534
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001536 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001537
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 if (Literal.GetIntegerValue(ResultVal)) {
1539 // If this value didn't fit into uintmax_t, warn and force to ull.
1540 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001541 Ty = Context.UnsignedLongLongTy;
1542 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001543 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 } else {
1545 // If this value fits into a ULL, try to figure out what else it fits into
1546 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001547
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1549 // be an unsigned int.
1550 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1551
1552 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001553 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001554 if (!Literal.isLong && !Literal.isLongLong) {
1555 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001556 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001557
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 // Does it fit in a unsigned int?
1559 if (ResultVal.isIntN(IntSize)) {
1560 // Does it fit in a signed int?
1561 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001562 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001564 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001565 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001568
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001570 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001571 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001572
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 // Does it fit in a unsigned long?
1574 if (ResultVal.isIntN(LongSize)) {
1575 // Does it fit in a signed long?
1576 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001577 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001579 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001580 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001582 }
1583
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001585 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001586 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001587
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 // Does it fit in a unsigned long long?
1589 if (ResultVal.isIntN(LongLongSize)) {
1590 // Does it fit in a signed long long?
1591 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001592 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001594 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001595 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 }
1597 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001598
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 // If we still couldn't decide a type, we probably have something that
1600 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001601 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001603 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001604 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001606
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001607 if (ResultVal.getBitWidth() != Width)
1608 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001610 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001612
Chris Lattner5d661452007-08-26 03:42:43 +00001613 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1614 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001615 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001616 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001617
1618 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001619}
1620
Sebastian Redlcd965b92009-01-18 18:53:16 +00001621Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1622 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001623 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001624 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001625 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001626}
1627
1628/// The UsualUnaryConversions() function is *not* called by this routine.
1629/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001630bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001631 SourceLocation OpLoc,
1632 const SourceRange &ExprRange,
1633 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001634 if (exprType->isDependentType())
1635 return false;
1636
Sebastian Redl5d484e82009-11-23 17:18:46 +00001637 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1638 // the result is the size of the referenced type."
1639 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1640 // result shall be the alignment of the referenced type."
1641 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1642 exprType = Ref->getPointeeType();
1643
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001645 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001646 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001647 if (isSizeof)
1648 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1649 return false;
1650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Chris Lattner1efaa952009-04-24 00:30:45 +00001652 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001653 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001654 Diag(OpLoc, diag::ext_sizeof_void_type)
1655 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001656 return false;
1657 }
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Chris Lattner1efaa952009-04-24 00:30:45 +00001659 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001660 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001661 PDiag(diag::err_alignof_incomplete_type)
1662 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001663 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Chris Lattner1efaa952009-04-24 00:30:45 +00001665 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001666 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001667 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001668 << exprType << isSizeof << ExprRange;
1669 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001670 }
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Chris Lattner1efaa952009-04-24 00:30:45 +00001672 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001673}
1674
Chris Lattner31e21e02009-01-24 20:17:12 +00001675bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1676 const SourceRange &ExprRange) {
1677 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001678
Mike Stump1eb44332009-09-09 15:08:12 +00001679 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001680 if (isa<DeclRefExpr>(E))
1681 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001682
1683 // Cannot know anything else if the expression is dependent.
1684 if (E->isTypeDependent())
1685 return false;
1686
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001687 if (E->getBitField()) {
1688 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1689 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001690 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001691
1692 // Alignment of a field access is always okay, so long as it isn't a
1693 // bit-field.
1694 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001695 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001696 return false;
1697
Chris Lattner31e21e02009-01-24 20:17:12 +00001698 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1699}
1700
Douglas Gregorba498172009-03-13 21:01:28 +00001701/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001702Action::OwningExprResult
John McCall5ab75172009-11-04 07:28:41 +00001703Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1704 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001705 bool isSizeOf, SourceRange R) {
John McCall5ab75172009-11-04 07:28:41 +00001706 if (!DInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001707 return ExprError();
1708
John McCall5ab75172009-11-04 07:28:41 +00001709 QualType T = DInfo->getType();
1710
Douglas Gregorba498172009-03-13 21:01:28 +00001711 if (!T->isDependentType() &&
1712 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1713 return ExprError();
1714
1715 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCall5ab75172009-11-04 07:28:41 +00001716 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001717 Context.getSizeType(), OpLoc,
1718 R.getEnd()));
1719}
1720
1721/// \brief Build a sizeof or alignof expression given an expression
1722/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001723Action::OwningExprResult
1724Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001725 bool isSizeOf, SourceRange R) {
1726 // Verify that the operand is valid.
1727 bool isInvalid = false;
1728 if (E->isTypeDependent()) {
1729 // Delay type-checking for type-dependent expressions.
1730 } else if (!isSizeOf) {
1731 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001732 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001733 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1734 isInvalid = true;
1735 } else {
1736 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1737 }
1738
1739 if (isInvalid)
1740 return ExprError();
1741
1742 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1743 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1744 Context.getSizeType(), OpLoc,
1745 R.getEnd()));
1746}
1747
Sebastian Redl05189992008-11-11 17:56:53 +00001748/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1749/// the same for @c alignof and @c __alignof
1750/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001751Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001752Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1753 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001755 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001756
Sebastian Redl05189992008-11-11 17:56:53 +00001757 if (isType) {
John McCall5ab75172009-11-04 07:28:41 +00001758 DeclaratorInfo *DInfo;
1759 (void) GetTypeFromParser(TyOrEx, &DInfo);
1760 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001761 }
Sebastian Redl05189992008-11-11 17:56:53 +00001762
Douglas Gregorba498172009-03-13 21:01:28 +00001763 Expr *ArgEx = (Expr *)TyOrEx;
1764 Action::OwningExprResult Result
1765 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1766
1767 if (Result.isInvalid())
1768 DeleteExpr(ArgEx);
1769
1770 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001771}
1772
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001773QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001774 if (V->isTypeDependent())
1775 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Chris Lattnercc26ed72007-08-26 05:39:26 +00001777 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001778 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001779 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Chris Lattnercc26ed72007-08-26 05:39:26 +00001781 // Otherwise they pass through real integer and floating point types here.
1782 if (V->getType()->isArithmeticType())
1783 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Chris Lattnercc26ed72007-08-26 05:39:26 +00001785 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001786 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1787 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001788 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001789}
1790
1791
Reid Spencer5f016e22007-07-11 17:01:13 +00001792
Sebastian Redl0eb23302009-01-19 00:08:26 +00001793Action::OwningExprResult
1794Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1795 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 UnaryOperator::Opcode Opc;
1797 switch (Kind) {
1798 default: assert(0 && "Unknown unary op!");
1799 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1800 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1801 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001802
Eli Friedmane4216e92009-11-18 03:38:04 +00001803 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001804}
1805
Sebastian Redl0eb23302009-01-19 00:08:26 +00001806Action::OwningExprResult
1807Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1808 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001809 // Since this might be a postfix expression, get rid of ParenListExprs.
1810 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1811
Sebastian Redl0eb23302009-01-19 00:08:26 +00001812 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1813 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Douglas Gregor337c6b92008-11-19 17:17:41 +00001815 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001816 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1817 Base.release();
1818 Idx.release();
1819 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1820 Context.DependentTy, RLoc));
1821 }
1822
Mike Stump1eb44332009-09-09 15:08:12 +00001823 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001824 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001825 LHSExp->getType()->isEnumeralType() ||
1826 RHSExp->getType()->isRecordType() ||
1827 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001828 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001829 }
1830
Sebastian Redlf322ed62009-10-29 20:17:01 +00001831 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1832}
1833
1834
1835Action::OwningExprResult
1836Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1837 ExprArg Idx, SourceLocation RLoc) {
1838 Expr *LHSExp = static_cast<Expr*>(Base.get());
1839 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1840
Chris Lattner12d9ff62007-07-16 00:14:47 +00001841 // Perform default conversions.
1842 DefaultFunctionArrayConversion(LHSExp);
1843 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001844
Chris Lattner12d9ff62007-07-16 00:14:47 +00001845 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001846
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001848 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001849 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001851 Expr *BaseExpr, *IndexExpr;
1852 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001853 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1854 BaseExpr = LHSExp;
1855 IndexExpr = RHSExp;
1856 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001857 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001858 BaseExpr = LHSExp;
1859 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001860 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001861 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001862 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001863 BaseExpr = RHSExp;
1864 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001865 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001866 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001867 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001868 BaseExpr = LHSExp;
1869 IndexExpr = RHSExp;
1870 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001871 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001872 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001873 // Handle the uncommon case of "123[Ptr]".
1874 BaseExpr = RHSExp;
1875 IndexExpr = LHSExp;
1876 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001877 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001878 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001879 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001880
Chris Lattner12d9ff62007-07-16 00:14:47 +00001881 // FIXME: need to deal with const...
1882 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001883 } else if (LHSTy->isArrayType()) {
1884 // If we see an array that wasn't promoted by
1885 // DefaultFunctionArrayConversion, it must be an array that
1886 // wasn't promoted because of the C90 rule that doesn't
1887 // allow promoting non-lvalue arrays. Warn, then
1888 // force the promotion here.
1889 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1890 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001891 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1892 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001893 LHSTy = LHSExp->getType();
1894
1895 BaseExpr = LHSExp;
1896 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001897 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001898 } else if (RHSTy->isArrayType()) {
1899 // Same as previous, except for 123[f().a] case
1900 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1901 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001902 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1903 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001904 RHSTy = RHSExp->getType();
1905
1906 BaseExpr = RHSExp;
1907 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001908 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001910 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1911 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001912 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001914 if (!(IndexExpr->getType()->isIntegerType() &&
1915 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001916 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1917 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001918
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001919 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001920 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1921 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001922 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1923
Douglas Gregore7450f52009-03-24 19:52:54 +00001924 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001925 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1926 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001927 // incomplete types are not object types.
1928 if (ResultType->isFunctionType()) {
1929 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1930 << ResultType << BaseExpr->getSourceRange();
1931 return ExprError();
1932 }
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Douglas Gregore7450f52009-03-24 19:52:54 +00001934 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001935 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001936 PDiag(diag::err_subscript_incomplete_type)
1937 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001938 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Chris Lattner1efaa952009-04-24 00:30:45 +00001940 // Diagnose bad cases where we step over interface counts.
1941 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1942 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1943 << ResultType << BaseExpr->getSourceRange();
1944 return ExprError();
1945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Sebastian Redl0eb23302009-01-19 00:08:26 +00001947 Base.release();
1948 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001949 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001950 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001951}
1952
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001953QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001954CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001955 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001956 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001957 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1958 // see FIXME there.
1959 //
1960 // FIXME: This logic can be greatly simplified by splitting it along
1961 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001962 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001963
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001964 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001965 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001966
Mike Stumpeed9cac2009-02-19 03:04:26 +00001967 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001968 // special names that indicate a subset of exactly half the elements are
1969 // to be selected.
1970 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001971
Nate Begeman353417a2009-01-18 01:47:54 +00001972 // This flag determines whether or not CompName has an 's' char prefix,
1973 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001974 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001975
1976 // Check that we've found one of the special components, or that the component
1977 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001978 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001979 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1980 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001981 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001982 do
1983 compStr++;
1984 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001985 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001986 do
1987 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001988 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001989 }
Nate Begeman353417a2009-01-18 01:47:54 +00001990
Mike Stumpeed9cac2009-02-19 03:04:26 +00001991 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001992 // We didn't get to the end of the string. This means the component names
1993 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001994 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1995 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001996 return QualType();
1997 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001998
Nate Begeman353417a2009-01-18 01:47:54 +00001999 // Ensure no component accessor exceeds the width of the vector type it
2000 // operates on.
2001 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002002 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002003
2004 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002005 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002006
2007 while (*compStr) {
2008 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2009 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2010 << baseType << SourceRange(CompLoc);
2011 return QualType();
2012 }
2013 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002014 }
Nate Begeman8a997642008-05-09 06:41:27 +00002015
Nate Begeman353417a2009-01-18 01:47:54 +00002016 // If this is a halving swizzle, verify that the base type has an even
2017 // number of elements.
2018 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002019 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00002020 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00002021 return QualType();
2022 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002023
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002024 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002025 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002026 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002027 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002028 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00002029 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002030 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002031 if (HexSwizzle)
2032 CompSize--;
2033
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002034 if (CompSize == 1)
2035 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002036
Nate Begeman213541a2008-04-18 23:10:10 +00002037 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002038 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002039 // diagostics look bad. We want extended vector types to appear built-in.
2040 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2041 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2042 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002043 }
2044 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002045}
2046
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002047static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002048 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002049 const Selector &Sel,
2050 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Anders Carlsson8f28f992009-08-26 18:25:21 +00002052 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002053 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002054 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002055 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002057 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2058 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002059 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002060 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002061 return D;
2062 }
2063 return 0;
2064}
2065
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002066static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002067 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002068 const Selector &Sel,
2069 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002070 // Check protocols on qualified interfaces.
2071 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002072 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002073 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002074 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002075 GDecl = PD;
2076 break;
2077 }
2078 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002079 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002080 GDecl = OMD;
2081 break;
2082 }
2083 }
2084 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002085 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002086 E = QIdTy->qual_end(); I != E; ++I) {
2087 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002088 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002089 if (GDecl)
2090 return GDecl;
2091 }
2092 }
2093 return GDecl;
2094}
Chris Lattner76a642f2009-02-15 22:43:40 +00002095
John McCall129e2df2009-11-30 22:42:35 +00002096Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002097Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2098 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002099 const CXXScopeSpec &SS,
2100 NamedDecl *FirstQualifierInScope,
2101 DeclarationName Name, SourceLocation NameLoc,
2102 const TemplateArgumentListInfo *TemplateArgs) {
2103 Expr *BaseExpr = Base.takeAs<Expr>();
2104
2105 // Even in dependent contexts, try to diagnose base expressions with
2106 // obviously wrong types, e.g.:
2107 //
2108 // T* t;
2109 // t.f;
2110 //
2111 // In Obj-C++, however, the above expression is valid, since it could be
2112 // accessing the 'f' property if T is an Obj-C interface. The extra check
2113 // allows this, while still reporting an error if T is a struct pointer.
2114 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002115 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002116 if (PT && (!getLangOptions().ObjC1 ||
2117 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002118 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002119 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002120 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002121 return ExprError();
2122 }
2123 }
2124
John McCallaa81e162009-12-01 22:10:20 +00002125 assert(BaseType->isDependentType());
John McCall129e2df2009-11-30 22:42:35 +00002126
2127 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2128 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002129 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002130 IsArrow, OpLoc,
2131 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2132 SS.getRange(),
2133 FirstQualifierInScope,
2134 Name, NameLoc,
2135 TemplateArgs));
2136}
2137
2138/// We know that the given qualified member reference points only to
2139/// declarations which do not belong to the static type of the base
2140/// expression. Diagnose the problem.
2141static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2142 Expr *BaseExpr,
2143 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002144 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002145 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002146 // If this is an implicit member access, use a different set of
2147 // diagnostics.
2148 if (!BaseExpr)
2149 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002150
2151 // FIXME: this is an exceedingly lame diagnostic for some of the more
2152 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002153 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002154 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002155 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002156}
2157
2158// Check whether the declarations we found through a nested-name
2159// specifier in a member expression are actually members of the base
2160// type. The restriction here is:
2161//
2162// C++ [expr.ref]p2:
2163// ... In these cases, the id-expression shall name a
2164// member of the class or of one of its base classes.
2165//
2166// So it's perfectly legitimate for the nested-name specifier to name
2167// an unrelated class, and for us to find an overload set including
2168// decls from classes which are not superclasses, as long as the decl
2169// we actually pick through overload resolution is from a superclass.
2170bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2171 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002172 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002173 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002174 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2175 if (!BaseRT) {
2176 // We can't check this yet because the base type is still
2177 // dependent.
2178 assert(BaseType->isDependentType());
2179 return false;
2180 }
2181 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002182
2183 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002184 // If this is an implicit member reference and we find a
2185 // non-instance member, it's not an error.
2186 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2187 return false;
John McCall129e2df2009-11-30 22:42:35 +00002188
John McCallaa81e162009-12-01 22:10:20 +00002189 // Note that we use the DC of the decl, not the underlying decl.
2190 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2191 while (RecordD->isAnonymousStructOrUnion())
2192 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2193
2194 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2195 MemberRecord.insert(RecordD->getCanonicalDecl());
2196
2197 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2198 return false;
2199 }
2200
John McCall2f841ba2009-12-02 03:53:29 +00002201 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002202 return true;
2203}
2204
2205static bool
2206LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2207 SourceRange BaseRange, const RecordType *RTy,
2208 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2209 RecordDecl *RDecl = RTy->getDecl();
2210 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2211 PDiag(diag::err_typecheck_incomplete_tag)
2212 << BaseRange))
2213 return true;
2214
2215 DeclContext *DC = RDecl;
2216 if (SS.isSet()) {
2217 // If the member name was a qualified-id, look into the
2218 // nested-name-specifier.
2219 DC = SemaRef.computeDeclContext(SS, false);
2220
John McCall2f841ba2009-12-02 03:53:29 +00002221 if (SemaRef.RequireCompleteDeclContext(SS)) {
2222 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2223 << SS.getRange() << DC;
2224 return true;
2225 }
2226
John McCallaa81e162009-12-01 22:10:20 +00002227 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2228
2229 if (!isa<TypeDecl>(DC)) {
2230 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2231 << DC << SS.getRange();
2232 return true;
John McCall129e2df2009-11-30 22:42:35 +00002233 }
2234 }
2235
John McCallaa81e162009-12-01 22:10:20 +00002236 // The record definition is complete, now look up the member.
2237 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002238
2239 return false;
2240}
2241
2242Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002243Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002244 SourceLocation OpLoc, bool IsArrow,
2245 const CXXScopeSpec &SS,
2246 NamedDecl *FirstQualifierInScope,
2247 DeclarationName Name, SourceLocation NameLoc,
2248 const TemplateArgumentListInfo *TemplateArgs) {
2249 Expr *Base = BaseArg.takeAs<Expr>();
2250
John McCall2f841ba2009-12-02 03:53:29 +00002251 if (BaseType->isDependentType() ||
2252 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002253 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002254 IsArrow, OpLoc,
2255 SS, FirstQualifierInScope,
2256 Name, NameLoc,
2257 TemplateArgs);
2258
2259 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002260
John McCallaa81e162009-12-01 22:10:20 +00002261 // Implicit member accesses.
2262 if (!Base) {
2263 QualType RecordTy = BaseType;
2264 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2265 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2266 RecordTy->getAs<RecordType>(),
2267 OpLoc, SS))
2268 return ExprError();
2269
2270 // Explicit member accesses.
2271 } else {
2272 OwningExprResult Result =
2273 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2274 SS, FirstQualifierInScope,
2275 /*ObjCImpDecl*/ DeclPtrTy());
2276
2277 if (Result.isInvalid()) {
2278 Owned(Base);
2279 return ExprError();
2280 }
2281
2282 if (Result.get())
2283 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002284 }
2285
John McCallaa81e162009-12-01 22:10:20 +00002286 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2287 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002288}
2289
2290Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002291Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2292 SourceLocation OpLoc, bool IsArrow,
2293 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002294 LookupResult &R,
2295 const TemplateArgumentListInfo *TemplateArgs) {
2296 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002297 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002298 if (IsArrow) {
2299 assert(BaseType->isPointerType());
2300 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2301 }
2302
2303 NestedNameSpecifier *Qualifier =
2304 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2305 DeclarationName MemberName = R.getLookupName();
2306 SourceLocation MemberLoc = R.getNameLoc();
2307
2308 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002309 return ExprError();
2310
John McCall129e2df2009-11-30 22:42:35 +00002311 if (R.empty()) {
2312 // Rederive where we looked up.
2313 DeclContext *DC = (SS.isSet()
2314 ? computeDeclContext(SS, false)
2315 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002316
John McCall129e2df2009-11-30 22:42:35 +00002317 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002318 << MemberName << DC
2319 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002320 return ExprError();
2321 }
2322
John McCall2f841ba2009-12-02 03:53:29 +00002323 // Diagnose qualified lookups that find only declarations from a
2324 // non-base type. Note that it's okay for lookup to find
2325 // declarations from a non-base type as long as those aren't the
2326 // ones picked by overload resolution.
2327 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002328 return ExprError();
2329
2330 // Construct an unresolved result if we in fact got an unresolved
2331 // result.
2332 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002333 bool Dependent =
2334 R.isUnresolvableResult() ||
2335 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002336
2337 UnresolvedMemberExpr *MemExpr
2338 = UnresolvedMemberExpr::Create(Context, Dependent,
2339 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002340 BaseExpr, BaseExprType,
2341 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002342 Qualifier, SS.getRange(),
2343 MemberName, MemberLoc,
2344 TemplateArgs);
2345 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2346 MemExpr->addDecl(*I);
2347
2348 return Owned(MemExpr);
2349 }
2350
2351 assert(R.isSingleResult());
2352 NamedDecl *MemberDecl = R.getFoundDecl();
2353
2354 // FIXME: diagnose the presence of template arguments now.
2355
2356 // If the decl being referenced had an error, return an error for this
2357 // sub-expr without emitting another error, in order to avoid cascading
2358 // error cases.
2359 if (MemberDecl->isInvalidDecl())
2360 return ExprError();
2361
John McCallaa81e162009-12-01 22:10:20 +00002362 // Handle the implicit-member-access case.
2363 if (!BaseExpr) {
2364 // If this is not an instance member, convert to a non-member access.
2365 if (!IsInstanceMember(MemberDecl))
2366 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2367
2368 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2369 }
2370
John McCall129e2df2009-11-30 22:42:35 +00002371 bool ShouldCheckUse = true;
2372 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2373 // Don't diagnose the use of a virtual member function unless it's
2374 // explicitly qualified.
2375 if (MD->isVirtual() && !SS.isSet())
2376 ShouldCheckUse = false;
2377 }
2378
2379 // Check the use of this member.
2380 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2381 Owned(BaseExpr);
2382 return ExprError();
2383 }
2384
2385 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2386 // We may have found a field within an anonymous union or struct
2387 // (C++ [class.union]).
2388 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
2389 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2390 BaseExpr, OpLoc);
2391
2392 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2393 QualType MemberType = FD->getType();
2394 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2395 MemberType = Ref->getPointeeType();
2396 else {
2397 Qualifiers BaseQuals = BaseType.getQualifiers();
2398 BaseQuals.removeObjCGCAttr();
2399 if (FD->isMutable()) BaseQuals.removeConst();
2400
2401 Qualifiers MemberQuals
2402 = Context.getCanonicalType(MemberType).getQualifiers();
2403
2404 Qualifiers Combined = BaseQuals + MemberQuals;
2405 if (Combined != MemberQuals)
2406 MemberType = Context.getQualifiedType(MemberType, Combined);
2407 }
2408
2409 MarkDeclarationReferenced(MemberLoc, FD);
2410 if (PerformObjectMemberConversion(BaseExpr, FD))
2411 return ExprError();
2412 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2413 FD, MemberLoc, MemberType));
2414 }
2415
2416 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2417 MarkDeclarationReferenced(MemberLoc, Var);
2418 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2419 Var, MemberLoc,
2420 Var->getType().getNonReferenceType()));
2421 }
2422
2423 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2424 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2425 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2426 MemberFn, MemberLoc,
2427 MemberFn->getType()));
2428 }
2429
2430 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2431 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2432 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2433 Enum, MemberLoc, Enum->getType()));
2434 }
2435
2436 Owned(BaseExpr);
2437
2438 if (isa<TypeDecl>(MemberDecl))
2439 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2440 << MemberName << int(IsArrow));
2441
2442 // We found a declaration kind that we didn't expect. This is a
2443 // generic error message that tells the user that she can't refer
2444 // to this member with '.' or '->'.
2445 return ExprError(Diag(MemberLoc,
2446 diag::err_typecheck_member_reference_unknown)
2447 << MemberName << int(IsArrow));
2448}
2449
2450/// Look up the given member of the given non-type-dependent
2451/// expression. This can return in one of two ways:
2452/// * If it returns a sentinel null-but-valid result, the caller will
2453/// assume that lookup was performed and the results written into
2454/// the provided structure. It will take over from there.
2455/// * Otherwise, the returned expression will be produced in place of
2456/// an ordinary member expression.
2457///
2458/// The ObjCImpDecl bit is a gross hack that will need to be properly
2459/// fixed for ObjC++.
2460Sema::OwningExprResult
2461Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
2462 bool IsArrow, SourceLocation OpLoc,
2463 const CXXScopeSpec &SS,
2464 NamedDecl *FirstQualifierInScope,
2465 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002466 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002467
Steve Naroff3cc4af82007-12-16 21:42:28 +00002468 // Perform default conversions.
2469 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002470
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002471 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002472 assert(!BaseType->isDependentType());
2473
2474 DeclarationName MemberName = R.getLookupName();
2475 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002476
2477 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002478 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002479 // function. Suggest the addition of those parentheses, build the
2480 // call, and continue on.
2481 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2482 if (const FunctionProtoType *Fun
2483 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2484 QualType ResultTy = Fun->getResultType();
2485 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002486 ((!IsArrow && ResultTy->isRecordType()) ||
2487 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002488 ResultTy->getAs<PointerType>()->getPointeeType()
2489 ->isRecordType()))) {
2490 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2491 Diag(Loc, diag::err_member_reference_needs_call)
2492 << QualType(Fun, 0)
2493 << CodeModificationHint::CreateInsertion(Loc, "()");
2494
2495 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002496 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002497 MultiExprArg(*this, 0, 0), 0, Loc);
2498 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002499 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002500
2501 BaseExpr = NewBase.takeAs<Expr>();
2502 DefaultFunctionArrayConversion(BaseExpr);
2503 BaseType = BaseExpr->getType();
2504 }
2505 }
2506 }
2507
David Chisnall0f436562009-08-17 16:35:33 +00002508 // If this is an Objective-C pseudo-builtin and a definition is provided then
2509 // use that.
2510 if (BaseType->isObjCIdType()) {
2511 // We have an 'id' type. Rather than fall through, we check if this
2512 // is a reference to 'isa'.
2513 if (BaseType != Context.ObjCIdRedefinitionType) {
2514 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002515 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002516 }
David Chisnall0f436562009-08-17 16:35:33 +00002517 }
John McCall129e2df2009-11-30 22:42:35 +00002518
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002519 // If this is an Objective-C pseudo-builtin and a definition is provided then
2520 // use that.
2521 if (Context.isObjCSelType(BaseType)) {
2522 // We have an 'SEL' type. Rather than fall through, we check if this
2523 // is a reference to 'sel_id'.
2524 if (BaseType != Context.ObjCSelRedefinitionType) {
2525 BaseType = Context.ObjCSelRedefinitionType;
2526 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2527 }
2528 }
John McCall129e2df2009-11-30 22:42:35 +00002529
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002530 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002531
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002532 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002533 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002534 // Also must look for a getter name which uses property syntax.
2535 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2536 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2537 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2538 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2539 ObjCMethodDecl *Getter;
2540 // FIXME: need to also look locally in the implementation.
2541 if ((Getter = IFace->lookupClassMethod(Sel))) {
2542 // Check the use of this method.
2543 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2544 return ExprError();
2545 }
2546 // If we found a getter then this may be a valid dot-reference, we
2547 // will look for the matching setter, in case it is needed.
2548 Selector SetterSel =
2549 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2550 PP.getSelectorTable(), Member);
2551 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2552 if (!Setter) {
2553 // If this reference is in an @implementation, also check for 'private'
2554 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002555 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002556 }
2557 // Look through local category implementations associated with the class.
2558 if (!Setter)
2559 Setter = IFace->getCategoryClassMethod(SetterSel);
2560
2561 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2562 return ExprError();
2563
2564 if (Getter || Setter) {
2565 QualType PType;
2566
2567 if (Getter)
2568 PType = Getter->getResultType();
2569 else
2570 // Get the expression type from Setter's incoming parameter.
2571 PType = (*(Setter->param_end() -1))->getType();
2572 // FIXME: we must check that the setter has property type.
2573 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2574 PType,
2575 Setter, MemberLoc, BaseExpr));
2576 }
2577 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2578 << MemberName << BaseType);
2579 }
2580 }
2581
2582 if (BaseType->isObjCClassType() &&
2583 BaseType != Context.ObjCClassRedefinitionType) {
2584 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002585 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002586 }
Mike Stump1eb44332009-09-09 15:08:12 +00002587
John McCall129e2df2009-11-30 22:42:35 +00002588 if (IsArrow) {
2589 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002590 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002591 else if (BaseType->isObjCObjectPointerType())
2592 ;
John McCall129e2df2009-11-30 22:42:35 +00002593 else {
2594 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2595 << BaseType << BaseExpr->getSourceRange();
2596 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002597 }
John McCall129e2df2009-11-30 22:42:35 +00002598 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002599
John McCall129e2df2009-11-30 22:42:35 +00002600 // Handle field access to simple records. This also handles access
2601 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002602 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002603 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2604 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002605 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002606 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002607 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002608
Douglas Gregora71d8192009-09-04 17:36:40 +00002609 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2610 // into a record type was handled above, any destructor we see here is a
2611 // pseudo-destructor.
2612 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2613 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002614 // The left hand side of the dot operator shall be of scalar type. The
2615 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002616 // type.
2617 if (!BaseType->isScalarType())
2618 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2619 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002620
Douglas Gregora71d8192009-09-04 17:36:40 +00002621 // [...] The type designated by the pseudo-destructor-name shall be the
2622 // same as the object type.
2623 if (!MemberName.getCXXNameType()->isDependentType() &&
2624 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2625 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2626 << BaseType << MemberName.getCXXNameType()
2627 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002628
2629 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002630 // the form
2631 //
Mike Stump1eb44332009-09-09 15:08:12 +00002632 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2633 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002634 // shall designate the same scalar type.
2635 //
2636 // FIXME: DPG can't see any way to trigger this particular clause, so it
2637 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Douglas Gregora71d8192009-09-04 17:36:40 +00002639 // FIXME: We've lost the precise spelling of the type by going through
2640 // DeclarationName. Can we do better?
2641 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002642 IsArrow, OpLoc,
2643 (NestedNameSpecifier *) SS.getScopeRep(),
2644 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002645 MemberName.getCXXNameType(),
2646 MemberLoc));
2647 }
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Chris Lattnera38e6b12008-07-21 04:59:05 +00002649 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2650 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002651 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2652 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002653 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002654 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002655 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002656 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002657 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2658
Steve Naroffc70e8d92009-07-16 00:25:06 +00002659 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2660 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002661 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Steve Naroffc70e8d92009-07-16 00:25:06 +00002663 if (IV) {
2664 // If the decl being referenced had an error, return an error for this
2665 // sub-expr without emitting another error, in order to avoid cascading
2666 // error cases.
2667 if (IV->isInvalidDecl())
2668 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002669
Steve Naroffc70e8d92009-07-16 00:25:06 +00002670 // Check whether we can reference this field.
2671 if (DiagnoseUseOfDecl(IV, MemberLoc))
2672 return ExprError();
2673 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2674 IV->getAccessControl() != ObjCIvarDecl::Package) {
2675 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2676 if (ObjCMethodDecl *MD = getCurMethodDecl())
2677 ClassOfMethodDecl = MD->getClassInterface();
2678 else if (ObjCImpDecl && getCurFunctionDecl()) {
2679 // Case of a c-function declared inside an objc implementation.
2680 // FIXME: For a c-style function nested inside an objc implementation
2681 // class, there is no implementation context available, so we pass
2682 // down the context as argument to this routine. Ideally, this context
2683 // need be passed down in the AST node and somehow calculated from the
2684 // AST for a function decl.
2685 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002686 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002687 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2688 ClassOfMethodDecl = IMPD->getClassInterface();
2689 else if (ObjCCategoryImplDecl* CatImplClass =
2690 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2691 ClassOfMethodDecl = CatImplClass->getClassInterface();
2692 }
Mike Stump1eb44332009-09-09 15:08:12 +00002693
2694 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2695 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002696 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002697 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002698 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002699 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2700 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002701 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002702 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002703 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002704
2705 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2706 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002707 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002708 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002709 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002710 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002711 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002712 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002713 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002714 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002715 if (!IsArrow && (BaseType->isObjCIdType() ||
2716 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002717 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002718 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Steve Naroff14108da2009-07-10 23:34:53 +00002720 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002721 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002722 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2723 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2724 // Check the use of this declaration
2725 if (DiagnoseUseOfDecl(PD, MemberLoc))
2726 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Steve Naroff14108da2009-07-10 23:34:53 +00002728 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2729 MemberLoc, BaseExpr));
2730 }
2731 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2732 // Check the use of this method.
2733 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2734 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Steve Naroff14108da2009-07-10 23:34:53 +00002736 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002737 OMD->getResultType(),
2738 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002739 NULL, 0));
2740 }
2741 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002742
Steve Naroff14108da2009-07-10 23:34:53 +00002743 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002744 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002745 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002746 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2747 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002748 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00002749 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00002750 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2751 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002752 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Daniel Dunbar2307d312008-09-03 01:05:41 +00002754 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002755 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002756 // Check whether we can reference this property.
2757 if (DiagnoseUseOfDecl(PD, MemberLoc))
2758 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002759 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002760 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002761 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002762 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2763 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002764 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002765 MemberLoc, BaseExpr));
2766 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002767 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002768 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2769 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002770 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002771 // Check whether we can reference this property.
2772 if (DiagnoseUseOfDecl(PD, MemberLoc))
2773 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002774
Steve Naroff6ece14c2009-01-21 00:14:39 +00002775 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002776 MemberLoc, BaseExpr));
2777 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002778 // If that failed, look for an "implicit" property by seeing if the nullary
2779 // selector is implemented.
2780
2781 // FIXME: The logic for looking up nullary and unary selectors should be
2782 // shared with the code in ActOnInstanceMessage.
2783
Anders Carlsson8f28f992009-08-26 18:25:21 +00002784 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002785 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002786
Daniel Dunbar2307d312008-09-03 01:05:41 +00002787 // If this reference is in an @implementation, check for 'private' methods.
2788 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002789 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002790
Steve Naroff7692ed62008-10-22 19:16:27 +00002791 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002792 if (!Getter)
2793 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002794 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002795 // Check if we can reference this property.
2796 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2797 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002798 }
2799 // If we found a getter then this may be a valid dot-reference, we
2800 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002801 Selector SetterSel =
2802 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002803 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002804 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002805 if (!Setter) {
2806 // If this reference is in an @implementation, also check for 'private'
2807 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002808 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002809 }
2810 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002811 if (!Setter)
2812 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002813
Steve Naroff1ca66942009-03-11 13:48:17 +00002814 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2815 return ExprError();
2816
2817 if (Getter || Setter) {
2818 QualType PType;
2819
2820 if (Getter)
2821 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002822 else
2823 // Get the expression type from Setter's incoming parameter.
2824 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002825 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002826 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002827 Setter, MemberLoc, BaseExpr));
2828 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002829 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002830 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002831 }
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Steve Narofff242b1b2009-07-24 17:54:45 +00002833 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00002834 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002835 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002836 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002837 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2838 Context.getObjCIdType()));
2839
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002840 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002841 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002842 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002843 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2844 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002845 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002846 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002847 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002848 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002849
Douglas Gregor214f31a2009-03-27 06:00:30 +00002850 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2851 << BaseType << BaseExpr->getSourceRange();
2852
Douglas Gregor214f31a2009-03-27 06:00:30 +00002853 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002854}
2855
John McCall129e2df2009-11-30 22:42:35 +00002856static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2857 SourceLocation NameLoc,
2858 Sema::ExprArg MemExpr) {
2859 Expr *E = (Expr *) MemExpr.get();
2860 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2861 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002862 << isa<CXXPseudoDestructorExpr>(E)
2863 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2864
John McCall129e2df2009-11-30 22:42:35 +00002865 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2866 move(MemExpr),
2867 /*LPLoc*/ ExpectedLParenLoc,
2868 Sema::MultiExprArg(SemaRef, 0, 0),
2869 /*CommaLocs*/ 0,
2870 /*RPLoc*/ ExpectedLParenLoc);
2871}
2872
2873/// The main callback when the parser finds something like
2874/// expression . [nested-name-specifier] identifier
2875/// expression -> [nested-name-specifier] identifier
2876/// where 'identifier' encompasses a fairly broad spectrum of
2877/// possibilities, including destructor and operator references.
2878///
2879/// \param OpKind either tok::arrow or tok::period
2880/// \param HasTrailingLParen whether the next token is '(', which
2881/// is used to diagnose mis-uses of special members that can
2882/// only be called
2883/// \param ObjCImpDecl the current ObjC @implementation decl;
2884/// this is an ugly hack around the fact that ObjC @implementations
2885/// aren't properly put in the context chain
2886Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
2887 SourceLocation OpLoc,
2888 tok::TokenKind OpKind,
2889 const CXXScopeSpec &SS,
2890 UnqualifiedId &Id,
2891 DeclPtrTy ObjCImpDecl,
2892 bool HasTrailingLParen) {
2893 if (SS.isSet() && SS.isInvalid())
2894 return ExprError();
2895
2896 TemplateArgumentListInfo TemplateArgsBuffer;
2897
2898 // Decompose the name into its component parts.
2899 DeclarationName Name;
2900 SourceLocation NameLoc;
2901 const TemplateArgumentListInfo *TemplateArgs;
2902 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
2903 Name, NameLoc, TemplateArgs);
2904
2905 bool IsArrow = (OpKind == tok::arrow);
2906
2907 NamedDecl *FirstQualifierInScope
2908 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
2909 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
2910
2911 // This is a postfix expression, so get rid of ParenListExprs.
2912 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
2913
2914 Expr *Base = BaseArg.takeAs<Expr>();
2915 OwningExprResult Result(*this);
2916 if (Base->getType()->isDependentType()) {
John McCallaa81e162009-12-01 22:10:20 +00002917 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00002918 IsArrow, OpLoc,
2919 SS, FirstQualifierInScope,
2920 Name, NameLoc,
2921 TemplateArgs);
2922 } else {
2923 LookupResult R(*this, Name, NameLoc, LookupMemberName);
2924 if (TemplateArgs) {
2925 // Re-use the lookup done for the template name.
2926 DecomposeTemplateName(R, Id);
2927 } else {
2928 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
2929 SS, FirstQualifierInScope,
2930 ObjCImpDecl);
2931
2932 if (Result.isInvalid()) {
2933 Owned(Base);
2934 return ExprError();
2935 }
2936
2937 if (Result.get()) {
2938 // The only way a reference to a destructor can be used is to
2939 // immediately call it, which falls into this case. If the
2940 // next token is not a '(', produce a diagnostic and build the
2941 // call now.
2942 if (!HasTrailingLParen &&
2943 Id.getKind() == UnqualifiedId::IK_DestructorName)
2944 return DiagnoseDtorReference(*this, NameLoc, move(Result));
2945
2946 return move(Result);
2947 }
2948 }
2949
John McCallaa81e162009-12-01 22:10:20 +00002950 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
2951 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002952 }
2953
2954 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002955}
2956
Anders Carlsson56c5e332009-08-25 03:49:14 +00002957Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2958 FunctionDecl *FD,
2959 ParmVarDecl *Param) {
2960 if (Param->hasUnparsedDefaultArg()) {
2961 Diag (CallLoc,
2962 diag::err_use_of_default_argument_to_function_declared_later) <<
2963 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002964 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002965 diag::note_default_argument_declared_here);
2966 } else {
2967 if (Param->hasUninstantiatedDefaultArg()) {
2968 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2969
2970 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002971 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002972
Mike Stump1eb44332009-09-09 15:08:12 +00002973 InstantiatingTemplate Inst(*this, CallLoc, Param,
2974 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002975 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002976
John McCallce3ff2b2009-08-25 22:02:44 +00002977 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002978 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002979 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002980
2981 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002982 /*FIXME:EqualLoc*/
2983 UninstExpr->getSourceRange().getBegin()))
2984 return ExprError();
2985 }
Mike Stump1eb44332009-09-09 15:08:12 +00002986
Anders Carlsson56c5e332009-08-25 03:49:14 +00002987 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002988
Anders Carlsson56c5e332009-08-25 03:49:14 +00002989 // If the default expression creates temporaries, we need to
2990 // push them to the current stack of expression temporaries so they'll
2991 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002992 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002993 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002994 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002995 "Can't destroy temporaries in a default argument expr!");
2996 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2997 ExprTemporaries.push_back(E->getTemporary(I));
2998 }
2999 }
3000
3001 // We already type-checked the argument, so we know it works.
3002 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3003}
3004
Douglas Gregor88a35142008-12-22 05:46:06 +00003005/// ConvertArgumentsForCall - Converts the arguments specified in
3006/// Args/NumArgs to the parameter types of the function FDecl with
3007/// function prototype Proto. Call is the call expression itself, and
3008/// Fn is the function expression. For a C++ member function, this
3009/// routine does not attempt to convert the object argument. Returns
3010/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003011bool
3012Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003013 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003014 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003015 Expr **Args, unsigned NumArgs,
3016 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003017 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003018 // assignment, to the types of the corresponding parameter, ...
3019 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003020 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003021
Douglas Gregor88a35142008-12-22 05:46:06 +00003022 // If too few arguments are available (and we don't have default
3023 // arguments for the remaining parameters), don't make the call.
3024 if (NumArgs < NumArgsInProto) {
3025 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3026 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3027 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003028 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003029 }
3030
3031 // If too many are passed and not variadic, error on the extras and drop
3032 // them.
3033 if (NumArgs > NumArgsInProto) {
3034 if (!Proto->isVariadic()) {
3035 Diag(Args[NumArgsInProto]->getLocStart(),
3036 diag::err_typecheck_call_too_many_args)
3037 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3038 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3039 Args[NumArgs-1]->getLocEnd());
3040 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003041 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003042 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003043 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003044 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003045 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003046 VariadicCallType CallType =
3047 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3048 if (Fn->getType()->isBlockPointerType())
3049 CallType = VariadicBlock; // Block
3050 else if (isa<MemberExpr>(Fn))
3051 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003052 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003053 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003054 if (Invalid)
3055 return true;
3056 unsigned TotalNumArgs = AllArgs.size();
3057 for (unsigned i = 0; i < TotalNumArgs; ++i)
3058 Call->setArg(i, AllArgs[i]);
3059
3060 return false;
3061}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003062
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003063bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3064 FunctionDecl *FDecl,
3065 const FunctionProtoType *Proto,
3066 unsigned FirstProtoArg,
3067 Expr **Args, unsigned NumArgs,
3068 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003069 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003070 unsigned NumArgsInProto = Proto->getNumArgs();
3071 unsigned NumArgsToCheck = NumArgs;
3072 bool Invalid = false;
3073 if (NumArgs != NumArgsInProto)
3074 // Use default arguments for missing arguments
3075 NumArgsToCheck = NumArgsInProto;
3076 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003077 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003078 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003079 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003080
Douglas Gregor88a35142008-12-22 05:46:06 +00003081 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003082 if (ArgIx < NumArgs) {
3083 Arg = Args[ArgIx++];
3084
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003085 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3086 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003087 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003088 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003089 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003090
Douglas Gregor61366e92008-12-24 00:01:03 +00003091 // Pass the argument.
3092 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3093 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00003094
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00003095 if (!ProtoArgType->isReferenceType())
3096 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003097 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003098 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003099
Mike Stump1eb44332009-09-09 15:08:12 +00003100 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003101 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003102 if (ArgExpr.isInvalid())
3103 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003104
Anders Carlsson56c5e332009-08-25 03:49:14 +00003105 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003106 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003107 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003108 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003109
Douglas Gregor88a35142008-12-22 05:46:06 +00003110 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003111 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003112 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003113 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003114 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003115 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003116 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003117 }
3118 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003119 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003120}
3121
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003122/// \brief "Deconstruct" the function argument of a call expression to find
3123/// the underlying declaration (if any), the name of the called function,
3124/// whether argument-dependent lookup is available, whether it has explicit
3125/// template arguments, etc.
3126void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCallba135432009-11-21 08:51:07 +00003127 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003128 DeclarationName &Name,
3129 NestedNameSpecifier *&Qualifier,
3130 SourceRange &QualifierRange,
3131 bool &ArgumentDependentLookup,
John McCall7453ed42009-11-22 00:44:51 +00003132 bool &Overloaded,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003133 bool &HasExplicitTemplateArguments,
John McCalld5532b62009-11-23 01:53:49 +00003134 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003135 // Set defaults for all of the output parameters.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003136 Name = DeclarationName();
3137 Qualifier = 0;
3138 QualifierRange = SourceRange();
John McCallf7a1a742009-11-24 19:00:30 +00003139 ArgumentDependentLookup = false;
John McCall7453ed42009-11-22 00:44:51 +00003140 Overloaded = false;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003141 HasExplicitTemplateArguments = false;
John McCall7453ed42009-11-22 00:44:51 +00003142
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003143 // If we're directly calling a function, get the appropriate declaration.
3144 // Also, in C++, keep track of whether we should perform argument-dependent
3145 // lookup and whether there were any explicitly-specified template arguments.
3146 while (true) {
3147 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
3148 FnExpr = IcExpr->getSubExpr();
3149 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003150 FnExpr = PExpr->getSubExpr();
3151 } else if (isa<UnaryOperator>(FnExpr) &&
3152 cast<UnaryOperator>(FnExpr)->getOpcode()
3153 == UnaryOperator::AddrOf) {
3154 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003155 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00003156 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
3157 ArgumentDependentLookup = false;
3158 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregora2813ce2009-10-23 18:54:35 +00003159 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003160 break;
John McCallba135432009-11-21 08:51:07 +00003161 } else if (UnresolvedLookupExpr *UnresLookup
3162 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
3163 Name = UnresLookup->getName();
3164 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
3165 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall7453ed42009-11-22 00:44:51 +00003166 Overloaded = UnresLookup->isOverloaded();
John McCallba135432009-11-21 08:51:07 +00003167 if ((Qualifier = UnresLookup->getQualifier()))
3168 QualifierRange = UnresLookup->getQualifierRange();
John McCallf7a1a742009-11-24 19:00:30 +00003169 if (UnresLookup->hasExplicitTemplateArgs()) {
3170 HasExplicitTemplateArguments = true;
3171 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003172 }
3173 break;
3174 } else {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003175 break;
3176 }
3177 }
3178}
3179
Steve Narofff69936d2007-09-16 03:34:24 +00003180/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003181/// This provides the location of the left/right parens and a list of comma
3182/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003183Action::OwningExprResult
3184Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3185 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003186 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003187 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003188
3189 // Since this might be a postfix expression, get rid of ParenListExprs.
3190 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003191
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003192 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003193 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003194 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003195
Douglas Gregor88a35142008-12-22 05:46:06 +00003196 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003197 // If this is a pseudo-destructor expression, build the call immediately.
3198 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3199 if (NumArgs > 0) {
3200 // Pseudo-destructor calls should not have any arguments.
3201 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3202 << CodeModificationHint::CreateRemoval(
3203 SourceRange(Args[0]->getLocStart(),
3204 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003205
Douglas Gregora71d8192009-09-04 17:36:40 +00003206 for (unsigned I = 0; I != NumArgs; ++I)
3207 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003208
Douglas Gregora71d8192009-09-04 17:36:40 +00003209 NumArgs = 0;
3210 }
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Douglas Gregora71d8192009-09-04 17:36:40 +00003212 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3213 RParenLoc));
3214 }
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Douglas Gregor17330012009-02-04 15:01:18 +00003216 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003217 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003218 // FIXME: Will need to cache the results of name lookup (including ADL) in
3219 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003220 bool Dependent = false;
3221 if (Fn->isTypeDependent())
3222 Dependent = true;
3223 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3224 Dependent = true;
3225
3226 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003227 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003228 Context.DependentTy, RParenLoc));
3229
3230 // Determine whether this is a call to an object (C++ [over.call.object]).
3231 if (Fn->getType()->isRecordType())
3232 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3233 CommaLocs, RParenLoc));
3234
John McCall129e2df2009-11-30 22:42:35 +00003235 Expr *NakedFn = Fn->IgnoreParens();
3236
3237 // Determine whether this is a call to an unresolved member function.
3238 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3239 // If lookup was unresolved but not dependent (i.e. didn't find
3240 // an unresolved using declaration), it has to be an overloaded
3241 // function set, which means it must contain either multiple
3242 // declarations (all methods or method templates) or a single
3243 // method template.
3244 assert((MemE->getNumDecls() > 1) ||
3245 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003246 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003247
John McCallaa81e162009-12-01 22:10:20 +00003248 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3249 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003250 }
3251
Douglas Gregorfa047642009-02-04 00:32:51 +00003252 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003253 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003254 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003255 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003256 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3257 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003258 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003259
3260 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003261 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003262 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3263 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003264 if (const FunctionProtoType *FPT =
3265 dyn_cast<FunctionProtoType>(BO->getType())) {
3266 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003267
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003268 ExprOwningPtr<CXXMemberCallExpr>
3269 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3270 NumArgs, ResultTy,
3271 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003272
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003273 if (CheckCallReturnType(FPT->getResultType(),
3274 BO->getRHS()->getSourceRange().getBegin(),
3275 TheCall.get(), 0))
3276 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003277
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003278 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3279 RParenLoc))
3280 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003281
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003282 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3283 }
3284 return ExprError(Diag(Fn->getLocStart(),
3285 diag::err_typecheck_call_not_function)
3286 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003287 }
3288 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003289 }
3290
Douglas Gregorfa047642009-02-04 00:32:51 +00003291 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003292 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003293 // lookup and whether there were any explicitly-specified template arguments.
John McCallba135432009-11-21 08:51:07 +00003294 llvm::SmallVector<NamedDecl*,8> Fns;
3295 DeclarationName UnqualifiedName;
John McCall7453ed42009-11-22 00:44:51 +00003296 bool Overloaded;
3297 bool ADL;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003298 bool HasExplicitTemplateArgs = 0;
John McCalld5532b62009-11-23 01:53:49 +00003299 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003300 NestedNameSpecifier *Qualifier = 0;
3301 SourceRange QualifierRange;
John McCallba135432009-11-21 08:51:07 +00003302 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00003303 ADL, Overloaded, HasExplicitTemplateArgs,
John McCalld5532b62009-11-23 01:53:49 +00003304 ExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003305
John McCall7453ed42009-11-22 00:44:51 +00003306 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
3307 FunctionDecl *FDecl; // same, if it's known to be a function
John McCallba135432009-11-21 08:51:07 +00003308
John McCall7453ed42009-11-22 00:44:51 +00003309 if (Overloaded || ADL) {
3310#ifndef NDEBUG
3311 if (ADL) {
3312 // To do ADL, we must have found an unqualified name.
3313 assert(UnqualifiedName && "found no unqualified name for ADL");
3314
3315 // We don't perform ADL for implicit declarations of builtins.
3316 // Verify that this was correctly set up.
3317 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
3318 FDecl->getBuiltinID() && FDecl->isImplicit())
3319 assert(0 && "performing ADL for builtin");
3320
3321 // We don't perform ADL in C.
3322 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
3323 }
3324
3325 if (Overloaded) {
3326 // To be overloaded, we must either have multiple functions or
3327 // at least one function template (which is effectively an
3328 // infinite set of functions).
3329 assert((Fns.size() > 1 ||
3330 (Fns.size() == 1 &&
3331 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
3332 && "unrecognized overload situation");
3333 }
3334#endif
3335
3336 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00003337 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall7453ed42009-11-22 00:44:51 +00003338 LParenLoc, Args, NumArgs, CommaLocs,
3339 RParenLoc, ADL);
3340 if (!FDecl)
3341 return ExprError();
3342
3343 Fn = FixOverloadedFunctionReference(Fn, FDecl);
3344
3345 NDecl = FDecl;
3346 } else {
3347 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
3348 if (Fns.empty())
John McCallaa81e162009-12-01 22:10:20 +00003349 NDecl = 0;
John McCall7453ed42009-11-22 00:44:51 +00003350 else {
3351 NDecl = Fns[0];
Douglas Gregorfa047642009-02-04 00:32:51 +00003352 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003353 }
Chris Lattner04421082008-04-08 04:40:51 +00003354
John McCallaa81e162009-12-01 22:10:20 +00003355 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3356}
3357
3358/// BuildCallExpr - Build a call to a resolved expression, i.e. an
3359/// expression not of \p OverloadTy. The expression should
3360/// unary-convert to an expression of function-pointer or
3361/// block-pointer type.
3362///
3363/// \param NDecl the declaration being called, if available
3364Sema::OwningExprResult
3365Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3366 SourceLocation LParenLoc,
3367 Expr **Args, unsigned NumArgs,
3368 SourceLocation RParenLoc) {
3369 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3370
Chris Lattner04421082008-04-08 04:40:51 +00003371 // Promote the function operand.
3372 UsualUnaryConversions(Fn);
3373
Chris Lattner925e60d2007-12-28 05:29:59 +00003374 // Make the call expr early, before semantic checks. This guarantees cleanup
3375 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003376 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3377 Args, NumArgs,
3378 Context.BoolTy,
3379 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003380
Steve Naroffdd972f22008-09-05 22:11:13 +00003381 const FunctionType *FuncT;
3382 if (!Fn->getType()->isBlockPointerType()) {
3383 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3384 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003385 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003386 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003387 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3388 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003389 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003390 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003391 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003392 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003393 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003394 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003395 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3396 << Fn->getType() << Fn->getSourceRange());
3397
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003398 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003399 if (CheckCallReturnType(FuncT->getResultType(),
3400 Fn->getSourceRange().getBegin(), TheCall.get(),
3401 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003402 return ExprError();
3403
Chris Lattner925e60d2007-12-28 05:29:59 +00003404 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003405 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003406
Douglas Gregor72564e72009-02-26 23:50:07 +00003407 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003408 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003409 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003410 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003411 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003412 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003413
Douglas Gregor74734d52009-04-02 15:37:10 +00003414 if (FDecl) {
3415 // Check if we have too few/too many template arguments, based
3416 // on our knowledge of the function definition.
3417 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003418 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003419 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003420 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003421 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3422 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3423 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3424 }
3425 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003426 }
3427
Steve Naroffb291ab62007-08-28 23:30:39 +00003428 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003429 for (unsigned i = 0; i != NumArgs; i++) {
3430 Expr *Arg = Args[i];
3431 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003432 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3433 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003434 PDiag(diag::err_call_incomplete_argument)
3435 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003436 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003437 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003438 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003439 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003440
Douglas Gregor88a35142008-12-22 05:46:06 +00003441 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3442 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003443 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3444 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003445
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003446 // Check for sentinels
3447 if (NDecl)
3448 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Chris Lattner59907c42007-08-10 20:18:51 +00003450 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003451 if (FDecl) {
3452 if (CheckFunctionCall(FDecl, TheCall.get()))
3453 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003455 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003456 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3457 } else if (NDecl) {
3458 if (CheckBlockCall(NDecl, TheCall.get()))
3459 return ExprError();
3460 }
Chris Lattner59907c42007-08-10 20:18:51 +00003461
Anders Carlssonec74c592009-08-16 03:06:32 +00003462 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003463}
3464
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003465Action::OwningExprResult
3466Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3467 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003468 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003469 //FIXME: Preserve type source info.
3470 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003471 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003472 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003473 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003474
Eli Friedman6223c222008-05-20 05:22:08 +00003475 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003476 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003477 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3478 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003479 } else if (!literalType->isDependentType() &&
3480 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003481 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003482 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003483 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003484 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003485
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003486 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003487 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003488 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003489
Chris Lattner371f2582008-12-04 23:50:19 +00003490 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003491 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003492 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003493 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003494 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003495 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003496 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003497 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003498}
3499
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003500Action::OwningExprResult
3501Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003502 SourceLocation RBraceLoc) {
3503 unsigned NumInit = initlist.size();
3504 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003505
Steve Naroff08d92e42007-09-15 18:49:24 +00003506 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003507 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003508
Mike Stumpeed9cac2009-02-19 03:04:26 +00003509 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003510 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003511 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003512 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003513}
3514
Anders Carlsson82debc72009-10-18 18:12:03 +00003515static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3516 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003517 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003518 return CastExpr::CK_NoOp;
3519
3520 if (SrcTy->hasPointerRepresentation()) {
3521 if (DestTy->hasPointerRepresentation())
3522 return CastExpr::CK_BitCast;
3523 if (DestTy->isIntegerType())
3524 return CastExpr::CK_PointerToIntegral;
3525 }
3526
3527 if (SrcTy->isIntegerType()) {
3528 if (DestTy->isIntegerType())
3529 return CastExpr::CK_IntegralCast;
3530 if (DestTy->hasPointerRepresentation())
3531 return CastExpr::CK_IntegralToPointer;
3532 if (DestTy->isRealFloatingType())
3533 return CastExpr::CK_IntegralToFloating;
3534 }
3535
3536 if (SrcTy->isRealFloatingType()) {
3537 if (DestTy->isRealFloatingType())
3538 return CastExpr::CK_FloatingCast;
3539 if (DestTy->isIntegerType())
3540 return CastExpr::CK_FloatingToIntegral;
3541 }
3542
3543 // FIXME: Assert here.
3544 // assert(false && "Unhandled cast combination!");
3545 return CastExpr::CK_Unknown;
3546}
3547
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003548/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003549bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003550 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003551 CXXMethodDecl *& ConversionDecl,
3552 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003553 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003554 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3555 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003556
Eli Friedman199ea952009-08-15 19:02:19 +00003557 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003558
3559 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3560 // type needs to be scalar.
3561 if (castType->isVoidType()) {
3562 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003563 Kind = CastExpr::CK_ToVoid;
3564 return false;
3565 }
3566
3567 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003568 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003569 (castType->isStructureType() || castType->isUnionType())) {
3570 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003571 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003572 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3573 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003574 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003575 return false;
3576 }
3577
3578 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003579 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003580 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003581 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003582 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003583 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003584 if (Context.hasSameUnqualifiedType(Field->getType(),
3585 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003586 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3587 << castExpr->getSourceRange();
3588 break;
3589 }
3590 }
3591 if (Field == FieldEnd)
3592 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3593 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003594 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003595 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003596 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003597
3598 // Reject any other conversions to non-scalar types.
3599 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3600 << castType << castExpr->getSourceRange();
3601 }
3602
3603 if (!castExpr->getType()->isScalarType() &&
3604 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003605 return Diag(castExpr->getLocStart(),
3606 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003607 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003608 }
3609
Anders Carlsson16a89042009-10-16 05:23:41 +00003610 if (castType->isExtVectorType())
3611 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3612
Anders Carlssonc3516322009-10-16 02:48:28 +00003613 if (castType->isVectorType())
3614 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3615 if (castExpr->getType()->isVectorType())
3616 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3617
3618 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003619 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003620
Anders Carlsson16a89042009-10-16 05:23:41 +00003621 if (isa<ObjCSelectorExpr>(castExpr))
3622 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3623
Anders Carlssonc3516322009-10-16 02:48:28 +00003624 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003625 QualType castExprType = castExpr->getType();
3626 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3627 return Diag(castExpr->getLocStart(),
3628 diag::err_cast_pointer_from_non_pointer_int)
3629 << castExprType << castExpr->getSourceRange();
3630 } else if (!castExpr->getType()->isArithmeticType()) {
3631 if (!castType->isIntegralType() && castType->isArithmeticType())
3632 return Diag(castExpr->getLocStart(),
3633 diag::err_cast_pointer_to_non_pointer_int)
3634 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003635 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003636
3637 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003638 return false;
3639}
3640
Anders Carlssonc3516322009-10-16 02:48:28 +00003641bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3642 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003643 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003644
Anders Carlssona64db8f2007-11-27 05:51:55 +00003645 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003646 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003647 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003648 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003649 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003650 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003651 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003652 } else
3653 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003654 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003655 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003656
Anders Carlssonc3516322009-10-16 02:48:28 +00003657 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003658 return false;
3659}
3660
Anders Carlsson16a89042009-10-16 05:23:41 +00003661bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3662 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003663 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003664
3665 QualType SrcTy = CastExpr->getType();
3666
Nate Begeman9b10da62009-06-27 22:05:55 +00003667 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3668 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003669 if (SrcTy->isVectorType()) {
3670 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3671 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3672 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003673 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003674 return false;
3675 }
3676
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003677 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003678 // conversion will take place first from scalar to elt type, and then
3679 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003680 if (SrcTy->isPointerType())
3681 return Diag(R.getBegin(),
3682 diag::err_invalid_conversion_between_vector_and_scalar)
3683 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003684
3685 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3686 ImpCastExprToType(CastExpr, DestElemTy,
3687 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003688
3689 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003690 return false;
3691}
3692
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003693Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003694Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003695 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003696 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003697
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003698 assert((Ty != 0) && (Op.get() != 0) &&
3699 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003700
Nate Begeman2ef13e52009-08-10 23:49:36 +00003701 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003702 //FIXME: Preserve type source info.
3703 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003704
Nate Begeman2ef13e52009-08-10 23:49:36 +00003705 // If the Expr being casted is a ParenListExpr, handle it specially.
3706 if (isa<ParenListExpr>(castExpr))
3707 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003708 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003709 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003710 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003711 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003712
3713 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003714 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003715 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003716
Anders Carlsson0aebc812009-09-09 21:33:21 +00003717 if (CastArg.isInvalid())
3718 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003719
Anders Carlsson0aebc812009-09-09 21:33:21 +00003720 castExpr = CastArg.takeAs<Expr>();
3721 } else {
3722 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003723 }
Mike Stump1eb44332009-09-09 15:08:12 +00003724
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003725 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003726 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003727 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003728}
3729
Nate Begeman2ef13e52009-08-10 23:49:36 +00003730/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3731/// of comma binary operators.
3732Action::OwningExprResult
3733Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3734 Expr *expr = EA.takeAs<Expr>();
3735 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3736 if (!E)
3737 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Nate Begeman2ef13e52009-08-10 23:49:36 +00003739 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003740
Nate Begeman2ef13e52009-08-10 23:49:36 +00003741 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3742 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3743 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Nate Begeman2ef13e52009-08-10 23:49:36 +00003745 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3746}
3747
3748Action::OwningExprResult
3749Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3750 SourceLocation RParenLoc, ExprArg Op,
3751 QualType Ty) {
3752 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003753
3754 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003755 // then handle it as such.
3756 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3757 if (PE->getNumExprs() == 0) {
3758 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3759 return ExprError();
3760 }
3761
3762 llvm::SmallVector<Expr *, 8> initExprs;
3763 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3764 initExprs.push_back(PE->getExpr(i));
3765
3766 // FIXME: This means that pretty-printing the final AST will produce curly
3767 // braces instead of the original commas.
3768 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003769 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003770 initExprs.size(), RParenLoc);
3771 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003772 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003773 Owned(E));
3774 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003775 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003776 // sequence of BinOp comma operators.
3777 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3778 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3779 }
3780}
3781
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003782Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003783 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003784 MultiExprArg Val,
3785 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003786 unsigned nexprs = Val.size();
3787 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003788 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3789 Expr *expr;
3790 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3791 expr = new (Context) ParenExpr(L, R, exprs[0]);
3792 else
3793 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003794 return Owned(expr);
3795}
3796
Sebastian Redl28507842009-02-26 14:39:58 +00003797/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3798/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003799/// C99 6.5.15
3800QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3801 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003802 // C++ is sufficiently different to merit its own checker.
3803 if (getLangOptions().CPlusPlus)
3804 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3805
John McCallb13c87f2009-11-05 09:23:39 +00003806 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3807
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003808 UsualUnaryConversions(Cond);
3809 UsualUnaryConversions(LHS);
3810 UsualUnaryConversions(RHS);
3811 QualType CondTy = Cond->getType();
3812 QualType LHSTy = LHS->getType();
3813 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003814
Reid Spencer5f016e22007-07-11 17:01:13 +00003815 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003816 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3817 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3818 << CondTy;
3819 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003820 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003821
Chris Lattner70d67a92008-01-06 22:42:25 +00003822 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003823 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3824 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003825
Chris Lattner70d67a92008-01-06 22:42:25 +00003826 // If both operands have arithmetic type, do the usual arithmetic conversions
3827 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003828 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3829 UsualArithmeticConversions(LHS, RHS);
3830 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003831 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003832
Chris Lattner70d67a92008-01-06 22:42:25 +00003833 // If both operands are the same structure or union type, the result is that
3834 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003835 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3836 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003837 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003838 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003839 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003840 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003841 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003842 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003843
Chris Lattner70d67a92008-01-06 22:42:25 +00003844 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003845 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003846 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3847 if (!LHSTy->isVoidType())
3848 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3849 << RHS->getSourceRange();
3850 if (!RHSTy->isVoidType())
3851 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3852 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003853 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3854 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003855 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003856 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003857 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3858 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003859 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003860 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003861 // promote the null to a pointer.
3862 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003863 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003864 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003865 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003866 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003867 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003868 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003869 }
David Chisnall0f436562009-08-17 16:35:33 +00003870 // Handle things like Class and struct objc_class*. Here we case the result
3871 // to the pseudo-builtin, because that will be implicitly cast back to the
3872 // redefinition type if an attempt is made to access its fields.
3873 if (LHSTy->isObjCClassType() &&
3874 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003875 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003876 return LHSTy;
3877 }
3878 if (RHSTy->isObjCClassType() &&
3879 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003880 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003881 return RHSTy;
3882 }
3883 // And the same for struct objc_object* / id
3884 if (LHSTy->isObjCIdType() &&
3885 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003886 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003887 return LHSTy;
3888 }
3889 if (RHSTy->isObjCIdType() &&
3890 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003891 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003892 return RHSTy;
3893 }
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00003894 // And the same for struct objc_selector* / SEL
3895 if (Context.isObjCSelType(LHSTy) &&
3896 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3897 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3898 return LHSTy;
3899 }
3900 if (Context.isObjCSelType(RHSTy) &&
3901 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3902 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3903 return RHSTy;
3904 }
Steve Naroff7154a772009-07-01 14:36:47 +00003905 // Handle block pointer types.
3906 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3907 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3908 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3909 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003910 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3911 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003912 return destType;
3913 }
3914 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3915 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3916 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003917 }
Steve Naroff7154a772009-07-01 14:36:47 +00003918 // We have 2 block pointer types.
3919 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3920 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003921 return LHSTy;
3922 }
Steve Naroff7154a772009-07-01 14:36:47 +00003923 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003924 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3925 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003926
Steve Naroff7154a772009-07-01 14:36:47 +00003927 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3928 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003929 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3930 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3931 // In this situation, we assume void* type. No especially good
3932 // reason, but this is what gcc does, and we do have to pick
3933 // to get a consistent AST.
3934 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003935 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3936 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003937 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003938 }
Steve Naroff7154a772009-07-01 14:36:47 +00003939 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003940 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3941 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003942 return LHSTy;
3943 }
Steve Naroff7154a772009-07-01 14:36:47 +00003944 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003945 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003946
Steve Naroff7154a772009-07-01 14:36:47 +00003947 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3948 // Two identical object pointer types are always compatible.
3949 return LHSTy;
3950 }
John McCall183700f2009-09-21 23:43:11 +00003951 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3952 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003953 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003954
Steve Naroff7154a772009-07-01 14:36:47 +00003955 // If both operands are interfaces and either operand can be
3956 // assigned to the other, use that type as the composite
3957 // type. This allows
3958 // xxx ? (A*) a : (B*) b
3959 // where B is a subclass of A.
3960 //
3961 // Additionally, as for assignment, if either type is 'id'
3962 // allow silent coercion. Finally, if the types are
3963 // incompatible then make sure to use 'id' as the composite
3964 // type so the result is acceptable for sending messages to.
3965
3966 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3967 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003968 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003969 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003970 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003971 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003972 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003973 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003974 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003975 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003976 // GCC allows qualified id and any Objective-C type to devolve to
3977 // id. Currently localizing to here until clear this should be
3978 // part of ObjCQualifiedIdTypesAreCompatible.
3979 compositeType = Context.getObjCIdType();
3980 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003981 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003982 } else if (!(compositeType =
3983 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3984 ;
3985 else {
Steve Naroff7154a772009-07-01 14:36:47 +00003986 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3987 << LHSTy << RHSTy
3988 << LHS->getSourceRange() << RHS->getSourceRange();
3989 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003990 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3991 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003992 return incompatTy;
3993 }
3994 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003995 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3996 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003997 return compositeType;
3998 }
Steve Naroffc715e782009-07-29 15:09:39 +00003999 // Check Objective-C object pointer types and 'void *'
4000 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004001 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00004002 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00004003 QualType destPointee
4004 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00004005 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004006 // Add qualifiers if necessary.
4007 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4008 // Promote to void*.
4009 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00004010 return destType;
4011 }
4012 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00004013 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004014 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00004015 QualType destPointee
4016 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00004017 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004018 // Add qualifiers if necessary.
4019 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4020 // Promote to void*.
4021 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00004022 return destType;
4023 }
Steve Naroff7154a772009-07-01 14:36:47 +00004024 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4025 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4026 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004027 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4028 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004029
4030 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4031 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4032 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004033 QualType destPointee
4034 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004035 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004036 // Add qualifiers if necessary.
4037 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4038 // Promote to void*.
4039 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004040 return destType;
4041 }
4042 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004043 QualType destPointee
4044 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004045 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004046 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004047 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004048 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004049 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004050 return destType;
4051 }
4052
4053 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4054 // Two identical pointer types are always compatible.
4055 return LHSTy;
4056 }
4057 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4058 rhptee.getUnqualifiedType())) {
4059 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4060 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4061 // In this situation, we assume void* type. No especially good
4062 // reason, but this is what gcc does, and we do have to pick
4063 // to get a consistent AST.
4064 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004065 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4066 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004067 return incompatTy;
4068 }
4069 // The pointer types are compatible.
4070 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4071 // differently qualified versions of compatible types, the result type is
4072 // a pointer to an appropriately qualified version of the *composite*
4073 // type.
4074 // FIXME: Need to calculate the composite type.
4075 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004076 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4077 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004078 return LHSTy;
4079 }
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Steve Naroff7154a772009-07-01 14:36:47 +00004081 // GCC compatibility: soften pointer/integer mismatch.
4082 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4083 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4084 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004085 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004086 return RHSTy;
4087 }
4088 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4089 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4090 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004091 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004092 return LHSTy;
4093 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004094
Chris Lattner70d67a92008-01-06 22:42:25 +00004095 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004096 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4097 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004098 return QualType();
4099}
4100
Steve Narofff69936d2007-09-16 03:34:24 +00004101/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004102/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004103Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4104 SourceLocation ColonLoc,
4105 ExprArg Cond, ExprArg LHS,
4106 ExprArg RHS) {
4107 Expr *CondExpr = (Expr *) Cond.get();
4108 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004109
4110 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4111 // was the condition.
4112 bool isLHSNull = LHSExpr == 0;
4113 if (isLHSNull)
4114 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004115
4116 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004117 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004118 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004119 return ExprError();
4120
4121 Cond.release();
4122 LHS.release();
4123 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004124 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004125 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004126 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004127}
4128
Reid Spencer5f016e22007-07-11 17:01:13 +00004129// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004130// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004131// routine is it effectively iqnores the qualifiers on the top level pointee.
4132// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4133// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004134Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004135Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4136 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004137
David Chisnall0f436562009-08-17 16:35:33 +00004138 if ((lhsType->isObjCClassType() &&
4139 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4140 (rhsType->isObjCClassType() &&
4141 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4142 return Compatible;
4143 }
4144
Reid Spencer5f016e22007-07-11 17:01:13 +00004145 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004146 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4147 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004148
Reid Spencer5f016e22007-07-11 17:01:13 +00004149 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004150 lhptee = Context.getCanonicalType(lhptee);
4151 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004152
Chris Lattner5cf216b2008-01-04 18:04:52 +00004153 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004154
4155 // C99 6.5.16.1p1: This following citation is common to constraints
4156 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4157 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004158 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004159 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004160 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004161
Mike Stumpeed9cac2009-02-19 03:04:26 +00004162 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4163 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004164 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004165 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004166 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004167 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004168
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004169 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004170 assert(rhptee->isFunctionType());
4171 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004172 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004173
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004174 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004175 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004176 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004177
4178 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004179 assert(lhptee->isFunctionType());
4180 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004181 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004182 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004183 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004184 lhptee = lhptee.getUnqualifiedType();
4185 rhptee = rhptee.getUnqualifiedType();
4186 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4187 // Check if the pointee types are compatible ignoring the sign.
4188 // We explicitly check for char so that we catch "char" vs
4189 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004190 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004191 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004192 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004193 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004194
4195 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004196 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004197 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004198 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004199
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004200 if (lhptee == rhptee) {
4201 // Types are compatible ignoring the sign. Qualifier incompatibility
4202 // takes priority over sign incompatibility because the sign
4203 // warning can be disabled.
4204 if (ConvTy != Compatible)
4205 return ConvTy;
4206 return IncompatiblePointerSign;
4207 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004208
4209 // If we are a multi-level pointer, it's possible that our issue is simply
4210 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4211 // the eventual target type is the same and the pointers have the same
4212 // level of indirection, this must be the issue.
4213 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4214 do {
4215 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4216 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4217
4218 lhptee = Context.getCanonicalType(lhptee);
4219 rhptee = Context.getCanonicalType(rhptee);
4220 } while (lhptee->isPointerType() && rhptee->isPointerType());
4221
Douglas Gregora4923eb2009-11-16 21:35:15 +00004222 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004223 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004224 }
4225
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004226 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004227 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004228 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004229 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004230}
4231
Steve Naroff1c7d0672008-09-04 15:10:53 +00004232/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4233/// block pointer types are compatible or whether a block and normal pointer
4234/// are compatible. It is more restrict than comparing two function pointer
4235// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004236Sema::AssignConvertType
4237Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004238 QualType rhsType) {
4239 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004240
Steve Naroff1c7d0672008-09-04 15:10:53 +00004241 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004242 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4243 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004244
Steve Naroff1c7d0672008-09-04 15:10:53 +00004245 // make sure we operate on the canonical type
4246 lhptee = Context.getCanonicalType(lhptee);
4247 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004248
Steve Naroff1c7d0672008-09-04 15:10:53 +00004249 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004250
Steve Naroff1c7d0672008-09-04 15:10:53 +00004251 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004252 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004253 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004254
Eli Friedman26784c12009-06-08 05:08:54 +00004255 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004256 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004257 return ConvTy;
4258}
4259
Mike Stumpeed9cac2009-02-19 03:04:26 +00004260/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4261/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004262/// pointers. Here are some objectionable examples that GCC considers warnings:
4263///
4264/// int a, *pint;
4265/// short *pshort;
4266/// struct foo *pfoo;
4267///
4268/// pint = pshort; // warning: assignment from incompatible pointer type
4269/// a = pint; // warning: assignment makes integer from pointer without a cast
4270/// pint = a; // warning: assignment makes pointer from integer without a cast
4271/// pint = pfoo; // warning: assignment from incompatible pointer type
4272///
4273/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004274/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004275///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004276Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004277Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004278 // Get canonical types. We're not formatting these types, just comparing
4279 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004280 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4281 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004282
4283 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004284 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004285
David Chisnall0f436562009-08-17 16:35:33 +00004286 if ((lhsType->isObjCClassType() &&
4287 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4288 (rhsType->isObjCClassType() &&
4289 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4290 return Compatible;
4291 }
4292
Douglas Gregor9d293df2008-10-28 00:22:11 +00004293 // If the left-hand side is a reference type, then we are in a
4294 // (rare!) case where we've allowed the use of references in C,
4295 // e.g., as a parameter type in a built-in function. In this case,
4296 // just make sure that the type referenced is compatible with the
4297 // right-hand side type. The caller is responsible for adjusting
4298 // lhsType so that the resulting expression does not have reference
4299 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004300 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004301 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004302 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004303 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004304 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004305 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4306 // to the same ExtVector type.
4307 if (lhsType->isExtVectorType()) {
4308 if (rhsType->isExtVectorType())
4309 return lhsType == rhsType ? Compatible : Incompatible;
4310 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4311 return Compatible;
4312 }
Mike Stump1eb44332009-09-09 15:08:12 +00004313
Nate Begemanbe2341d2008-07-14 18:02:46 +00004314 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004315 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004316 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004317 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004318 if (getLangOptions().LaxVectorConversions &&
4319 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004320 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004321 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004322 }
4323 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004324 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004325
Chris Lattnere8b3e962008-01-04 23:32:24 +00004326 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004327 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004328
Chris Lattner78eca282008-04-07 06:49:41 +00004329 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004330 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004331 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004332
Chris Lattner78eca282008-04-07 06:49:41 +00004333 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004334 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004335
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004336 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004337 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004338 if (lhsType->isVoidPointerType()) // an exception to the rule.
4339 return Compatible;
4340 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004341 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004342 if (rhsType->getAs<BlockPointerType>()) {
4343 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004344 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004345
4346 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004347 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004348 return Compatible;
4349 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004350 return Incompatible;
4351 }
4352
4353 if (isa<BlockPointerType>(lhsType)) {
4354 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004355 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004356
Steve Naroffb4406862008-09-29 18:10:17 +00004357 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004358 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004359 return Compatible;
4360
Steve Naroff1c7d0672008-09-04 15:10:53 +00004361 if (rhsType->isBlockPointerType())
4362 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004363
Ted Kremenek6217b802009-07-29 21:53:49 +00004364 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004365 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004366 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004367 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004368 return Incompatible;
4369 }
4370
Steve Naroff14108da2009-07-10 23:34:53 +00004371 if (isa<ObjCObjectPointerType>(lhsType)) {
4372 if (rhsType->isIntegerType())
4373 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004374
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004375 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004376 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004377 if (rhsType->isVoidPointerType()) // an exception to the rule.
4378 return Compatible;
4379 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004380 }
4381 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004382 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4383 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004384 if (Context.typesAreCompatible(lhsType, rhsType))
4385 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00004386 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4387 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004388 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004389 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004390 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004391 if (RHSPT->getPointeeType()->isVoidType())
4392 return Compatible;
4393 }
4394 // Treat block pointers as objects.
4395 if (rhsType->isBlockPointerType())
4396 return Compatible;
4397 return Incompatible;
4398 }
Chris Lattner78eca282008-04-07 06:49:41 +00004399 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004400 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004401 if (lhsType == Context.BoolTy)
4402 return Compatible;
4403
4404 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004405 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004406
Mike Stumpeed9cac2009-02-19 03:04:26 +00004407 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004408 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004409
4410 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004411 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004412 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004413 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004414 }
Steve Naroff14108da2009-07-10 23:34:53 +00004415 if (isa<ObjCObjectPointerType>(rhsType)) {
4416 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4417 if (lhsType == Context.BoolTy)
4418 return Compatible;
4419
4420 if (lhsType->isIntegerType())
4421 return PointerToInt;
4422
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004423 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004424 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004425 if (lhsType->isVoidPointerType()) // an exception to the rule.
4426 return Compatible;
4427 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004428 }
4429 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004430 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004431 return Compatible;
4432 return Incompatible;
4433 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004434
Chris Lattnerfc144e22008-01-04 23:18:45 +00004435 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004436 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004437 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004438 }
4439 return Incompatible;
4440}
4441
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004442/// \brief Constructs a transparent union from an expression that is
4443/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004444static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004445 QualType UnionType, FieldDecl *Field) {
4446 // Build an initializer list that designates the appropriate member
4447 // of the transparent union.
4448 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4449 &E, 1,
4450 SourceLocation());
4451 Initializer->setType(UnionType);
4452 Initializer->setInitializedFieldInUnion(Field);
4453
4454 // Build a compound literal constructing a value of the transparent
4455 // union type from this initializer list.
4456 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4457 false);
4458}
4459
4460Sema::AssignConvertType
4461Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4462 QualType FromType = rExpr->getType();
4463
Mike Stump1eb44332009-09-09 15:08:12 +00004464 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004465 // transparent_union GCC extension.
4466 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004467 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004468 return Incompatible;
4469
4470 // The field to initialize within the transparent union.
4471 RecordDecl *UD = UT->getDecl();
4472 FieldDecl *InitField = 0;
4473 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004474 for (RecordDecl::field_iterator it = UD->field_begin(),
4475 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004476 it != itend; ++it) {
4477 if (it->getType()->isPointerType()) {
4478 // If the transparent union contains a pointer type, we allow:
4479 // 1) void pointer
4480 // 2) null pointer constant
4481 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004482 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004483 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004484 InitField = *it;
4485 break;
4486 }
Mike Stump1eb44332009-09-09 15:08:12 +00004487
Douglas Gregorce940492009-09-25 04:25:58 +00004488 if (rExpr->isNullPointerConstant(Context,
4489 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004490 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004491 InitField = *it;
4492 break;
4493 }
4494 }
4495
4496 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4497 == Compatible) {
4498 InitField = *it;
4499 break;
4500 }
4501 }
4502
4503 if (!InitField)
4504 return Incompatible;
4505
4506 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4507 return Compatible;
4508}
4509
Chris Lattner5cf216b2008-01-04 18:04:52 +00004510Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004511Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004512 if (getLangOptions().CPlusPlus) {
4513 if (!lhsType->isRecordType()) {
4514 // C++ 5.17p3: If the left operand is not of class type, the
4515 // expression is implicitly converted (C++ 4) to the
4516 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004517 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4518 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004519 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004520 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004521 }
4522
4523 // FIXME: Currently, we fall through and treat C++ classes like C
4524 // structures.
4525 }
4526
Steve Naroff529a4ad2007-11-27 17:58:44 +00004527 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4528 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004529 if ((lhsType->isPointerType() ||
4530 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004531 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004532 && rExpr->isNullPointerConstant(Context,
4533 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004534 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004535 return Compatible;
4536 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004537
Chris Lattner943140e2007-10-16 02:55:40 +00004538 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004539 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004540 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004541 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004542 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004543 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004544 if (!lhsType->isReferenceType())
4545 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004546
Chris Lattner5cf216b2008-01-04 18:04:52 +00004547 Sema::AssignConvertType result =
4548 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004549
Steve Narofff1120de2007-08-24 22:33:52 +00004550 // C99 6.5.16.1p2: The value of the right operand is converted to the
4551 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004552 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4553 // so that we can use references in built-in functions even in C.
4554 // The getNonReferenceType() call makes sure that the resulting expression
4555 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004556 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004557 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4558 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004559 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004560}
4561
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004562QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004563 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004564 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004565 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004566 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004567}
4568
Mike Stumpeed9cac2009-02-19 03:04:26 +00004569inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004570 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004571 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004572 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004573 QualType lhsType =
4574 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4575 QualType rhsType =
4576 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004577
Nate Begemanbe2341d2008-07-14 18:02:46 +00004578 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004579 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004580 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004581
Nate Begemanbe2341d2008-07-14 18:02:46 +00004582 // Handle the case of a vector & extvector type of the same size and element
4583 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004584 if (getLangOptions().LaxVectorConversions) {
4585 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004586 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4587 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004588 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004589 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004590 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004591 }
4592 }
4593 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004594
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004595 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4596 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4597 bool swapped = false;
4598 if (rhsType->isExtVectorType()) {
4599 swapped = true;
4600 std::swap(rex, lex);
4601 std::swap(rhsType, lhsType);
4602 }
Mike Stump1eb44332009-09-09 15:08:12 +00004603
Nate Begemandde25982009-06-28 19:12:57 +00004604 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004605 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004606 QualType EltTy = LV->getElementType();
4607 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4608 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004609 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004610 if (swapped) std::swap(rex, lex);
4611 return lhsType;
4612 }
4613 }
4614 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4615 rhsType->isRealFloatingType()) {
4616 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004617 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004618 if (swapped) std::swap(rex, lex);
4619 return lhsType;
4620 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004621 }
4622 }
Mike Stump1eb44332009-09-09 15:08:12 +00004623
Nate Begemandde25982009-06-28 19:12:57 +00004624 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004625 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004626 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004627 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004628 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004629}
4630
Reid Spencer5f016e22007-07-11 17:01:13 +00004631inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004632 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004633 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004634 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004635
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004636 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004637
Steve Naroffa4332e22007-07-17 00:58:39 +00004638 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004639 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004640 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004641}
4642
4643inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004644 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004645 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4646 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4647 return CheckVectorOperands(Loc, lex, rex);
4648 return InvalidOperands(Loc, lex, rex);
4649 }
Steve Naroff90045e82007-07-13 23:32:42 +00004650
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004651 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004652
Steve Naroffa4332e22007-07-17 00:58:39 +00004653 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004654 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004655 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004656}
4657
4658inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004659 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004660 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4661 QualType compType = CheckVectorOperands(Loc, lex, rex);
4662 if (CompLHSTy) *CompLHSTy = compType;
4663 return compType;
4664 }
Steve Naroff49b45262007-07-13 16:58:59 +00004665
Eli Friedmanab3a8522009-03-28 01:22:36 +00004666 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004667
Reid Spencer5f016e22007-07-11 17:01:13 +00004668 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004669 if (lex->getType()->isArithmeticType() &&
4670 rex->getType()->isArithmeticType()) {
4671 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004672 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004673 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004674
Eli Friedmand72d16e2008-05-18 18:08:51 +00004675 // Put any potential pointer into PExp
4676 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004677 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004678 std::swap(PExp, IExp);
4679
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004680 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Eli Friedmand72d16e2008-05-18 18:08:51 +00004682 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004683 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004684
Chris Lattnerb5f15622009-04-24 23:50:08 +00004685 // Check for arithmetic on pointers to incomplete types.
4686 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004687 if (getLangOptions().CPlusPlus) {
4688 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004689 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004690 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004691 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004692
4693 // GNU extension: arithmetic on pointer to void
4694 Diag(Loc, diag::ext_gnu_void_ptr)
4695 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004696 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004697 if (getLangOptions().CPlusPlus) {
4698 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4699 << lex->getType() << lex->getSourceRange();
4700 return QualType();
4701 }
4702
4703 // GNU extension: arithmetic on pointer to function
4704 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4705 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004706 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004707 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004708 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004709 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004710 PExp->getType()->isObjCObjectPointerType()) &&
4711 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004712 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4713 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004714 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004715 return QualType();
4716 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004717 // Diagnose bad cases where we step over interface counts.
4718 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4719 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4720 << PointeeTy << PExp->getSourceRange();
4721 return QualType();
4722 }
Mike Stump1eb44332009-09-09 15:08:12 +00004723
Eli Friedmanab3a8522009-03-28 01:22:36 +00004724 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004725 QualType LHSTy = Context.isPromotableBitField(lex);
4726 if (LHSTy.isNull()) {
4727 LHSTy = lex->getType();
4728 if (LHSTy->isPromotableIntegerType())
4729 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004730 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004731 *CompLHSTy = LHSTy;
4732 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004733 return PExp->getType();
4734 }
4735 }
4736
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004737 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004738}
4739
Chris Lattnereca7be62008-04-07 05:30:13 +00004740// C99 6.5.6
4741QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004742 SourceLocation Loc, QualType* CompLHSTy) {
4743 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4744 QualType compType = CheckVectorOperands(Loc, lex, rex);
4745 if (CompLHSTy) *CompLHSTy = compType;
4746 return compType;
4747 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004748
Eli Friedmanab3a8522009-03-28 01:22:36 +00004749 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004750
Chris Lattner6e4ab612007-12-09 21:53:25 +00004751 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004752
Chris Lattner6e4ab612007-12-09 21:53:25 +00004753 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004754 if (lex->getType()->isArithmeticType()
4755 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004756 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004757 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004758 }
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Chris Lattner6e4ab612007-12-09 21:53:25 +00004760 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004761 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004762 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004763
Douglas Gregore7450f52009-03-24 19:52:54 +00004764 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004765
Douglas Gregore7450f52009-03-24 19:52:54 +00004766 bool ComplainAboutVoid = false;
4767 Expr *ComplainAboutFunc = 0;
4768 if (lpointee->isVoidType()) {
4769 if (getLangOptions().CPlusPlus) {
4770 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4771 << lex->getSourceRange() << rex->getSourceRange();
4772 return QualType();
4773 }
4774
4775 // GNU C extension: arithmetic on pointer to void
4776 ComplainAboutVoid = true;
4777 } else if (lpointee->isFunctionType()) {
4778 if (getLangOptions().CPlusPlus) {
4779 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004780 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004781 return QualType();
4782 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004783
4784 // GNU C extension: arithmetic on pointer to function
4785 ComplainAboutFunc = lex;
4786 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004787 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004788 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004789 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004790 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004791 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004792
Chris Lattnerb5f15622009-04-24 23:50:08 +00004793 // Diagnose bad cases where we step over interface counts.
4794 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4795 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4796 << lpointee << lex->getSourceRange();
4797 return QualType();
4798 }
Mike Stump1eb44332009-09-09 15:08:12 +00004799
Chris Lattner6e4ab612007-12-09 21:53:25 +00004800 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004801 if (rex->getType()->isIntegerType()) {
4802 if (ComplainAboutVoid)
4803 Diag(Loc, diag::ext_gnu_void_ptr)
4804 << lex->getSourceRange() << rex->getSourceRange();
4805 if (ComplainAboutFunc)
4806 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004807 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004808 << ComplainAboutFunc->getSourceRange();
4809
Eli Friedmanab3a8522009-03-28 01:22:36 +00004810 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004811 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004812 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004813
Chris Lattner6e4ab612007-12-09 21:53:25 +00004814 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004815 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004816 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004817
Douglas Gregore7450f52009-03-24 19:52:54 +00004818 // RHS must be a completely-type object type.
4819 // Handle the GNU void* extension.
4820 if (rpointee->isVoidType()) {
4821 if (getLangOptions().CPlusPlus) {
4822 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4823 << lex->getSourceRange() << rex->getSourceRange();
4824 return QualType();
4825 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004826
Douglas Gregore7450f52009-03-24 19:52:54 +00004827 ComplainAboutVoid = true;
4828 } else if (rpointee->isFunctionType()) {
4829 if (getLangOptions().CPlusPlus) {
4830 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004831 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004832 return QualType();
4833 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004834
4835 // GNU extension: arithmetic on pointer to function
4836 if (!ComplainAboutFunc)
4837 ComplainAboutFunc = rex;
4838 } else if (!rpointee->isDependentType() &&
4839 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004840 PDiag(diag::err_typecheck_sub_ptr_object)
4841 << rex->getSourceRange()
4842 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004843 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004844
Eli Friedman88d936b2009-05-16 13:54:38 +00004845 if (getLangOptions().CPlusPlus) {
4846 // Pointee types must be the same: C++ [expr.add]
4847 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4848 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4849 << lex->getType() << rex->getType()
4850 << lex->getSourceRange() << rex->getSourceRange();
4851 return QualType();
4852 }
4853 } else {
4854 // Pointee types must be compatible C99 6.5.6p3
4855 if (!Context.typesAreCompatible(
4856 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4857 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4858 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4859 << lex->getType() << rex->getType()
4860 << lex->getSourceRange() << rex->getSourceRange();
4861 return QualType();
4862 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004863 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004864
Douglas Gregore7450f52009-03-24 19:52:54 +00004865 if (ComplainAboutVoid)
4866 Diag(Loc, diag::ext_gnu_void_ptr)
4867 << lex->getSourceRange() << rex->getSourceRange();
4868 if (ComplainAboutFunc)
4869 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004870 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004871 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004872
4873 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004874 return Context.getPointerDiffType();
4875 }
4876 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004877
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004878 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004879}
4880
Chris Lattnereca7be62008-04-07 05:30:13 +00004881// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004882QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004883 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004884 // C99 6.5.7p2: Each of the operands shall have integer type.
4885 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004886 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004887
Nate Begeman2207d792009-10-25 02:26:48 +00004888 // Vector shifts promote their scalar inputs to vector type.
4889 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4890 return CheckVectorOperands(Loc, lex, rex);
4891
Chris Lattnerca5eede2007-12-12 05:47:28 +00004892 // Shifts don't perform usual arithmetic conversions, they just do integer
4893 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004894 QualType LHSTy = Context.isPromotableBitField(lex);
4895 if (LHSTy.isNull()) {
4896 LHSTy = lex->getType();
4897 if (LHSTy->isPromotableIntegerType())
4898 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004899 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004900 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004901 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004902
Chris Lattnerca5eede2007-12-12 05:47:28 +00004903 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004904
Ryan Flynnd0439682009-08-07 16:20:20 +00004905 // Sanity-check shift operands
4906 llvm::APSInt Right;
4907 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004908 if (!rex->isValueDependent() &&
4909 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004910 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004911 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4912 else {
4913 llvm::APInt LeftBits(Right.getBitWidth(),
4914 Context.getTypeSize(lex->getType()));
4915 if (Right.uge(LeftBits))
4916 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4917 }
4918 }
4919
Chris Lattnerca5eede2007-12-12 05:47:28 +00004920 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004921 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004922}
4923
John McCall5dbad3d2009-11-06 08:49:08 +00004924/// \brief Implements -Wsign-compare.
4925///
4926/// \param lex the left-hand expression
4927/// \param rex the right-hand expression
4928/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004929/// \param Equality whether this is an "equality-like" join, which
4930/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004931void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004932 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004933 // Don't warn if we're in an unevaluated context.
Douglas Gregor2afce722009-11-26 00:44:06 +00004934 if (ExprEvalContexts.back().Context == Unevaluated)
John McCall7d62a8f2009-11-06 18:16:06 +00004935 return;
4936
John McCall45aa4552009-11-05 00:40:04 +00004937 QualType lt = lex->getType(), rt = rex->getType();
4938
4939 // Only warn if both operands are integral.
4940 if (!lt->isIntegerType() || !rt->isIntegerType())
4941 return;
4942
Sebastian Redl732429c2009-11-05 21:09:23 +00004943 // If either expression is value-dependent, don't warn. We'll get another
4944 // chance at instantiation time.
4945 if (lex->isValueDependent() || rex->isValueDependent())
4946 return;
4947
John McCall45aa4552009-11-05 00:40:04 +00004948 // The rule is that the signed operand becomes unsigned, so isolate the
4949 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00004950 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00004951 if (lt->isSignedIntegerType()) {
4952 if (rt->isSignedIntegerType()) return;
4953 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00004954 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00004955 } else {
4956 if (!rt->isSignedIntegerType()) return;
4957 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00004958 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00004959 }
4960
John McCall5dbad3d2009-11-06 08:49:08 +00004961 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00004962 // then (1) the result type will be signed and (2) the unsigned
4963 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00004964 // of the comparison will be exact.
4965 if (Context.getIntWidth(signedOperand->getType()) >
4966 Context.getIntWidth(unsignedOperand->getType()))
4967 return;
4968
John McCall45aa4552009-11-05 00:40:04 +00004969 // If the value is a non-negative integer constant, then the
4970 // signed->unsigned conversion won't change it.
4971 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00004972 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00004973 assert(value.isSigned() && "result of signed expression not signed");
4974
4975 if (value.isNonNegative())
4976 return;
4977 }
4978
John McCall5dbad3d2009-11-06 08:49:08 +00004979 if (Equality) {
4980 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00004981 // constant which cannot collide with a overflowed signed operand,
4982 // then reinterpreting the signed operand as unsigned will not
4983 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00004984 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4985 assert(!value.isSigned() && "result of unsigned expression is signed");
4986
4987 // 2's complement: test the top bit.
4988 if (value.isNonNegative())
4989 return;
4990 }
4991 }
4992
John McCallb13c87f2009-11-05 09:23:39 +00004993 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00004994 << lex->getType() << rex->getType()
4995 << lex->getSourceRange() << rex->getSourceRange();
4996}
4997
Douglas Gregor0c6db942009-05-04 06:07:12 +00004998// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004999QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005000 unsigned OpaqueOpc, bool isRelational) {
5001 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5002
Nate Begemanbe2341d2008-07-14 18:02:46 +00005003 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005004 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005005
John McCall5dbad3d2009-11-06 08:49:08 +00005006 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5007 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005008
Chris Lattnera5937dd2007-08-26 01:18:55 +00005009 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005010 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5011 UsualArithmeticConversions(lex, rex);
5012 else {
5013 UsualUnaryConversions(lex);
5014 UsualUnaryConversions(rex);
5015 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005016 QualType lType = lex->getType();
5017 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005018
Mike Stumpaf199f32009-05-07 18:43:07 +00005019 if (!lType->isFloatingType()
5020 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005021 // For non-floating point types, check for self-comparisons of the form
5022 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5023 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005024 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005025 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005026 Expr *LHSStripped = lex->IgnoreParens();
5027 Expr *RHSStripped = rex->IgnoreParens();
5028 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5029 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005030 if (DRL->getDecl() == DRR->getDecl() &&
5031 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00005032 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00005033
Chris Lattner55660a72009-03-08 19:39:53 +00005034 if (isa<CastExpr>(LHSStripped))
5035 LHSStripped = LHSStripped->IgnoreParenCasts();
5036 if (isa<CastExpr>(RHSStripped))
5037 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005038
Chris Lattner55660a72009-03-08 19:39:53 +00005039 // Warn about comparisons against a string constant (unless the other
5040 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005041 Expr *literalString = 0;
5042 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005043 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005044 !RHSStripped->isNullPointerConstant(Context,
5045 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005046 literalString = lex;
5047 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005048 } else if ((isa<StringLiteral>(RHSStripped) ||
5049 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005050 !LHSStripped->isNullPointerConstant(Context,
5051 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005052 literalString = rex;
5053 literalStringStripped = RHSStripped;
5054 }
5055
5056 if (literalString) {
5057 std::string resultComparison;
5058 switch (Opc) {
5059 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5060 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5061 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5062 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5063 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5064 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5065 default: assert(false && "Invalid comparison operator");
5066 }
5067 Diag(Loc, diag::warn_stringcompare)
5068 << isa<ObjCEncodeExpr>(literalStringStripped)
5069 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00005070 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5071 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5072 "strcmp(")
5073 << CodeModificationHint::CreateInsertion(
5074 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00005075 resultComparison);
5076 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005077 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005078
Douglas Gregor447b69e2008-11-19 03:25:36 +00005079 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00005080 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005081
Chris Lattnera5937dd2007-08-26 01:18:55 +00005082 if (isRelational) {
5083 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005084 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005085 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005086 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005087 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00005088 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005089 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00005090 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005091
Chris Lattnera5937dd2007-08-26 01:18:55 +00005092 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005093 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005094 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005095
Douglas Gregorce940492009-09-25 04:25:58 +00005096 bool LHSIsNull = lex->isNullPointerConstant(Context,
5097 Expr::NPC_ValueDependentIsNull);
5098 bool RHSIsNull = rex->isNullPointerConstant(Context,
5099 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005100
Chris Lattnera5937dd2007-08-26 01:18:55 +00005101 // All of the following pointer related warnings are GCC extensions, except
5102 // when handling null pointer constants. One day, we can consider making them
5103 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005104 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005105 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005106 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005107 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005108 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005109
Douglas Gregor0c6db942009-05-04 06:07:12 +00005110 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005111 if (LCanPointeeTy == RCanPointeeTy)
5112 return ResultTy;
5113
Douglas Gregor0c6db942009-05-04 06:07:12 +00005114 // C++ [expr.rel]p2:
5115 // [...] Pointer conversions (4.10) and qualification
5116 // conversions (4.4) are performed on pointer operands (or on
5117 // a pointer operand and a null pointer constant) to bring
5118 // them to their composite pointer type. [...]
5119 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005120 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005121 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005122 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005123 if (T.isNull()) {
5124 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5125 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5126 return QualType();
5127 }
5128
Eli Friedman73c39ab2009-10-20 08:27:19 +00005129 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5130 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005131 return ResultTy;
5132 }
Eli Friedman3075e762009-08-23 00:27:47 +00005133 // C99 6.5.9p2 and C99 6.5.8p2
5134 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5135 RCanPointeeTy.getUnqualifiedType())) {
5136 // Valid unless a relational comparison of function pointers
5137 if (isRelational && LCanPointeeTy->isFunctionType()) {
5138 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5139 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5140 }
5141 } else if (!isRelational &&
5142 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5143 // Valid unless comparison between non-null pointer and function pointer
5144 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5145 && !LHSIsNull && !RHSIsNull) {
5146 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5147 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5148 }
5149 } else {
5150 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005151 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005152 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005153 }
Eli Friedman3075e762009-08-23 00:27:47 +00005154 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005155 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005156 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005157 }
Mike Stump1eb44332009-09-09 15:08:12 +00005158
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005159 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005160 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005161 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005162 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005163 (lType->isPointerType() ||
5164 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005165 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005166 return ResultTy;
5167 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005168 if (LHSIsNull &&
5169 (rType->isPointerType() ||
5170 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005171 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005172 return ResultTy;
5173 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005174
5175 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005176 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005177 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5178 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005179 // In addition, pointers to members can be compared, or a pointer to
5180 // member and a null pointer constant. Pointer to member conversions
5181 // (4.11) and qualification conversions (4.4) are performed to bring
5182 // them to a common type. If one operand is a null pointer constant,
5183 // the common type is the type of the other operand. Otherwise, the
5184 // common type is a pointer to member type similar (4.4) to the type
5185 // of one of the operands, with a cv-qualification signature (4.4)
5186 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005187 // types.
5188 QualType T = FindCompositePointerType(lex, rex);
5189 if (T.isNull()) {
5190 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5191 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5192 return QualType();
5193 }
Mike Stump1eb44332009-09-09 15:08:12 +00005194
Eli Friedman73c39ab2009-10-20 08:27:19 +00005195 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5196 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005197 return ResultTy;
5198 }
Mike Stump1eb44332009-09-09 15:08:12 +00005199
Douglas Gregor20b3e992009-08-24 17:42:35 +00005200 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005201 if (lType->isNullPtrType() && rType->isNullPtrType())
5202 return ResultTy;
5203 }
Mike Stump1eb44332009-09-09 15:08:12 +00005204
Steve Naroff1c7d0672008-09-04 15:10:53 +00005205 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005206 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005207 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5208 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005209
Steve Naroff1c7d0672008-09-04 15:10:53 +00005210 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005211 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005212 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005213 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005214 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005215 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005216 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005217 }
Steve Naroff59f53942008-09-28 01:11:11 +00005218 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005219 if (!isRelational
5220 && ((lType->isBlockPointerType() && rType->isPointerType())
5221 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005222 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005223 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005224 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005225 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005226 ->getPointeeType()->isVoidType())))
5227 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5228 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005229 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005230 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005231 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005232 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005233
Steve Naroff14108da2009-07-10 23:34:53 +00005234 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005235 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005236 const PointerType *LPT = lType->getAs<PointerType>();
5237 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005238 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005239 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005240 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005241 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005242
Steve Naroffa8069f12008-11-17 19:49:16 +00005243 if (!LPtrToVoid && !RPtrToVoid &&
5244 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005245 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005246 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005247 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005248 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005249 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005250 }
Steve Naroff14108da2009-07-10 23:34:53 +00005251 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005252 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005253 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5254 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005255 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005256 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005257 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005258 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005259 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005260 unsigned DiagID = 0;
5261 if (RHSIsNull) {
5262 if (isRelational)
5263 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5264 } else if (isRelational)
5265 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5266 else
5267 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005268
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005269 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005270 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005271 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005272 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005273 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005274 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005275 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005276 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005277 unsigned DiagID = 0;
5278 if (LHSIsNull) {
5279 if (isRelational)
5280 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5281 } else if (isRelational)
5282 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5283 else
5284 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005285
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005286 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005287 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005288 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005289 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005290 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005291 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005292 }
Steve Naroff39218df2008-09-04 16:56:14 +00005293 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005294 if (!isRelational && RHSIsNull
5295 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005296 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005297 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005298 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005299 if (!isRelational && LHSIsNull
5300 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005301 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005302 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005303 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005304 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005305}
5306
Nate Begemanbe2341d2008-07-14 18:02:46 +00005307/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005308/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005309/// like a scalar comparison, a vector comparison produces a vector of integer
5310/// types.
5311QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005312 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005313 bool isRelational) {
5314 // Check to make sure we're operating on vectors of the same type and width,
5315 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005316 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005317 if (vType.isNull())
5318 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005319
Nate Begemanbe2341d2008-07-14 18:02:46 +00005320 QualType lType = lex->getType();
5321 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005322
Nate Begemanbe2341d2008-07-14 18:02:46 +00005323 // For non-floating point types, check for self-comparisons of the form
5324 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5325 // often indicate logic errors in the program.
5326 if (!lType->isFloatingType()) {
5327 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5328 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5329 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005330 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005331 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005332
Nate Begemanbe2341d2008-07-14 18:02:46 +00005333 // Check for comparisons of floating point operands using != and ==.
5334 if (!isRelational && lType->isFloatingType()) {
5335 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005336 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005337 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005338
Nate Begemanbe2341d2008-07-14 18:02:46 +00005339 // Return the type for the comparison, which is the same as vector type for
5340 // integer vectors, or an integer type of identical size and number of
5341 // elements for floating point vectors.
5342 if (lType->isIntegerType())
5343 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005344
John McCall183700f2009-09-21 23:43:11 +00005345 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005346 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005347 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005348 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005349 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005350 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5351
Mike Stumpeed9cac2009-02-19 03:04:26 +00005352 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005353 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005354 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5355}
5356
Reid Spencer5f016e22007-07-11 17:01:13 +00005357inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005358 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005359 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005360 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005361
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005362 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005363
Steve Naroffa4332e22007-07-17 00:58:39 +00005364 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005365 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005366 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005367}
5368
5369inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005370 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005371 if (!Context.getLangOptions().CPlusPlus) {
5372 UsualUnaryConversions(lex);
5373 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005374
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005375 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5376 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005377
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005378 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005379 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005380
5381 // C++ [expr.log.and]p1
5382 // C++ [expr.log.or]p1
5383 // The operands are both implicitly converted to type bool (clause 4).
5384 StandardConversionSequence LHS;
5385 if (!IsStandardConversion(lex, Context.BoolTy,
5386 /*InOverloadResolution=*/false, LHS))
5387 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005388
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005389 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5390 "passing", /*IgnoreBaseAccess=*/false))
5391 return InvalidOperands(Loc, lex, rex);
5392
5393 StandardConversionSequence RHS;
5394 if (!IsStandardConversion(rex, Context.BoolTy,
5395 /*InOverloadResolution=*/false, RHS))
5396 return InvalidOperands(Loc, lex, rex);
5397
5398 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5399 "passing", /*IgnoreBaseAccess=*/false))
5400 return InvalidOperands(Loc, lex, rex);
5401
5402 // C++ [expr.log.and]p2
5403 // C++ [expr.log.or]p2
5404 // The result is a bool.
5405 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005406}
5407
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005408/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5409/// is a read-only property; return true if so. A readonly property expression
5410/// depends on various declarations and thus must be treated specially.
5411///
Mike Stump1eb44332009-09-09 15:08:12 +00005412static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005413 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5414 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5415 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5416 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005417 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005418 BaseType->getAsObjCInterfacePointerType())
5419 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5420 if (S.isPropertyReadonly(PDecl, IFace))
5421 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005422 }
5423 }
5424 return false;
5425}
5426
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005427/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5428/// emit an error and return true. If so, return false.
5429static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005430 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005431 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005432 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005433 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5434 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005435 if (IsLV == Expr::MLV_Valid)
5436 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005437
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005438 unsigned Diag = 0;
5439 bool NeedType = false;
5440 switch (IsLV) { // C99 6.5.16p2
5441 default: assert(0 && "Unknown result from isModifiableLvalue!");
5442 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005443 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005444 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5445 NeedType = true;
5446 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005447 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005448 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5449 NeedType = true;
5450 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005451 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005452 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5453 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005454 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005455 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5456 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005457 case Expr::MLV_IncompleteType:
5458 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005459 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005460 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5461 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005462 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005463 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5464 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005465 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005466 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5467 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005468 case Expr::MLV_ReadonlyProperty:
5469 Diag = diag::error_readonly_property_assignment;
5470 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005471 case Expr::MLV_NoSetterProperty:
5472 Diag = diag::error_nosetter_property_assignment;
5473 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005474 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005475
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005476 SourceRange Assign;
5477 if (Loc != OrigLoc)
5478 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005479 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005480 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005481 else
Mike Stump1eb44332009-09-09 15:08:12 +00005482 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005483 return true;
5484}
5485
5486
5487
5488// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005489QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5490 SourceLocation Loc,
5491 QualType CompoundType) {
5492 // Verify that LHS is a modifiable lvalue, and emit error if not.
5493 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005494 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005495
5496 QualType LHSType = LHS->getType();
5497 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005498
Chris Lattner5cf216b2008-01-04 18:04:52 +00005499 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005500 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005501 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005502 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005503 // Special case of NSObject attributes on c-style pointer types.
5504 if (ConvTy == IncompatiblePointer &&
5505 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005506 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005507 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005508 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005509 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005510
Chris Lattner2c156472008-08-21 18:04:13 +00005511 // If the RHS is a unary plus or minus, check to see if they = and + are
5512 // right next to each other. If so, the user may have typo'd "x =+ 4"
5513 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005514 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005515 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5516 RHSCheck = ICE->getSubExpr();
5517 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5518 if ((UO->getOpcode() == UnaryOperator::Plus ||
5519 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005520 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005521 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005522 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5523 // And there is a space or other character before the subexpr of the
5524 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005525 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5526 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005527 Diag(Loc, diag::warn_not_compound_assign)
5528 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5529 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005530 }
Chris Lattner2c156472008-08-21 18:04:13 +00005531 }
5532 } else {
5533 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005534 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005535 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005536
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005537 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5538 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005539 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005540
Reid Spencer5f016e22007-07-11 17:01:13 +00005541 // C99 6.5.16p3: The type of an assignment expression is the type of the
5542 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005543 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005544 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5545 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005546 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005547 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005548 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005549}
5550
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005551// C99 6.5.17
5552QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005553 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005554 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005555
5556 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5557 // incomplete in C++).
5558
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005559 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005560}
5561
Steve Naroff49b45262007-07-13 16:58:59 +00005562/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5563/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005564QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5565 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005566 if (Op->isTypeDependent())
5567 return Context.DependentTy;
5568
Chris Lattner3528d352008-11-21 07:05:48 +00005569 QualType ResType = Op->getType();
5570 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005571
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005572 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5573 // Decrement of bool is not allowed.
5574 if (!isInc) {
5575 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5576 return QualType();
5577 }
5578 // Increment of bool sets it to true, but is deprecated.
5579 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5580 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005581 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005582 } else if (ResType->isAnyPointerType()) {
5583 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005584
Chris Lattner3528d352008-11-21 07:05:48 +00005585 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005586 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005587 if (getLangOptions().CPlusPlus) {
5588 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5589 << Op->getSourceRange();
5590 return QualType();
5591 }
5592
5593 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005594 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005595 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005596 if (getLangOptions().CPlusPlus) {
5597 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5598 << Op->getType() << Op->getSourceRange();
5599 return QualType();
5600 }
5601
5602 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005603 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005604 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005605 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005606 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005607 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005608 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005609 // Diagnose bad cases where we step over interface counts.
5610 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5611 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5612 << PointeeTy << Op->getSourceRange();
5613 return QualType();
5614 }
Chris Lattner3528d352008-11-21 07:05:48 +00005615 } else if (ResType->isComplexType()) {
5616 // C99 does not support ++/-- on complex types, we allow as an extension.
5617 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005618 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005619 } else {
5620 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005621 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005622 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005623 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005624 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005625 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005626 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005627 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005628 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005629}
5630
Anders Carlsson369dee42008-02-01 07:15:58 +00005631/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005632/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005633/// where the declaration is needed for type checking. We only need to
5634/// handle cases when the expression references a function designator
5635/// or is an lvalue. Here are some examples:
5636/// - &(x) => x
5637/// - &*****f => f for f a function designator.
5638/// - &s.xx => s
5639/// - &s.zz[1].yy -> s, if zz is an array
5640/// - *(x + 1) -> x, if x is an array
5641/// - &"123"[2] -> 0
5642/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005643static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005644 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005645 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005646 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005647 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005648 // If this is an arrow operator, the address is an offset from
5649 // the base's value, so the object the base refers to is
5650 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005651 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005652 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005653 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005654 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005655 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005656 // FIXME: This code shouldn't be necessary! We should catch the implicit
5657 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005658 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5659 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5660 if (ICE->getSubExpr()->getType()->isArrayType())
5661 return getPrimaryDecl(ICE->getSubExpr());
5662 }
5663 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005664 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005665 case Stmt::UnaryOperatorClass: {
5666 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005667
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005668 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005669 case UnaryOperator::Real:
5670 case UnaryOperator::Imag:
5671 case UnaryOperator::Extension:
5672 return getPrimaryDecl(UO->getSubExpr());
5673 default:
5674 return 0;
5675 }
5676 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005677 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005678 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005679 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005680 // If the result of an implicit cast is an l-value, we care about
5681 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005682 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005683 default:
5684 return 0;
5685 }
5686}
5687
5688/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005689/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005690/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005691/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005692/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005693/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005694/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005695QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005696 // Make sure to ignore parentheses in subsequent checks
5697 op = op->IgnoreParens();
5698
Douglas Gregor9103bb22008-12-17 22:52:20 +00005699 if (op->isTypeDependent())
5700 return Context.DependentTy;
5701
Steve Naroff08f19672008-01-13 17:10:08 +00005702 if (getLangOptions().C99) {
5703 // Implement C99-only parts of addressof rules.
5704 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5705 if (uOp->getOpcode() == UnaryOperator::Deref)
5706 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5707 // (assuming the deref expression is valid).
5708 return uOp->getSubExpr()->getType();
5709 }
5710 // Technically, there should be a check for array subscript
5711 // expressions here, but the result of one is always an lvalue anyway.
5712 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005713 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005714 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005715
Eli Friedman441cf102009-05-16 23:27:50 +00005716 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5717 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005718 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005719 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005720 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005721 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5722 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005723 return QualType();
5724 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005725 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005726 // The operand cannot be a bit-field
5727 Diag(OpLoc, diag::err_typecheck_address_of)
5728 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005729 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005730 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5731 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005732 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005733 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005734 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005735 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005736 } else if (isa<ObjCPropertyRefExpr>(op)) {
5737 // cannot take address of a property expression.
5738 Diag(OpLoc, diag::err_typecheck_address_of)
5739 << "property expression" << op->getSourceRange();
5740 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005741 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5742 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005743 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5744 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005745 } else if (isa<UnresolvedLookupExpr>(op)) {
5746 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005747 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005748 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005749 // with the register storage-class specifier.
5750 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5751 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005752 Diag(OpLoc, diag::err_typecheck_address_of)
5753 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005754 return QualType();
5755 }
John McCallba135432009-11-21 08:51:07 +00005756 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005757 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005758 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005759 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005760 // Could be a pointer to member, though, if there is an explicit
5761 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005762 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005763 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005764 if (Ctx && Ctx->isRecord()) {
5765 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005766 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005767 diag::err_cannot_form_pointer_to_member_of_reference_type)
5768 << FD->getDeclName() << FD->getType();
5769 return QualType();
5770 }
Mike Stump1eb44332009-09-09 15:08:12 +00005771
Sebastian Redlebc07d52009-02-03 20:19:35 +00005772 return Context.getMemberPointerType(op->getType(),
5773 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005774 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005775 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005776 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005777 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005778 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005779 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5780 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005781 return Context.getMemberPointerType(op->getType(),
5782 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5783 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005784 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005785 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005786
Eli Friedman441cf102009-05-16 23:27:50 +00005787 if (lval == Expr::LV_IncompleteVoidType) {
5788 // Taking the address of a void variable is technically illegal, but we
5789 // allow it in cases which are otherwise valid.
5790 // Example: "extern void x; void* y = &x;".
5791 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5792 }
5793
Reid Spencer5f016e22007-07-11 17:01:13 +00005794 // If the operand has type "type", the result has type "pointer to type".
5795 return Context.getPointerType(op->getType());
5796}
5797
Chris Lattner22caddc2008-11-23 09:13:29 +00005798QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005799 if (Op->isTypeDependent())
5800 return Context.DependentTy;
5801
Chris Lattner22caddc2008-11-23 09:13:29 +00005802 UsualUnaryConversions(Op);
5803 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005804
Chris Lattner22caddc2008-11-23 09:13:29 +00005805 // Note that per both C89 and C99, this is always legal, even if ptype is an
5806 // incomplete type or void. It would be possible to warn about dereferencing
5807 // a void pointer, but it's completely well-defined, and such a warning is
5808 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005809 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005810 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005811
John McCall183700f2009-09-21 23:43:11 +00005812 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005813 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005814
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005815 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005816 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005817 return QualType();
5818}
5819
5820static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5821 tok::TokenKind Kind) {
5822 BinaryOperator::Opcode Opc;
5823 switch (Kind) {
5824 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005825 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5826 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005827 case tok::star: Opc = BinaryOperator::Mul; break;
5828 case tok::slash: Opc = BinaryOperator::Div; break;
5829 case tok::percent: Opc = BinaryOperator::Rem; break;
5830 case tok::plus: Opc = BinaryOperator::Add; break;
5831 case tok::minus: Opc = BinaryOperator::Sub; break;
5832 case tok::lessless: Opc = BinaryOperator::Shl; break;
5833 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5834 case tok::lessequal: Opc = BinaryOperator::LE; break;
5835 case tok::less: Opc = BinaryOperator::LT; break;
5836 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5837 case tok::greater: Opc = BinaryOperator::GT; break;
5838 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5839 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5840 case tok::amp: Opc = BinaryOperator::And; break;
5841 case tok::caret: Opc = BinaryOperator::Xor; break;
5842 case tok::pipe: Opc = BinaryOperator::Or; break;
5843 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5844 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5845 case tok::equal: Opc = BinaryOperator::Assign; break;
5846 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5847 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5848 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5849 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5850 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5851 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5852 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5853 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5854 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5855 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5856 case tok::comma: Opc = BinaryOperator::Comma; break;
5857 }
5858 return Opc;
5859}
5860
5861static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5862 tok::TokenKind Kind) {
5863 UnaryOperator::Opcode Opc;
5864 switch (Kind) {
5865 default: assert(0 && "Unknown unary op!");
5866 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5867 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5868 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5869 case tok::star: Opc = UnaryOperator::Deref; break;
5870 case tok::plus: Opc = UnaryOperator::Plus; break;
5871 case tok::minus: Opc = UnaryOperator::Minus; break;
5872 case tok::tilde: Opc = UnaryOperator::Not; break;
5873 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005874 case tok::kw___real: Opc = UnaryOperator::Real; break;
5875 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5876 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5877 }
5878 return Opc;
5879}
5880
Douglas Gregoreaebc752008-11-06 23:29:22 +00005881/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5882/// operator @p Opc at location @c TokLoc. This routine only supports
5883/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005884Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5885 unsigned Op,
5886 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005887 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005888 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005889 // The following two variables are used for compound assignment operators
5890 QualType CompLHSTy; // Type of LHS after promotions for computation
5891 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005892
5893 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005894 case BinaryOperator::Assign:
5895 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5896 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005897 case BinaryOperator::PtrMemD:
5898 case BinaryOperator::PtrMemI:
5899 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5900 Opc == BinaryOperator::PtrMemI);
5901 break;
5902 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005903 case BinaryOperator::Div:
5904 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5905 break;
5906 case BinaryOperator::Rem:
5907 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5908 break;
5909 case BinaryOperator::Add:
5910 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5911 break;
5912 case BinaryOperator::Sub:
5913 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5914 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005915 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005916 case BinaryOperator::Shr:
5917 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5918 break;
5919 case BinaryOperator::LE:
5920 case BinaryOperator::LT:
5921 case BinaryOperator::GE:
5922 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005923 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005924 break;
5925 case BinaryOperator::EQ:
5926 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005927 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005928 break;
5929 case BinaryOperator::And:
5930 case BinaryOperator::Xor:
5931 case BinaryOperator::Or:
5932 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5933 break;
5934 case BinaryOperator::LAnd:
5935 case BinaryOperator::LOr:
5936 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5937 break;
5938 case BinaryOperator::MulAssign:
5939 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005940 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5941 CompLHSTy = CompResultTy;
5942 if (!CompResultTy.isNull())
5943 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005944 break;
5945 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005946 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5947 CompLHSTy = CompResultTy;
5948 if (!CompResultTy.isNull())
5949 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005950 break;
5951 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005952 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5953 if (!CompResultTy.isNull())
5954 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005955 break;
5956 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005957 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5958 if (!CompResultTy.isNull())
5959 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005960 break;
5961 case BinaryOperator::ShlAssign:
5962 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005963 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5964 CompLHSTy = CompResultTy;
5965 if (!CompResultTy.isNull())
5966 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005967 break;
5968 case BinaryOperator::AndAssign:
5969 case BinaryOperator::XorAssign:
5970 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005971 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5972 CompLHSTy = CompResultTy;
5973 if (!CompResultTy.isNull())
5974 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005975 break;
5976 case BinaryOperator::Comma:
5977 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5978 break;
5979 }
5980 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005981 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005982 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005983 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5984 else
5985 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005986 CompLHSTy, CompResultTy,
5987 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005988}
5989
Sebastian Redlaee3c932009-10-27 12:10:02 +00005990/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5991/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005992static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5993 const PartialDiagnostic &PD,
5994 SourceRange ParenRange)
5995{
5996 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5997 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5998 // We can't display the parentheses, so just dig the
5999 // warning/error and return.
6000 Self.Diag(Loc, PD);
6001 return;
6002 }
6003
6004 Self.Diag(Loc, PD)
6005 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6006 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6007}
6008
Sebastian Redlaee3c932009-10-27 12:10:02 +00006009/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6010/// operators are mixed in a way that suggests that the programmer forgot that
6011/// comparison operators have higher precedence. The most typical example of
6012/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006013static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6014 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006015 typedef BinaryOperator BinOp;
6016 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6017 rhsopc = static_cast<BinOp::Opcode>(-1);
6018 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006019 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006020 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006021 rhsopc = BO->getOpcode();
6022
6023 // Subs are not binary operators.
6024 if (lhsopc == -1 && rhsopc == -1)
6025 return;
6026
6027 // Bitwise operations are sometimes used as eager logical ops.
6028 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006029 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6030 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006031 return;
6032
Sebastian Redlaee3c932009-10-27 12:10:02 +00006033 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006034 SuggestParentheses(Self, OpLoc,
6035 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006036 << SourceRange(lhs->getLocStart(), OpLoc)
6037 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6038 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6039 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006040 SuggestParentheses(Self, OpLoc,
6041 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006042 << SourceRange(OpLoc, rhs->getLocEnd())
6043 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6044 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006045}
6046
6047/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6048/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6049/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6050static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6051 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006052 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006053 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6054}
6055
Reid Spencer5f016e22007-07-11 17:01:13 +00006056// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006057Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6058 tok::TokenKind Kind,
6059 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006060 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006061 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006062
Steve Narofff69936d2007-09-16 03:34:24 +00006063 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6064 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006065
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006066 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6067 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6068
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006069 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6070}
6071
6072Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6073 BinaryOperator::Opcode Opc,
6074 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006075 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006076 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006077 rhs->getType()->isOverloadableType())) {
6078 // Find all of the overloaded operators visible from this
6079 // point. We perform both an operator-name lookup from the local
6080 // scope and an argument-dependent lookup based on the types of
6081 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006082 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006083 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6084 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006085 if (S)
6086 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6087 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006088 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006089 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006090 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006091 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006092 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006093
Douglas Gregor063daf62009-03-13 18:40:31 +00006094 // Build the (potentially-overloaded, potentially-dependent)
6095 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006096 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006097 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006098
Douglas Gregoreaebc752008-11-06 23:29:22 +00006099 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006100 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006101}
6102
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006103Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006104 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006105 ExprArg InputArg) {
6106 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006107
Mike Stump390b4cc2009-05-16 07:39:55 +00006108 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006109 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006110 QualType resultType;
6111 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006112 case UnaryOperator::OffsetOf:
6113 assert(false && "Invalid unary operator");
6114 break;
6115
Reid Spencer5f016e22007-07-11 17:01:13 +00006116 case UnaryOperator::PreInc:
6117 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006118 case UnaryOperator::PostInc:
6119 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006120 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006121 Opc == UnaryOperator::PreInc ||
6122 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006123 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006124 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006125 resultType = CheckAddressOfOperand(Input, OpLoc);
6126 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006127 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006128 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006129 resultType = CheckIndirectionOperand(Input, OpLoc);
6130 break;
6131 case UnaryOperator::Plus:
6132 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006133 UsualUnaryConversions(Input);
6134 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006135 if (resultType->isDependentType())
6136 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006137 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6138 break;
6139 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6140 resultType->isEnumeralType())
6141 break;
6142 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6143 Opc == UnaryOperator::Plus &&
6144 resultType->isPointerType())
6145 break;
6146
Sebastian Redl0eb23302009-01-19 00:08:26 +00006147 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6148 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006149 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006150 UsualUnaryConversions(Input);
6151 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006152 if (resultType->isDependentType())
6153 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006154 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6155 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6156 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006157 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006158 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006159 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006160 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6161 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006162 break;
6163 case UnaryOperator::LNot: // logical negation
6164 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006165 DefaultFunctionArrayConversion(Input);
6166 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006167 if (resultType->isDependentType())
6168 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006169 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006170 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6171 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006172 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006173 // In C++, it's bool. C++ 5.3.1p8
6174 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006175 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006176 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006177 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006178 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006179 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006180 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006181 resultType = Input->getType();
6182 break;
6183 }
6184 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006185 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006186
6187 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006188 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006189}
6190
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006191Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6192 UnaryOperator::Opcode Opc,
6193 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006194 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006195 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6196 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006197 // Find all of the overloaded operators visible from this
6198 // point. We perform both an operator-name lookup from the local
6199 // scope and an argument-dependent lookup based on the types of
6200 // the arguments.
6201 FunctionSet Functions;
6202 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6203 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006204 if (S)
6205 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6206 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006207 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006208 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006209 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006210 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006211
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006212 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6213 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006214
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006215 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6216}
6217
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006218// Unary Operators. 'Tok' is the token for the operator.
6219Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6220 tok::TokenKind Op, ExprArg input) {
6221 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6222}
6223
Steve Naroff1b273c42007-09-16 14:56:35 +00006224/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006225Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6226 SourceLocation LabLoc,
6227 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006228 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006229 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006230
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006231 // If we haven't seen this label yet, create a forward reference. It
6232 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006233 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006234 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006235
Reid Spencer5f016e22007-07-11 17:01:13 +00006236 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006237 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6238 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006239}
6240
Sebastian Redlf53597f2009-03-15 17:47:39 +00006241Sema::OwningExprResult
6242Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6243 SourceLocation RPLoc) { // "({..})"
6244 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006245 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6246 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6247
Eli Friedmandca2b732009-01-24 23:09:00 +00006248 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006249 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006250 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006251
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006252 // FIXME: there are a variety of strange constraints to enforce here, for
6253 // example, it is not possible to goto into a stmt expression apparently.
6254 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006255
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006256 // If there are sub stmts in the compound stmt, take the type of the last one
6257 // as the type of the stmtexpr.
6258 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006259
Chris Lattner611b2ec2008-07-26 19:51:01 +00006260 if (!Compound->body_empty()) {
6261 Stmt *LastStmt = Compound->body_back();
6262 // If LastStmt is a label, skip down through into the body.
6263 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6264 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006265
Chris Lattner611b2ec2008-07-26 19:51:01 +00006266 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006267 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006268 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006269
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006270 // FIXME: Check that expression type is complete/non-abstract; statement
6271 // expressions are not lvalues.
6272
Sebastian Redlf53597f2009-03-15 17:47:39 +00006273 substmt.release();
6274 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006275}
Steve Naroffd34e9152007-08-01 22:05:33 +00006276
Sebastian Redlf53597f2009-03-15 17:47:39 +00006277Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6278 SourceLocation BuiltinLoc,
6279 SourceLocation TypeLoc,
6280 TypeTy *argty,
6281 OffsetOfComponent *CompPtr,
6282 unsigned NumComponents,
6283 SourceLocation RPLoc) {
6284 // FIXME: This function leaks all expressions in the offset components on
6285 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006286 // FIXME: Preserve type source info.
6287 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006288 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006289
Sebastian Redl28507842009-02-26 14:39:58 +00006290 bool Dependent = ArgTy->isDependentType();
6291
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006292 // We must have at least one component that refers to the type, and the first
6293 // one is known to be a field designator. Verify that the ArgTy represents
6294 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006295 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006296 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006297
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006298 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6299 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006300
Eli Friedman35183ac2009-02-27 06:44:11 +00006301 // Otherwise, create a null pointer as the base, and iteratively process
6302 // the offsetof designators.
6303 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6304 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006305 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006306 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006307
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006308 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6309 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006310 // FIXME: This diagnostic isn't actually visible because the location is in
6311 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006312 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006313 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6314 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006315
Sebastian Redl28507842009-02-26 14:39:58 +00006316 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006317 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006318
John McCalld00f2002009-11-04 03:03:43 +00006319 if (RequireCompleteType(TypeLoc, Res->getType(),
6320 diag::err_offsetof_incomplete_type))
6321 return ExprError();
6322
Sebastian Redl28507842009-02-26 14:39:58 +00006323 // FIXME: Dependent case loses a lot of information here. And probably
6324 // leaks like a sieve.
6325 for (unsigned i = 0; i != NumComponents; ++i) {
6326 const OffsetOfComponent &OC = CompPtr[i];
6327 if (OC.isBrackets) {
6328 // Offset of an array sub-field. TODO: Should we allow vector elements?
6329 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6330 if (!AT) {
6331 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006332 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6333 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006334 }
6335
6336 // FIXME: C++: Verify that operator[] isn't overloaded.
6337
Eli Friedman35183ac2009-02-27 06:44:11 +00006338 // Promote the array so it looks more like a normal array subscript
6339 // expression.
6340 DefaultFunctionArrayConversion(Res);
6341
Sebastian Redl28507842009-02-26 14:39:58 +00006342 // C99 6.5.2.1p1
6343 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006344 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006345 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006346 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006347 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006348 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006349
6350 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6351 OC.LocEnd);
6352 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006353 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006354
Ted Kremenek6217b802009-07-29 21:53:49 +00006355 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006356 if (!RC) {
6357 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006358 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6359 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006360 }
Chris Lattner704fe352007-08-30 17:59:59 +00006361
Sebastian Redl28507842009-02-26 14:39:58 +00006362 // Get the decl corresponding to this.
6363 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006364 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006365 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00006366 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6367 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6368 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006369 DidWarnAboutNonPOD = true;
6370 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006371 }
Mike Stump1eb44332009-09-09 15:08:12 +00006372
John McCalla24dc2e2009-11-17 02:14:36 +00006373 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6374 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006375
John McCall1bcee0a2009-12-02 08:25:40 +00006376 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006377 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006378 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006379 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6380 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006381
Sebastian Redl28507842009-02-26 14:39:58 +00006382 // FIXME: C++: Verify that MemberDecl isn't a static field.
6383 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006384 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006385 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006386 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006387 } else {
6388 // MemberDecl->getType() doesn't get the right qualifiers, but it
6389 // doesn't matter here.
6390 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6391 MemberDecl->getType().getNonReferenceType());
6392 }
Sebastian Redl28507842009-02-26 14:39:58 +00006393 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006394 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006395
Sebastian Redlf53597f2009-03-15 17:47:39 +00006396 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6397 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006398}
6399
6400
Sebastian Redlf53597f2009-03-15 17:47:39 +00006401Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6402 TypeTy *arg1,TypeTy *arg2,
6403 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006404 // FIXME: Preserve type source info.
6405 QualType argT1 = GetTypeFromParser(arg1);
6406 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006407
Steve Naroffd34e9152007-08-01 22:05:33 +00006408 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006409
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006410 if (getLangOptions().CPlusPlus) {
6411 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6412 << SourceRange(BuiltinLoc, RPLoc);
6413 return ExprError();
6414 }
6415
Sebastian Redlf53597f2009-03-15 17:47:39 +00006416 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6417 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006418}
6419
Sebastian Redlf53597f2009-03-15 17:47:39 +00006420Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6421 ExprArg cond,
6422 ExprArg expr1, ExprArg expr2,
6423 SourceLocation RPLoc) {
6424 Expr *CondExpr = static_cast<Expr*>(cond.get());
6425 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6426 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006427
Steve Naroffd04fdd52007-08-03 21:21:27 +00006428 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6429
Sebastian Redl28507842009-02-26 14:39:58 +00006430 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006431 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006432 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006433 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006434 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006435 } else {
6436 // The conditional expression is required to be a constant expression.
6437 llvm::APSInt condEval(32);
6438 SourceLocation ExpLoc;
6439 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006440 return ExprError(Diag(ExpLoc,
6441 diag::err_typecheck_choose_expr_requires_constant)
6442 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006443
Sebastian Redl28507842009-02-26 14:39:58 +00006444 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6445 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006446 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6447 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006448 }
6449
Sebastian Redlf53597f2009-03-15 17:47:39 +00006450 cond.release(); expr1.release(); expr2.release();
6451 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006452 resType, RPLoc,
6453 resType->isDependentType(),
6454 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006455}
6456
Steve Naroff4eb206b2008-09-03 18:15:37 +00006457//===----------------------------------------------------------------------===//
6458// Clang Extensions.
6459//===----------------------------------------------------------------------===//
6460
6461/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006462void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006463 // Analyze block parameters.
6464 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006465
Steve Naroff4eb206b2008-09-03 18:15:37 +00006466 // Add BSI to CurBlock.
6467 BSI->PrevBlockInfo = CurBlock;
6468 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006469
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006470 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006471 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006472 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006473 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006474 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6475 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006476
Steve Naroff090276f2008-10-10 01:28:17 +00006477 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006478 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006479}
6480
Mike Stump98eb8a72009-02-04 22:31:32 +00006481void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006482 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006483
6484 if (ParamInfo.getNumTypeObjects() == 0
6485 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006486 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006487 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6488
Mike Stump4eeab842009-04-28 01:10:27 +00006489 if (T->isArrayType()) {
6490 Diag(ParamInfo.getSourceRange().getBegin(),
6491 diag::err_block_returns_array);
6492 return;
6493 }
6494
Mike Stump98eb8a72009-02-04 22:31:32 +00006495 // The parameter list is optional, if there was none, assume ().
6496 if (!T->isFunctionType())
6497 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6498
6499 CurBlock->hasPrototype = true;
6500 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006501 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006502 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006503 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006504 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006505 // FIXME: remove the attribute.
6506 }
John McCall183700f2009-09-21 23:43:11 +00006507 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006508
Chris Lattner9097af12009-04-11 19:27:54 +00006509 // Do not allow returning a objc interface by-value.
6510 if (RetTy->isObjCInterfaceType()) {
6511 Diag(ParamInfo.getSourceRange().getBegin(),
6512 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6513 return;
6514 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006515 return;
6516 }
6517
Steve Naroff4eb206b2008-09-03 18:15:37 +00006518 // Analyze arguments to block.
6519 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6520 "Not a function declarator!");
6521 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006522
Steve Naroff090276f2008-10-10 01:28:17 +00006523 CurBlock->hasPrototype = FTI.hasPrototype;
6524 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006525
Steve Naroff4eb206b2008-09-03 18:15:37 +00006526 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6527 // no arguments, not a function that takes a single void argument.
6528 if (FTI.hasPrototype &&
6529 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006530 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6531 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006532 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006533 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006534 } else if (FTI.hasPrototype) {
6535 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006536 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006537 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006538 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006539 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006540 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006541 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006542 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006543 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6544 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6545 // If this has an identifier, add it to the scope stack.
6546 if ((*AI)->getIdentifier())
6547 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006548
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006549 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006550 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006551 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006552 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006553 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006554 // FIXME: remove the attribute.
6555 }
Mike Stump1eb44332009-09-09 15:08:12 +00006556
Chris Lattner9097af12009-04-11 19:27:54 +00006557 // Analyze the return type.
6558 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006559 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006560
Chris Lattner9097af12009-04-11 19:27:54 +00006561 // Do not allow returning a objc interface by-value.
6562 if (RetTy->isObjCInterfaceType()) {
6563 Diag(ParamInfo.getSourceRange().getBegin(),
6564 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6565 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006566 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006567}
6568
6569/// ActOnBlockError - If there is an error parsing a block, this callback
6570/// is invoked to pop the information about the block from the action impl.
6571void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6572 // Ensure that CurBlock is deleted.
6573 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006574
Chris Lattner17a78302009-04-19 05:28:12 +00006575 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6576
Steve Naroff4eb206b2008-09-03 18:15:37 +00006577 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006578 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006579 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006580 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006581}
6582
6583/// ActOnBlockStmtExpr - This is called when the body of a block statement
6584/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006585Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6586 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006587 // If blocks are disabled, emit an error.
6588 if (!LangOpts.Blocks)
6589 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006590
Steve Naroff4eb206b2008-09-03 18:15:37 +00006591 // Ensure that CurBlock is deleted.
6592 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006593
Steve Naroff090276f2008-10-10 01:28:17 +00006594 PopDeclContext();
6595
Steve Naroff4eb206b2008-09-03 18:15:37 +00006596 // Pop off CurBlock, handle nested blocks.
6597 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006598
Steve Naroff4eb206b2008-09-03 18:15:37 +00006599 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006600 if (!BSI->ReturnType.isNull())
6601 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006602
Steve Naroff4eb206b2008-09-03 18:15:37 +00006603 llvm::SmallVector<QualType, 8> ArgTypes;
6604 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6605 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006606
Mike Stump56925862009-07-28 22:04:01 +00006607 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006608 QualType BlockTy;
6609 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006610 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6611 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006612 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006613 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006614 BSI->isVariadic, 0, false, false, 0, 0,
6615 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006616
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006617 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006618 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006619 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006620
Chris Lattner17a78302009-04-19 05:28:12 +00006621 // If needed, diagnose invalid gotos and switches in the block.
6622 if (CurFunctionNeedsScopeChecking)
6623 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6624 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006625
Anders Carlssone9146f22009-05-01 19:49:17 +00006626 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006627 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006628 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6629 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006630}
6631
Sebastian Redlf53597f2009-03-15 17:47:39 +00006632Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6633 ExprArg expr, TypeTy *type,
6634 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006635 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006636 Expr *E = static_cast<Expr*>(expr.get());
6637 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006638
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006639 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006640
6641 // Get the va_list type
6642 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006643 if (VaListType->isArrayType()) {
6644 // Deal with implicit array decay; for example, on x86-64,
6645 // va_list is an array, but it's supposed to decay to
6646 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006647 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006648 // Make sure the input expression also decays appropriately.
6649 UsualUnaryConversions(E);
6650 } else {
6651 // Otherwise, the va_list argument must be an l-value because
6652 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006653 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006654 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006655 return ExprError();
6656 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006657
Douglas Gregordd027302009-05-19 23:10:31 +00006658 if (!E->isTypeDependent() &&
6659 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006660 return ExprError(Diag(E->getLocStart(),
6661 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006662 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006663 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006664
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006665 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006666 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006667
Sebastian Redlf53597f2009-03-15 17:47:39 +00006668 expr.release();
6669 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6670 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006671}
6672
Sebastian Redlf53597f2009-03-15 17:47:39 +00006673Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006674 // The type of __null will be int or long, depending on the size of
6675 // pointers on the target.
6676 QualType Ty;
6677 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6678 Ty = Context.IntTy;
6679 else
6680 Ty = Context.LongTy;
6681
Sebastian Redlf53597f2009-03-15 17:47:39 +00006682 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006683}
6684
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006685static void
6686MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6687 QualType DstType,
6688 Expr *SrcExpr,
6689 CodeModificationHint &Hint) {
6690 if (!SemaRef.getLangOptions().ObjC1)
6691 return;
6692
6693 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6694 if (!PT)
6695 return;
6696
6697 // Check if the destination is of type 'id'.
6698 if (!PT->isObjCIdType()) {
6699 // Check if the destination is the 'NSString' interface.
6700 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6701 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6702 return;
6703 }
6704
6705 // Strip off any parens and casts.
6706 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6707 if (!SL || SL->isWide())
6708 return;
6709
6710 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6711}
6712
Chris Lattner5cf216b2008-01-04 18:04:52 +00006713bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6714 SourceLocation Loc,
6715 QualType DstType, QualType SrcType,
6716 Expr *SrcExpr, const char *Flavor) {
6717 // Decode the result (notice that AST's are still created for extensions).
6718 bool isInvalid = false;
6719 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006720 CodeModificationHint Hint;
6721
Chris Lattner5cf216b2008-01-04 18:04:52 +00006722 switch (ConvTy) {
6723 default: assert(0 && "Unknown conversion type");
6724 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006725 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006726 DiagKind = diag::ext_typecheck_convert_pointer_int;
6727 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006728 case IntToPointer:
6729 DiagKind = diag::ext_typecheck_convert_int_pointer;
6730 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006731 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006732 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006733 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6734 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006735 case IncompatiblePointerSign:
6736 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6737 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006738 case FunctionVoidPointer:
6739 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6740 break;
6741 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006742 // If the qualifiers lost were because we were applying the
6743 // (deprecated) C++ conversion from a string literal to a char*
6744 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6745 // Ideally, this check would be performed in
6746 // CheckPointerTypesForAssignment. However, that would require a
6747 // bit of refactoring (so that the second argument is an
6748 // expression, rather than a type), which should be done as part
6749 // of a larger effort to fix CheckPointerTypesForAssignment for
6750 // C++ semantics.
6751 if (getLangOptions().CPlusPlus &&
6752 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6753 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006754 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6755 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006756 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006757 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006758 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006759 case IntToBlockPointer:
6760 DiagKind = diag::err_int_to_block_pointer;
6761 break;
6762 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006763 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006764 break;
Steve Naroff39579072008-10-14 22:18:38 +00006765 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006766 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006767 // it can give a more specific diagnostic.
6768 DiagKind = diag::warn_incompatible_qualified_id;
6769 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006770 case IncompatibleVectors:
6771 DiagKind = diag::warn_incompatible_vectors;
6772 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006773 case Incompatible:
6774 DiagKind = diag::err_typecheck_convert_incompatible;
6775 isInvalid = true;
6776 break;
6777 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006778
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006779 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006780 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006781 return isInvalid;
6782}
Anders Carlssone21555e2008-11-30 19:50:32 +00006783
Chris Lattner3bf68932009-04-25 21:59:05 +00006784bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006785 llvm::APSInt ICEResult;
6786 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6787 if (Result)
6788 *Result = ICEResult;
6789 return false;
6790 }
6791
Anders Carlssone21555e2008-11-30 19:50:32 +00006792 Expr::EvalResult EvalResult;
6793
Mike Stumpeed9cac2009-02-19 03:04:26 +00006794 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006795 EvalResult.HasSideEffects) {
6796 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6797
6798 if (EvalResult.Diag) {
6799 // We only show the note if it's not the usual "invalid subexpression"
6800 // or if it's actually in a subexpression.
6801 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6802 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6803 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6804 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006805
Anders Carlssone21555e2008-11-30 19:50:32 +00006806 return true;
6807 }
6808
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006809 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6810 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006811
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006812 if (EvalResult.Diag &&
6813 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6814 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006815
Anders Carlssone21555e2008-11-30 19:50:32 +00006816 if (Result)
6817 *Result = EvalResult.Val.getInt();
6818 return false;
6819}
Douglas Gregore0762c92009-06-19 23:52:42 +00006820
Douglas Gregor2afce722009-11-26 00:44:06 +00006821void
Mike Stump1eb44332009-09-09 15:08:12 +00006822Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00006823 ExprEvalContexts.push_back(
6824 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00006825}
6826
Mike Stump1eb44332009-09-09 15:08:12 +00006827void
Douglas Gregor2afce722009-11-26 00:44:06 +00006828Sema::PopExpressionEvaluationContext() {
6829 // Pop the current expression evaluation context off the stack.
6830 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6831 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006832
Douglas Gregor2afce722009-11-26 00:44:06 +00006833 if (Rec.Context == PotentiallyPotentiallyEvaluated &&
6834 Rec.PotentiallyReferenced) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006835 // Mark any remaining declarations in the current position of the stack
6836 // as "referenced". If they were not meant to be referenced, semantic
6837 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Douglas Gregor2afce722009-11-26 00:44:06 +00006838 for (PotentiallyReferencedDecls::iterator
6839 I = Rec.PotentiallyReferenced->begin(),
6840 IEnd = Rec.PotentiallyReferenced->end();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006841 I != IEnd; ++I)
6842 MarkDeclarationReferenced(I->first, I->second);
Douglas Gregor2afce722009-11-26 00:44:06 +00006843 }
6844
6845 // When are coming out of an unevaluated context, clear out any
6846 // temporaries that we may have created as part of the evaluation of
6847 // the expression in that context: they aren't relevant because they
6848 // will never be constructed.
6849 if (Rec.Context == Unevaluated &&
6850 ExprTemporaries.size() > Rec.NumTemporaries)
6851 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6852 ExprTemporaries.end());
6853
6854 // Destroy the popped expression evaluation record.
6855 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006856}
Douglas Gregore0762c92009-06-19 23:52:42 +00006857
6858/// \brief Note that the given declaration was referenced in the source code.
6859///
6860/// This routine should be invoke whenever a given declaration is referenced
6861/// in the source code, and where that reference occurred. If this declaration
6862/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6863/// C99 6.9p3), then the declaration will be marked as used.
6864///
6865/// \param Loc the location where the declaration was referenced.
6866///
6867/// \param D the declaration that has been referenced by the source code.
6868void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6869 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006870
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006871 if (D->isUsed())
6872 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006873
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006874 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6875 // template or not. The reason for this is that unevaluated expressions
6876 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6877 // -Wunused-parameters)
6878 if (isa<ParmVarDecl>(D) ||
6879 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006880 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006881
Douglas Gregore0762c92009-06-19 23:52:42 +00006882 // Do not mark anything as "used" within a dependent context; wait for
6883 // an instantiation.
6884 if (CurContext->isDependentContext())
6885 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006886
Douglas Gregor2afce722009-11-26 00:44:06 +00006887 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006888 case Unevaluated:
6889 // We are in an expression that is not potentially evaluated; do nothing.
6890 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006891
Douglas Gregorac7610d2009-06-22 20:57:11 +00006892 case PotentiallyEvaluated:
6893 // We are in a potentially-evaluated expression, so this declaration is
6894 // "used"; handle this below.
6895 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006896
Douglas Gregorac7610d2009-06-22 20:57:11 +00006897 case PotentiallyPotentiallyEvaluated:
6898 // We are in an expression that may be potentially evaluated; queue this
6899 // declaration reference until we know whether the expression is
6900 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00006901 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00006902 return;
6903 }
Mike Stump1eb44332009-09-09 15:08:12 +00006904
Douglas Gregore0762c92009-06-19 23:52:42 +00006905 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006906 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006907 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006908 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6909 if (!Constructor->isUsed())
6910 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006911 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006912 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006913 if (!Constructor->isUsed())
6914 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6915 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006916 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6917 if (Destructor->isImplicit() && !Destructor->isUsed())
6918 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006919
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006920 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6921 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6922 MethodDecl->getOverloadedOperator() == OO_Equal) {
6923 if (!MethodDecl->isUsed())
6924 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6925 }
6926 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006927 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006928 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006929 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006930 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006931 bool AlreadyInstantiated = false;
6932 if (FunctionTemplateSpecializationInfo *SpecInfo
6933 = Function->getTemplateSpecializationInfo()) {
6934 if (SpecInfo->getPointOfInstantiation().isInvalid())
6935 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006936 else if (SpecInfo->getTemplateSpecializationKind()
6937 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006938 AlreadyInstantiated = true;
6939 } else if (MemberSpecializationInfo *MSInfo
6940 = Function->getMemberSpecializationInfo()) {
6941 if (MSInfo->getPointOfInstantiation().isInvalid())
6942 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006943 else if (MSInfo->getTemplateSpecializationKind()
6944 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006945 AlreadyInstantiated = true;
6946 }
6947
6948 if (!AlreadyInstantiated)
6949 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6950 }
6951
Douglas Gregore0762c92009-06-19 23:52:42 +00006952 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006953 Function->setUsed(true);
6954 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006955 }
Mike Stump1eb44332009-09-09 15:08:12 +00006956
Douglas Gregore0762c92009-06-19 23:52:42 +00006957 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006958 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006959 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006960 Var->getInstantiatedFromStaticDataMember()) {
6961 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6962 assert(MSInfo && "Missing member specialization information?");
6963 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6964 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6965 MSInfo->setPointOfInstantiation(Loc);
6966 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6967 }
6968 }
Mike Stump1eb44332009-09-09 15:08:12 +00006969
Douglas Gregore0762c92009-06-19 23:52:42 +00006970 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006971
Douglas Gregore0762c92009-06-19 23:52:42 +00006972 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006973 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006974 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006975}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006976
6977bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6978 CallExpr *CE, FunctionDecl *FD) {
6979 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6980 return false;
6981
6982 PartialDiagnostic Note =
6983 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6984 << FD->getDeclName() : PDiag();
6985 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6986
6987 if (RequireCompleteType(Loc, ReturnType,
6988 FD ?
6989 PDiag(diag::err_call_function_incomplete_return)
6990 << CE->getSourceRange() << FD->getDeclName() :
6991 PDiag(diag::err_call_incomplete_return)
6992 << CE->getSourceRange(),
6993 std::make_pair(NoteLoc, Note)))
6994 return true;
6995
6996 return false;
6997}
6998
John McCall5a881bb2009-10-12 21:59:07 +00006999// Diagnose the common s/=/==/ typo. Note that adding parentheses
7000// will prevent this condition from triggering, which is what we want.
7001void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7002 SourceLocation Loc;
7003
John McCalla52ef082009-11-11 02:41:58 +00007004 unsigned diagnostic = diag::warn_condition_is_assignment;
7005
John McCall5a881bb2009-10-12 21:59:07 +00007006 if (isa<BinaryOperator>(E)) {
7007 BinaryOperator *Op = cast<BinaryOperator>(E);
7008 if (Op->getOpcode() != BinaryOperator::Assign)
7009 return;
7010
John McCallc8d8ac52009-11-12 00:06:05 +00007011 // Greylist some idioms by putting them into a warning subcategory.
7012 if (ObjCMessageExpr *ME
7013 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7014 Selector Sel = ME->getSelector();
7015
John McCallc8d8ac52009-11-12 00:06:05 +00007016 // self = [<foo> init...]
7017 if (isSelfExpr(Op->getLHS())
7018 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7019 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7020
7021 // <foo> = [<bar> nextObject]
7022 else if (Sel.isUnarySelector() &&
7023 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7024 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7025 }
John McCalla52ef082009-11-11 02:41:58 +00007026
John McCall5a881bb2009-10-12 21:59:07 +00007027 Loc = Op->getOperatorLoc();
7028 } else if (isa<CXXOperatorCallExpr>(E)) {
7029 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7030 if (Op->getOperator() != OO_Equal)
7031 return;
7032
7033 Loc = Op->getOperatorLoc();
7034 } else {
7035 // Not an assignment.
7036 return;
7037 }
7038
John McCall5a881bb2009-10-12 21:59:07 +00007039 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007040 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007041
John McCalla52ef082009-11-11 02:41:58 +00007042 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007043 << E->getSourceRange()
7044 << CodeModificationHint::CreateInsertion(Open, "(")
7045 << CodeModificationHint::CreateInsertion(Close, ")");
7046}
7047
7048bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7049 DiagnoseAssignmentAsCondition(E);
7050
7051 if (!E->isTypeDependent()) {
7052 DefaultFunctionArrayConversion(E);
7053
7054 QualType T = E->getType();
7055
7056 if (getLangOptions().CPlusPlus) {
7057 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7058 return true;
7059 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7060 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7061 << T << E->getSourceRange();
7062 return true;
7063 }
7064 }
7065
7066 return false;
7067}