blob: dfd9555d03a87c88ae70be44b998c19f0459577a [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"
Douglas Gregor99a2e602009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000020#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000021#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/Lex/LiteralSupport.h"
26#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000027#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000028#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000029#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000030#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
David Chisnall0f436562009-08-17 16:35:33 +000033
Douglas Gregor48f3bb92009-02-18 21:56:37 +000034/// \brief Determine whether the use of this declaration is valid, and
35/// emit any corresponding diagnostics.
36///
37/// This routine diagnoses various problems with referencing
38/// declarations that can occur when using a declaration. For example,
39/// it might warn if a deprecated or unavailable declaration is being
40/// used, or produce an error (and return true) if a C++0x deleted
41/// function is being used.
42///
Chris Lattner52338262009-10-25 22:31:57 +000043/// If IgnoreDeprecated is set to true, this should not want about deprecated
44/// decls.
45///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000046/// \returns true if there was an error (this declaration cannot be
47/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000048///
John McCall54abf7d2009-11-04 02:18:39 +000049bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000050 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000051 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000052 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000053 }
54
Chris Lattnerffb93682009-10-25 17:21:40 +000055 // See if the decl is unavailable
56 if (D->getAttr<UnavailableAttr>()) {
57 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
58 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
59 }
60
Douglas Gregor48f3bb92009-02-18 21:56:37 +000061 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000062 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000063 if (FD->isDeleted()) {
64 Diag(Loc, diag::err_deleted_function_use);
65 Diag(D->getLocation(), diag::note_unavailable_here) << true;
66 return true;
67 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000068 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000069
Douglas Gregor48f3bb92009-02-18 21:56:37 +000070 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000071}
72
Fariborz Jahanian5b530052009-05-13 18:09:35 +000073/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000074/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000075/// attribute. It warns if call does not have the sentinel argument.
76///
77void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000078 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000079 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000080 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000081 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000082 int sentinelPos = attr->getSentinel();
83 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000084
Mike Stump390b4cc2009-05-16 07:39:55 +000085 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
86 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000087 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000088 bool warnNotEnoughArgs = false;
89 int isMethod = 0;
90 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
91 // skip over named parameters.
92 ObjCMethodDecl::param_iterator P, E = MD->param_end();
93 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
94 if (nullPos)
95 --nullPos;
96 else
97 ++i;
98 }
99 warnNotEnoughArgs = (P != E || i >= NumArgs);
100 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000101 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000102 // skip over named parameters.
103 ObjCMethodDecl::param_iterator P, E = FD->param_end();
104 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
105 if (nullPos)
106 --nullPos;
107 else
108 ++i;
109 }
110 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000111 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000112 // block or function pointer call.
113 QualType Ty = V->getType();
114 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000115 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000116 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
117 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000118 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
119 unsigned NumArgsInProto = Proto->getNumArgs();
120 unsigned k;
121 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
122 if (nullPos)
123 --nullPos;
124 else
125 ++i;
126 }
127 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
128 }
129 if (Ty->isBlockPointerType())
130 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000131 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000132 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000133 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000134 return;
135
136 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000137 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000138 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000139 return;
140 }
141 int sentinel = i;
142 while (sentinelPos > 0 && i < NumArgs-1) {
143 --sentinelPos;
144 ++i;
145 }
146 if (sentinelPos > 0) {
147 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000148 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000149 return;
150 }
151 while (i < NumArgs-1) {
152 ++i;
153 ++sentinel;
154 }
155 Expr *sentinelExpr = Args[sentinel];
Anders Carlssone4d2bdd2009-11-24 17:24:21 +0000156 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
157 (!sentinelExpr->getType()->isPointerType() ||
158 !sentinelExpr->isNullPointerConstant(Context,
159 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000160 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000161 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000162 }
163 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000164}
165
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000166SourceRange Sema::getExprRange(ExprTy *E) const {
167 Expr *Ex = (Expr *)E;
168 return Ex? Ex->getSourceRange() : SourceRange();
169}
170
Chris Lattnere7a2e912008-07-25 21:10:04 +0000171//===----------------------------------------------------------------------===//
172// Standard Promotions and Conversions
173//===----------------------------------------------------------------------===//
174
Chris Lattnere7a2e912008-07-25 21:10:04 +0000175/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
176void Sema::DefaultFunctionArrayConversion(Expr *&E) {
177 QualType Ty = E->getType();
178 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
179
Chris Lattnere7a2e912008-07-25 21:10:04 +0000180 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000181 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000182 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000183 else if (Ty->isArrayType()) {
184 // In C90 mode, arrays only promote to pointers if the array expression is
185 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
186 // type 'array of type' is converted to an expression that has type 'pointer
187 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
188 // that has type 'array of type' ...". The relevant change is "an lvalue"
189 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000190 //
191 // C++ 4.2p1:
192 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
193 // T" can be converted to an rvalue of type "pointer to T".
194 //
195 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
196 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000197 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
198 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000199 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000200}
201
202/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000203/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000204/// sometimes surpressed. For example, the array->pointer conversion doesn't
205/// apply if the array is an argument to the sizeof or address (&) operators.
206/// In these instances, this routine should *not* be called.
207Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
208 QualType Ty = Expr->getType();
209 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Douglas Gregorfc24e442009-05-01 20:41:21 +0000211 // C99 6.3.1.1p2:
212 //
213 // The following may be used in an expression wherever an int or
214 // unsigned int may be used:
215 // - an object or expression with an integer type whose integer
216 // conversion rank is less than or equal to the rank of int
217 // and unsigned int.
218 // - A bit-field of type _Bool, int, signed int, or unsigned int.
219 //
220 // If an int can represent all values of the original type, the
221 // value is converted to an int; otherwise, it is converted to an
222 // unsigned int. These are called the integer promotions. All
223 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000224 QualType PTy = Context.isPromotableBitField(Expr);
225 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000226 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000227 return Expr;
228 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000229 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000230 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000231 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000232 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000233 }
234
Douglas Gregorfc24e442009-05-01 20:41:21 +0000235 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000236 return Expr;
237}
238
Chris Lattner05faf172008-07-25 22:25:12 +0000239/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000240/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000241/// double. All other argument types are converted by UsualUnaryConversions().
242void Sema::DefaultArgumentPromotion(Expr *&Expr) {
243 QualType Ty = Expr->getType();
244 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattner05faf172008-07-25 22:25:12 +0000246 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000247 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000248 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000249 return ImpCastExprToType(Expr, Context.DoubleTy,
250 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattner05faf172008-07-25 22:25:12 +0000252 UsualUnaryConversions(Expr);
253}
254
Chris Lattner312531a2009-04-12 08:11:20 +0000255/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
256/// will warn if the resulting type is not a POD type, and rejects ObjC
257/// interfaces passed by value. This returns true if the argument type is
258/// completely illegal.
259bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000260 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Chris Lattner312531a2009-04-12 08:11:20 +0000262 if (Expr->getType()->isObjCInterfaceType()) {
Douglas Gregor75b699a2009-12-12 07:25:49 +0000263 switch (ExprEvalContexts.back().Context ) {
264 case Unevaluated:
265 // The argument will never be evaluated, so don't complain.
266 break;
267
268 case PotentiallyEvaluated:
269 Diag(Expr->getLocStart(),
270 diag::err_cannot_pass_objc_interface_to_vararg)
271 << Expr->getType() << CT;
272 return true;
273
274 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +0000275 ExprEvalContexts.back().addDiagnostic(Expr->getLocStart(),
276 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
277 << Expr->getType() << CT);
Douglas Gregor75b699a2009-12-12 07:25:49 +0000278 break;
279 }
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000280 }
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Douglas Gregor75b699a2009-12-12 07:25:49 +0000282 if (!Expr->getType()->isPODType()) {
283 switch (ExprEvalContexts.back().Context ) {
284 case Unevaluated:
285 // The argument will never be evaluated, so don't complain.
286 break;
287
288 case PotentiallyEvaluated:
289 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
290 << Expr->getType() << CT;
291 break;
292
293 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +0000294 ExprEvalContexts.back().addDiagnostic(Expr->getLocStart(),
295 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
296 << Expr->getType() << CT);
Douglas Gregor75b699a2009-12-12 07:25:49 +0000297 break;
298 }
299 }
Chris Lattner312531a2009-04-12 08:11:20 +0000300
301 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000302}
303
304
Chris Lattnere7a2e912008-07-25 21:10:04 +0000305/// UsualArithmeticConversions - Performs various conversions that are common to
306/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000307/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000308/// responsible for emitting appropriate error diagnostics.
309/// FIXME: verify the conversion rules for "complex int" are consistent with
310/// GCC.
311QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
312 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000313 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000314 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000315
316 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000317
Mike Stump1eb44332009-09-09 15:08:12 +0000318 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000319 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000320 QualType lhs =
321 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000322 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000323 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000324
325 // If both types are identical, no conversion is needed.
326 if (lhs == rhs)
327 return lhs;
328
329 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
330 // The caller can deal with this (e.g. pointer + int).
331 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
332 return lhs;
333
Douglas Gregor2d833e32009-05-02 00:36:19 +0000334 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000335 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000336 if (!LHSBitfieldPromoteTy.isNull())
337 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000338 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000339 if (!RHSBitfieldPromoteTy.isNull())
340 rhs = RHSBitfieldPromoteTy;
341
Eli Friedmana95d7572009-08-19 07:44:53 +0000342 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000343 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000344 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
345 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000346 return destType;
347}
348
Chris Lattnere7a2e912008-07-25 21:10:04 +0000349//===----------------------------------------------------------------------===//
350// Semantic Analysis for various Expression Types
351//===----------------------------------------------------------------------===//
352
353
Steve Narofff69936d2007-09-16 03:34:24 +0000354/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000355/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
356/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
357/// multiple tokens. However, the common case is that StringToks points to one
358/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000359///
360Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000361Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 assert(NumStringToks && "Must have at least one string!");
363
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000364 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000366 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000367
368 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
369 for (unsigned i = 0; i != NumStringToks; ++i)
370 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000371
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000372 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000373 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000374 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000375
376 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
377 if (getLangOptions().CPlusPlus)
378 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000379
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000380 // Get an array type for the string, according to C99 6.4.5. This includes
381 // the nul terminator character as well as the string length for pascal
382 // strings.
383 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000384 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000385 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000388 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000389 Literal.GetStringLength(),
390 Literal.AnyWide, StrTy,
391 &StringTokLocs[0],
392 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000393}
394
Chris Lattner639e2d32008-10-20 05:16:36 +0000395/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
396/// CurBlock to VD should cause it to be snapshotted (as we do for auto
397/// variables defined outside the block) or false if this is not needed (e.g.
398/// for values inside the block or for globals).
399///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000400/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
401/// up-to-date.
402///
Chris Lattner639e2d32008-10-20 05:16:36 +0000403static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
404 ValueDecl *VD) {
405 // If the value is defined inside the block, we couldn't snapshot it even if
406 // we wanted to.
407 if (CurBlock->TheDecl == VD->getDeclContext())
408 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner639e2d32008-10-20 05:16:36 +0000410 // If this is an enum constant or function, it is constant, don't snapshot.
411 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
412 return false;
413
414 // If this is a reference to an extern, static, or global variable, no need to
415 // snapshot it.
416 // FIXME: What about 'const' variables in C++?
417 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000418 if (!Var->hasLocalStorage())
419 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000421 // Blocks that have these can't be constant.
422 CurBlock->hasBlockDeclRefExprs = true;
423
424 // If we have nested blocks, the decl may be declared in an outer block (in
425 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
426 // be defined outside all of the current blocks (in which case the blocks do
427 // all get the bit). Walk the nesting chain.
428 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
429 NextBlock = NextBlock->PrevBlockInfo) {
430 // If we found the defining block for the variable, don't mark the block as
431 // having a reference outside it.
432 if (NextBlock->TheDecl == VD->getDeclContext())
433 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000435 // Otherwise, the DeclRef from the inner block causes the outer one to need
436 // a snapshot as well.
437 NextBlock->hasBlockDeclRefExprs = true;
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner639e2d32008-10-20 05:16:36 +0000440 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000441}
442
Chris Lattner639e2d32008-10-20 05:16:36 +0000443
444
Douglas Gregora2813ce2009-10-23 18:54:35 +0000445/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000446Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000447Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000448 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000449 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
450 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000451 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000452 << D->getDeclName();
453 return ExprError();
454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Anders Carlssone41590d2009-06-24 00:10:43 +0000456 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
457 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
458 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
459 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000460 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000461 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000462 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000463 << D->getIdentifier();
464 return ExprError();
465 }
466 }
467 }
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Douglas Gregore0762c92009-06-19 23:52:42 +0000470 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Douglas Gregora2813ce2009-10-23 18:54:35 +0000472 return Owned(DeclRefExpr::Create(Context,
473 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
474 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000475 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000476}
477
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000478/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
479/// variable corresponding to the anonymous union or struct whose type
480/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000481static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
482 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000483 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000484 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Mike Stump390b4cc2009-05-16 07:39:55 +0000486 // FIXME: Once Decls are directly linked together, this will be an O(1)
487 // operation rather than a slow walk through DeclContext's vector (which
488 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000489 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000490 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000491 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000492 D != DEnd; ++D) {
493 if (*D == Record) {
494 // The object for the anonymous struct/union directly
495 // follows its type in the list of declarations.
496 ++D;
497 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000498 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000499 return *D;
500 }
501 }
502
503 assert(false && "Missing object for anonymous record");
504 return 0;
505}
506
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000507/// \brief Given a field that represents a member of an anonymous
508/// struct/union, build the path from that field's context to the
509/// actual member.
510///
511/// Construct the sequence of field member references we'll have to
512/// perform to get to the field in the anonymous union/struct. The
513/// list of members is built from the field outward, so traverse it
514/// backwards to go from an object in the current context to the field
515/// we found.
516///
517/// \returns The variable from which the field access should begin,
518/// for an anonymous struct/union that is not a member of another
519/// class. Otherwise, returns NULL.
520VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
521 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000522 assert(Field->getDeclContext()->isRecord() &&
523 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
524 && "Field must be stored inside an anonymous struct or union");
525
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000526 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000527 VarDecl *BaseObject = 0;
528 DeclContext *Ctx = Field->getDeclContext();
529 do {
530 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000531 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000532 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000533 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000534 else {
535 BaseObject = cast<VarDecl>(AnonObject);
536 break;
537 }
538 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000539 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000540 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000541
542 return BaseObject;
543}
544
545Sema::OwningExprResult
546Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
547 FieldDecl *Field,
548 Expr *BaseObjectExpr,
549 SourceLocation OpLoc) {
550 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000551 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000552 AnonFields);
553
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000554 // Build the expression that refers to the base object, from
555 // which we will build a sequence of member references to each
556 // of the anonymous union objects and, eventually, the field we
557 // found via name lookup.
558 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000559 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000560 if (BaseObject) {
561 // BaseObject is an anonymous struct/union variable (and is,
562 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000563 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000564 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000566 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000567 BaseQuals
568 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000569 } else if (BaseObjectExpr) {
570 // The caller provided the base object expression. Determine
571 // whether its a pointer and whether it adds any qualifiers to the
572 // anonymous struct/union fields we're looking into.
573 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000574 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000575 BaseObjectIsPointer = true;
576 ObjectType = ObjectPtr->getPointeeType();
577 }
John McCall0953e762009-09-24 19:53:00 +0000578 BaseQuals
579 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000580 } else {
581 // We've found a member of an anonymous struct/union that is
582 // inside a non-anonymous struct/union, so in a well-formed
583 // program our base object expression is "this".
584 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
585 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000586 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000587 = Context.getTagDeclType(
588 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
589 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000590 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000591 == Context.getCanonicalType(ThisType)) ||
592 IsDerivedFrom(ThisType, AnonFieldType)) {
593 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000594 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000595 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000596 BaseObjectIsPointer = true;
597 }
598 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000599 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
600 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000601 }
John McCall0953e762009-09-24 19:53:00 +0000602 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000603 }
604
Mike Stump1eb44332009-09-09 15:08:12 +0000605 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000606 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
607 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000608 }
609
610 // Build the implicit member references to the field of the
611 // anonymous struct/union.
612 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000613 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000614 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
615 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
616 FI != FIEnd; ++FI) {
617 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000618 Qualifiers MemberTypeQuals =
619 Context.getCanonicalType(MemberType).getQualifiers();
620
621 // CVR attributes from the base are picked up by members,
622 // except that 'mutable' members don't pick up 'const'.
623 if ((*FI)->isMutable())
624 ResultQuals.removeConst();
625
626 // GC attributes are never picked up by members.
627 ResultQuals.removeObjCGCAttr();
628
629 // TR 18037 does not allow fields to be declared with address spaces.
630 assert(!MemberTypeQuals.hasAddressSpace());
631
632 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
633 if (NewQuals != MemberTypeQuals)
634 MemberType = Context.getQualifiedType(MemberType, NewQuals);
635
Douglas Gregore0762c92009-06-19 23:52:42 +0000636 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman16c53782009-12-04 07:18:51 +0000637 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000638 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000639 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
640 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000641 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000642 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000643 }
644
Sebastian Redlcd965b92009-01-18 18:53:16 +0000645 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000646}
647
John McCall129e2df2009-11-30 22:42:35 +0000648/// Decomposes the given name into a DeclarationName, its location, and
649/// possibly a list of template arguments.
650///
651/// If this produces template arguments, it is permitted to call
652/// DecomposeTemplateName.
653///
654/// This actually loses a lot of source location information for
655/// non-standard name kinds; we should consider preserving that in
656/// some way.
657static void DecomposeUnqualifiedId(Sema &SemaRef,
658 const UnqualifiedId &Id,
659 TemplateArgumentListInfo &Buffer,
660 DeclarationName &Name,
661 SourceLocation &NameLoc,
662 const TemplateArgumentListInfo *&TemplateArgs) {
663 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
664 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
665 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
666
667 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
668 Id.TemplateId->getTemplateArgs(),
669 Id.TemplateId->NumArgs);
670 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
671 TemplateArgsPtr.release();
672
673 TemplateName TName =
674 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
675
676 Name = SemaRef.Context.getNameForTemplate(TName);
677 NameLoc = Id.TemplateId->TemplateNameLoc;
678 TemplateArgs = &Buffer;
679 } else {
680 Name = SemaRef.GetNameFromUnqualifiedId(Id);
681 NameLoc = Id.StartLocation;
682 TemplateArgs = 0;
683 }
684}
685
686/// Decompose the given template name into a list of lookup results.
687///
688/// The unqualified ID must name a non-dependent template, which can
689/// be more easily tested by checking whether DecomposeUnqualifiedId
690/// found template arguments.
691static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
692 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
693 TemplateName TName =
694 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
695
John McCallf7a1a742009-11-24 19:00:30 +0000696 if (TemplateDecl *TD = TName.getAsTemplateDecl())
697 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000698 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
699 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
700 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000701 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000702
John McCallf7a1a742009-11-24 19:00:30 +0000703 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000704}
705
John McCall129e2df2009-11-30 22:42:35 +0000706static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
707 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
708 E = Record->bases_end(); I != E; ++I) {
709 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
710 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
711 if (!BaseRT) return false;
712
713 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
714 if (!BaseRecord->isDefinition() ||
715 !IsFullyFormedScope(SemaRef, BaseRecord))
716 return false;
717 }
718
719 return true;
720}
721
John McCalle1599ce2009-11-30 23:50:49 +0000722/// Determines whether we can lookup this id-expression now or whether
723/// we have to wait until template instantiation is complete.
724static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000725 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000726
John McCalle1599ce2009-11-30 23:50:49 +0000727 // If the qualifier scope isn't computable, it's definitely dependent.
728 if (!DC) return true;
729
730 // If the qualifier scope doesn't name a record, we can always look into it.
731 if (!isa<CXXRecordDecl>(DC)) return false;
732
733 // We can't look into record types unless they're fully-formed.
734 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
735
John McCallaa81e162009-12-01 22:10:20 +0000736 return false;
737}
John McCalle1599ce2009-11-30 23:50:49 +0000738
John McCallaa81e162009-12-01 22:10:20 +0000739/// Determines if the given class is provably not derived from all of
740/// the prospective base classes.
741static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
742 CXXRecordDecl *Record,
743 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000744 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000745 return false;
746
John McCallb1b42562009-12-01 22:28:41 +0000747 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
748 if (!RD) return false;
749 Record = cast<CXXRecordDecl>(RD);
750
John McCallaa81e162009-12-01 22:10:20 +0000751 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
752 E = Record->bases_end(); I != E; ++I) {
753 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
754 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
755 if (!BaseRT) return false;
756
757 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000758 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
759 return false;
760 }
761
762 return true;
763}
764
John McCall144238e2009-12-02 20:26:00 +0000765/// Determines if this is an instance member of a class.
766static bool IsInstanceMember(NamedDecl *D) {
John McCall3b4294e2009-12-16 12:17:52 +0000767 assert(D->isCXXClassMember() &&
John McCallaa81e162009-12-01 22:10:20 +0000768 "checking whether non-member is instance member");
769
770 if (isa<FieldDecl>(D)) return true;
771
772 if (isa<CXXMethodDecl>(D))
773 return !cast<CXXMethodDecl>(D)->isStatic();
774
775 if (isa<FunctionTemplateDecl>(D)) {
776 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
777 return !cast<CXXMethodDecl>(D)->isStatic();
778 }
779
780 return false;
781}
782
783enum IMAKind {
784 /// The reference is definitely not an instance member access.
785 IMA_Static,
786
787 /// The reference may be an implicit instance member access.
788 IMA_Mixed,
789
790 /// The reference may be to an instance member, but it is invalid if
791 /// so, because the context is not an instance method.
792 IMA_Mixed_StaticContext,
793
794 /// The reference may be to an instance member, but it is invalid if
795 /// so, because the context is from an unrelated class.
796 IMA_Mixed_Unrelated,
797
798 /// The reference is definitely an implicit instance member access.
799 IMA_Instance,
800
801 /// The reference may be to an unresolved using declaration.
802 IMA_Unresolved,
803
804 /// The reference may be to an unresolved using declaration and the
805 /// context is not an instance method.
806 IMA_Unresolved_StaticContext,
807
808 /// The reference is to a member of an anonymous structure in a
809 /// non-class context.
810 IMA_AnonymousMember,
811
812 /// All possible referrents are instance members and the current
813 /// context is not an instance method.
814 IMA_Error_StaticContext,
815
816 /// All possible referrents are instance members of an unrelated
817 /// class.
818 IMA_Error_Unrelated
819};
820
821/// The given lookup names class member(s) and is not being used for
822/// an address-of-member expression. Classify the type of access
823/// according to whether it's possible that this reference names an
824/// instance member. This is best-effort; it is okay to
825/// conservatively answer "yes", in which case some errors will simply
826/// not be caught until template-instantiation.
827static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
828 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000829 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000830
831 bool isStaticContext =
832 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
833 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
834
835 if (R.isUnresolvableResult())
836 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
837
838 // Collect all the declaring classes of instance members we find.
839 bool hasNonInstance = false;
840 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
841 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
842 NamedDecl *D = (*I)->getUnderlyingDecl();
843 if (IsInstanceMember(D)) {
844 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
845
846 // If this is a member of an anonymous record, move out to the
847 // innermost non-anonymous struct or union. If there isn't one,
848 // that's a special case.
849 while (R->isAnonymousStructOrUnion()) {
850 R = dyn_cast<CXXRecordDecl>(R->getParent());
851 if (!R) return IMA_AnonymousMember;
852 }
853 Classes.insert(R->getCanonicalDecl());
854 }
855 else
856 hasNonInstance = true;
857 }
858
859 // If we didn't find any instance members, it can't be an implicit
860 // member reference.
861 if (Classes.empty())
862 return IMA_Static;
863
864 // If the current context is not an instance method, it can't be
865 // an implicit member reference.
866 if (isStaticContext)
867 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
868
869 // If we can prove that the current context is unrelated to all the
870 // declaring classes, it can't be an implicit member reference (in
871 // which case it's an error if any of those members are selected).
872 if (IsProvablyNotDerivedFrom(SemaRef,
873 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
874 Classes))
875 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
876
877 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
878}
879
880/// Diagnose a reference to a field with no object available.
881static void DiagnoseInstanceReference(Sema &SemaRef,
882 const CXXScopeSpec &SS,
883 const LookupResult &R) {
884 SourceLocation Loc = R.getNameLoc();
885 SourceRange Range(Loc);
886 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
887
888 if (R.getAsSingle<FieldDecl>()) {
889 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
890 if (MD->isStatic()) {
891 // "invalid use of member 'x' in static member function"
892 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
893 << Range << R.getLookupName();
894 return;
895 }
896 }
897
898 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
899 << R.getLookupName() << Range;
900 return;
901 }
902
903 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000904}
905
John McCall578b69b2009-12-16 08:11:27 +0000906/// Diagnose an empty lookup.
907///
908/// \return false if new lookup candidates were found
909bool Sema::DiagnoseEmptyLookup(const CXXScopeSpec &SS,
910 LookupResult &R) {
911 DeclarationName Name = R.getLookupName();
912
913 // We don't know how to recover from bad qualified lookups.
914 if (!SS.isEmpty()) {
915 Diag(R.getNameLoc(), diag::err_no_member)
916 << Name << computeDeclContext(SS, false)
917 << SS.getRange();
918 return true;
919 }
920
921 unsigned diagnostic = diag::err_undeclared_var_use;
922 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
923 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
924 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
925 diagnostic = diag::err_undeclared_use;
926
927 // Fake an unqualified lookup. This is useful when (for example)
928 // the original lookup would not have found something because it was
929 // a dependent name.
930 for (DeclContext *DC = CurContext; DC; DC = DC->getParent()) {
931 if (isa<CXXRecordDecl>(DC)) {
932 LookupQualifiedName(R, DC);
933
934 if (!R.empty()) {
935 // Don't give errors about ambiguities in this lookup.
936 R.suppressDiagnostics();
937
938 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
939 bool isInstance = CurMethod &&
940 CurMethod->isInstance() &&
941 DC == CurMethod->getParent();
942
943 // Give a code modification hint to insert 'this->'.
944 // TODO: fixit for inserting 'Base<T>::' in the other cases.
945 // Actually quite difficult!
946 if (isInstance)
947 Diag(R.getNameLoc(), diagnostic) << Name
948 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
949 "this->");
950 else
951 Diag(R.getNameLoc(), diagnostic) << Name;
952
953 // Do we really want to note all of these?
954 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
955 Diag((*I)->getLocation(), diag::note_dependent_var_use);
956
957 // Tell the callee to try to recover.
958 return false;
959 }
960 }
961 }
962
963 // Give up, we can't recover.
964 Diag(R.getNameLoc(), diagnostic) << Name;
965 return true;
966}
967
John McCallf7a1a742009-11-24 19:00:30 +0000968Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
969 const CXXScopeSpec &SS,
970 UnqualifiedId &Id,
971 bool HasTrailingLParen,
972 bool isAddressOfOperand) {
973 assert(!(isAddressOfOperand && HasTrailingLParen) &&
974 "cannot be direct & operand and have a trailing lparen");
975
976 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000977 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000978
John McCall129e2df2009-11-30 22:42:35 +0000979 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +0000980
981 // Decompose the UnqualifiedId into the following data.
982 DeclarationName Name;
983 SourceLocation NameLoc;
984 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +0000985 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
986 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000987
Douglas Gregor10c42622008-11-18 15:03:34 +0000988 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +0000989
John McCallf7a1a742009-11-24 19:00:30 +0000990 // C++ [temp.dep.expr]p3:
991 // An id-expression is type-dependent if it contains:
992 // -- a nested-name-specifier that contains a class-name that
993 // names a dependent type.
994 // Determine whether this is a member of an unknown specialization;
995 // we need to handle these differently.
John McCalle1599ce2009-11-30 23:50:49 +0000996 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCallf7a1a742009-11-24 19:00:30 +0000997 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000998 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000999 TemplateArgs);
1000 }
John McCallba135432009-11-21 08:51:07 +00001001
John McCallf7a1a742009-11-24 19:00:30 +00001002 // Perform the required lookup.
1003 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1004 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +00001005 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +00001006 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +00001007 } else {
1008 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001009
John McCallf7a1a742009-11-24 19:00:30 +00001010 // If this reference is in an Objective-C method, then we need to do
1011 // some special Objective-C lookup, too.
1012 if (!SS.isSet() && II && getCurMethodDecl()) {
1013 OwningExprResult E(LookupInObjCMethod(R, S, II));
1014 if (E.isInvalid())
1015 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001016
John McCallf7a1a742009-11-24 19:00:30 +00001017 Expr *Ex = E.takeAs<Expr>();
1018 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001019 }
Chris Lattner8a934232008-03-31 00:36:02 +00001020 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001021
John McCallf7a1a742009-11-24 19:00:30 +00001022 if (R.isAmbiguous())
1023 return ExprError();
1024
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001025 // Determine whether this name might be a candidate for
1026 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001027 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001028
John McCallf7a1a742009-11-24 19:00:30 +00001029 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001031 // in C90, extension in C99, forbidden in C++).
1032 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1033 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1034 if (D) R.addDecl(D);
1035 }
1036
1037 // If this name wasn't predeclared and if this is not a function
1038 // call, diagnose the problem.
1039 if (R.empty()) {
John McCall578b69b2009-12-16 08:11:27 +00001040 if (DiagnoseEmptyLookup(SS, R))
1041 return ExprError();
1042
1043 assert(!R.empty() &&
1044 "DiagnoseEmptyLookup returned false but added no results");
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 }
1046 }
Mike Stump1eb44332009-09-09 15:08:12 +00001047
John McCallf7a1a742009-11-24 19:00:30 +00001048 // This is guaranteed from this point on.
1049 assert(!R.empty() || ADL);
1050
1051 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001052 // Warn about constructs like:
1053 // if (void *X = foo()) { ... } else { X }.
1054 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregor751f9a42009-06-30 15:47:41 +00001056 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1057 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001058 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001059 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001060 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001061 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001062 << Var->getDeclName()
1063 << (Var->getType()->isPointerType()? 2 :
1064 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001065 break;
1066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001068 // Move to the parent of this scope.
1069 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001070 }
1071 }
John McCallf7a1a742009-11-24 19:00:30 +00001072 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001073 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1074 // C99 DR 316 says that, if a function type comes from a
1075 // function definition (without a prototype), that type is only
1076 // used for checking compatibility. Therefore, when referencing
1077 // the function, we pretend that we don't have the full function
1078 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001079 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001080 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001081
Douglas Gregor751f9a42009-06-30 15:47:41 +00001082 QualType T = Func->getType();
1083 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001084 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001085 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001086 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001087 }
1088 }
Mike Stump1eb44332009-09-09 15:08:12 +00001089
John McCallaa81e162009-12-01 22:10:20 +00001090 // Check whether this might be a C++ implicit instance member access.
1091 // C++ [expr.prim.general]p6:
1092 // Within the definition of a non-static member function, an
1093 // identifier that names a non-static member is transformed to a
1094 // class member access expression.
1095 // But note that &SomeClass::foo is grammatically distinct, even
1096 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001097 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001098 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001099 if (!isAbstractMemberPointer)
1100 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001101 }
1102
John McCallf7a1a742009-11-24 19:00:30 +00001103 if (TemplateArgs)
1104 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001105
John McCallf7a1a742009-11-24 19:00:30 +00001106 return BuildDeclarationNameExpr(SS, R, ADL);
1107}
1108
John McCall3b4294e2009-12-16 12:17:52 +00001109/// Builds an expression which might be an implicit member expression.
1110Sema::OwningExprResult
1111Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1112 LookupResult &R,
1113 const TemplateArgumentListInfo *TemplateArgs) {
1114 switch (ClassifyImplicitMemberAccess(*this, R)) {
1115 case IMA_Instance:
1116 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1117
1118 case IMA_AnonymousMember:
1119 assert(R.isSingleResult());
1120 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1121 R.getAsSingle<FieldDecl>());
1122
1123 case IMA_Mixed:
1124 case IMA_Mixed_Unrelated:
1125 case IMA_Unresolved:
1126 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1127
1128 case IMA_Static:
1129 case IMA_Mixed_StaticContext:
1130 case IMA_Unresolved_StaticContext:
1131 if (TemplateArgs)
1132 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1133 return BuildDeclarationNameExpr(SS, R, false);
1134
1135 case IMA_Error_StaticContext:
1136 case IMA_Error_Unrelated:
1137 DiagnoseInstanceReference(*this, SS, R);
1138 return ExprError();
1139 }
1140
1141 llvm_unreachable("unexpected instance member access kind");
1142 return ExprError();
1143}
1144
John McCall129e2df2009-11-30 22:42:35 +00001145/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1146/// declaration name, generally during template instantiation.
1147/// There's a large number of things which don't need to be done along
1148/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001149Sema::OwningExprResult
1150Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1151 DeclarationName Name,
1152 SourceLocation NameLoc) {
1153 DeclContext *DC;
1154 if (!(DC = computeDeclContext(SS, false)) ||
1155 DC->isDependentContext() ||
1156 RequireCompleteDeclContext(SS))
1157 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1158
1159 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1160 LookupQualifiedName(R, DC);
1161
1162 if (R.isAmbiguous())
1163 return ExprError();
1164
1165 if (R.empty()) {
1166 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1167 return ExprError();
1168 }
1169
1170 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1171}
1172
1173/// LookupInObjCMethod - The parser has read a name in, and Sema has
1174/// detected that we're currently inside an ObjC method. Perform some
1175/// additional lookup.
1176///
1177/// Ideally, most of this would be done by lookup, but there's
1178/// actually quite a lot of extra work involved.
1179///
1180/// Returns a null sentinel to indicate trivial success.
1181Sema::OwningExprResult
1182Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1183 IdentifierInfo *II) {
1184 SourceLocation Loc = Lookup.getNameLoc();
1185
1186 // There are two cases to handle here. 1) scoped lookup could have failed,
1187 // in which case we should look for an ivar. 2) scoped lookup could have
1188 // found a decl, but that decl is outside the current instance method (i.e.
1189 // a global variable). In these two cases, we do a lookup for an ivar with
1190 // this name, if the lookup sucedes, we replace it our current decl.
1191
1192 // If we're in a class method, we don't normally want to look for
1193 // ivars. But if we don't find anything else, and there's an
1194 // ivar, that's an error.
1195 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1196
1197 bool LookForIvars;
1198 if (Lookup.empty())
1199 LookForIvars = true;
1200 else if (IsClassMethod)
1201 LookForIvars = false;
1202 else
1203 LookForIvars = (Lookup.isSingleResult() &&
1204 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1205
1206 if (LookForIvars) {
1207 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1208 ObjCInterfaceDecl *ClassDeclared;
1209 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1210 // Diagnose using an ivar in a class method.
1211 if (IsClassMethod)
1212 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1213 << IV->getDeclName());
1214
1215 // If we're referencing an invalid decl, just return this as a silent
1216 // error node. The error diagnostic was already emitted on the decl.
1217 if (IV->isInvalidDecl())
1218 return ExprError();
1219
1220 // Check if referencing a field with __attribute__((deprecated)).
1221 if (DiagnoseUseOfDecl(IV, Loc))
1222 return ExprError();
1223
1224 // Diagnose the use of an ivar outside of the declaring class.
1225 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1226 ClassDeclared != IFace)
1227 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1228
1229 // FIXME: This should use a new expr for a direct reference, don't
1230 // turn this into Self->ivar, just return a BareIVarExpr or something.
1231 IdentifierInfo &II = Context.Idents.get("self");
1232 UnqualifiedId SelfName;
1233 SelfName.setIdentifier(&II, SourceLocation());
1234 CXXScopeSpec SelfScopeSpec;
1235 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1236 SelfName, false, false);
1237 MarkDeclarationReferenced(Loc, IV);
1238 return Owned(new (Context)
1239 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1240 SelfExpr.takeAs<Expr>(), true, true));
1241 }
1242 } else if (getCurMethodDecl()->isInstanceMethod()) {
1243 // We should warn if a local variable hides an ivar.
1244 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1245 ObjCInterfaceDecl *ClassDeclared;
1246 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1247 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1248 IFace == ClassDeclared)
1249 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1250 }
1251 }
1252
1253 // Needed to implement property "super.method" notation.
1254 if (Lookup.empty() && II->isStr("super")) {
1255 QualType T;
1256
1257 if (getCurMethodDecl()->isInstanceMethod())
1258 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1259 getCurMethodDecl()->getClassInterface()));
1260 else
1261 T = Context.getObjCClassType();
1262 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1263 }
1264
1265 // Sentinel value saying that we didn't do anything special.
1266 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001267}
John McCallba135432009-11-21 08:51:07 +00001268
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001269/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001270bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001271Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1272 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001273 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001274 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001275 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001276 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001277 if (DestType->isDependentType() || From->getType()->isDependentType())
1278 return false;
1279 QualType FromRecordType = From->getType();
1280 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001281 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001282 DestType = Context.getPointerType(DestType);
1283 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001284 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001285 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1286 CheckDerivedToBaseConversion(FromRecordType,
1287 DestRecordType,
1288 From->getSourceRange().getBegin(),
1289 From->getSourceRange()))
1290 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001291 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1292 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001293 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001294 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001295}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001296
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001297/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001298static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001299 const CXXScopeSpec &SS, ValueDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001300 SourceLocation Loc, QualType Ty,
1301 const TemplateArgumentListInfo *TemplateArgs = 0) {
1302 NestedNameSpecifier *Qualifier = 0;
1303 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001304 if (SS.isSet()) {
1305 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1306 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308
John McCallf7a1a742009-11-24 19:00:30 +00001309 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1310 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001311}
1312
John McCallaa81e162009-12-01 22:10:20 +00001313/// Builds an implicit member access expression. The current context
1314/// is known to be an instance method, and the given unqualified lookup
1315/// set is known to contain only instance members, at least one of which
1316/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001317Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001318Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1319 LookupResult &R,
1320 const TemplateArgumentListInfo *TemplateArgs,
1321 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001322 assert(!R.empty() && !R.isAmbiguous());
1323
John McCallba135432009-11-21 08:51:07 +00001324 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001325
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001326 // We may have found a field within an anonymous union or struct
1327 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001328 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001329 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001330 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001331 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001332 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001333
John McCallaa81e162009-12-01 22:10:20 +00001334 // If this is known to be an instance access, go ahead and build a
1335 // 'this' expression now.
1336 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1337 Expr *This = 0; // null signifies implicit access
1338 if (IsKnownInstance) {
1339 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001340 }
1341
John McCallaa81e162009-12-01 22:10:20 +00001342 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1343 /*OpLoc*/ SourceLocation(),
1344 /*IsArrow*/ true,
1345 SS, R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001346}
1347
John McCallf7a1a742009-11-24 19:00:30 +00001348bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001349 const LookupResult &R,
1350 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001351 // Only when used directly as the postfix-expression of a call.
1352 if (!HasTrailingLParen)
1353 return false;
1354
1355 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001356 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001357 return false;
1358
1359 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001360 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001361 return false;
1362
1363 // Turn off ADL when we find certain kinds of declarations during
1364 // normal lookup:
1365 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1366 NamedDecl *D = *I;
1367
1368 // C++0x [basic.lookup.argdep]p3:
1369 // -- a declaration of a class member
1370 // Since using decls preserve this property, we check this on the
1371 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001372 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001373 return false;
1374
1375 // C++0x [basic.lookup.argdep]p3:
1376 // -- a block-scope function declaration that is not a
1377 // using-declaration
1378 // NOTE: we also trigger this for function templates (in fact, we
1379 // don't check the decl type at all, since all other decl types
1380 // turn off ADL anyway).
1381 if (isa<UsingShadowDecl>(D))
1382 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1383 else if (D->getDeclContext()->isFunctionOrMethod())
1384 return false;
1385
1386 // C++0x [basic.lookup.argdep]p3:
1387 // -- a declaration that is neither a function or a function
1388 // template
1389 // And also for builtin functions.
1390 if (isa<FunctionDecl>(D)) {
1391 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1392
1393 // But also builtin functions.
1394 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1395 return false;
1396 } else if (!isa<FunctionTemplateDecl>(D))
1397 return false;
1398 }
1399
1400 return true;
1401}
1402
1403
John McCallba135432009-11-21 08:51:07 +00001404/// Diagnoses obvious problems with the use of the given declaration
1405/// as an expression. This is only actually called for lookups that
1406/// were not overloaded, and it doesn't promise that the declaration
1407/// will in fact be used.
1408static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1409 if (isa<TypedefDecl>(D)) {
1410 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1411 return true;
1412 }
1413
1414 if (isa<ObjCInterfaceDecl>(D)) {
1415 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1416 return true;
1417 }
1418
1419 if (isa<NamespaceDecl>(D)) {
1420 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1421 return true;
1422 }
1423
1424 return false;
1425}
1426
1427Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001428Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001429 LookupResult &R,
1430 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001431 // If this is a single, fully-resolved result and we don't need ADL,
1432 // just build an ordinary singleton decl ref.
1433 if (!NeedsADL && R.isSingleResult())
John McCall5b3f9132009-11-22 01:44:31 +00001434 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001435
1436 // We only need to check the declaration if there's exactly one
1437 // result, because in the overloaded case the results can only be
1438 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001439 if (R.isSingleResult() &&
1440 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001441 return ExprError();
1442
John McCallf7a1a742009-11-24 19:00:30 +00001443 bool Dependent
1444 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001445 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001446 = UnresolvedLookupExpr::Create(Context, Dependent,
1447 (NestedNameSpecifier*) SS.getScopeRep(),
1448 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001449 R.getLookupName(), R.getNameLoc(),
1450 NeedsADL, R.isOverloadedResult());
1451 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1452 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001453
1454 return Owned(ULE);
1455}
1456
1457
1458/// \brief Complete semantic analysis for a reference to the given declaration.
1459Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001460Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001461 SourceLocation Loc, NamedDecl *D) {
1462 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001463 assert(!isa<FunctionTemplateDecl>(D) &&
1464 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001465 DeclarationName Name = D->getDeclName();
1466
1467 if (CheckDeclInExpr(*this, Loc, D))
1468 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001469
Douglas Gregor9af2f522009-12-01 16:58:18 +00001470 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1471 // Specifically diagnose references to class templates that are missing
1472 // a template argument list.
1473 Diag(Loc, diag::err_template_decl_ref)
1474 << Template << SS.getRange();
1475 Diag(Template->getLocation(), diag::note_template_decl_here);
1476 return ExprError();
1477 }
1478
1479 // Make sure that we're referring to a value.
1480 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1481 if (!VD) {
1482 Diag(Loc, diag::err_ref_non_value)
1483 << D << SS.getRange();
Daniel Dunbarec3455f2009-12-15 04:24:24 +00001484 Diag(D->getLocation(), diag::note_previous_declaration);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001485 return ExprError();
1486 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001487
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001488 // Check whether this declaration can be used. Note that we suppress
1489 // this check when we're going to perform argument-dependent lookup
1490 // on this function name, because this might not be the function
1491 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001492 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001493 return ExprError();
1494
Steve Naroffdd972f22008-09-05 22:11:13 +00001495 // Only create DeclRefExpr's for valid Decl's.
1496 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001497 return ExprError();
1498
Chris Lattner639e2d32008-10-20 05:16:36 +00001499 // If the identifier reference is inside a block, and it refers to a value
1500 // that is outside the block, create a BlockDeclRefExpr instead of a
1501 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1502 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001503 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001504 // We do not do this for things like enum constants, global variables, etc,
1505 // as they do not get snapshotted.
1506 //
1507 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001508 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001509 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001510 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001511 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001512 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001513 // This is to record that a 'const' was actually synthesize and added.
1514 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001515 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Eli Friedman5fdeae12009-03-22 23:00:19 +00001517 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001518 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001519 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001520 }
1521 // If this reference is not in a block or if the referenced variable is
1522 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001523
John McCallf7a1a742009-11-24 19:00:30 +00001524 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001525}
1526
Sebastian Redlcd965b92009-01-18 18:53:16 +00001527Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1528 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001529 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001530
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001532 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001533 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1534 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1535 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001537
Chris Lattnerfa28b302008-01-12 08:14:25 +00001538 // Pre-defined identifiers are of type char[x], where x is the length of the
1539 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Anders Carlsson3a082d82009-09-08 18:24:21 +00001541 Decl *currentDecl = getCurFunctionOrMethodDecl();
1542 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001543 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001544 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001545 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001546
Anders Carlsson773f3972009-09-11 01:22:35 +00001547 QualType ResTy;
1548 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1549 ResTy = Context.DependentTy;
1550 } else {
1551 unsigned Length =
1552 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001553
Anders Carlsson773f3972009-09-11 01:22:35 +00001554 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001555 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001556 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1557 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001558 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001559}
1560
Sebastian Redlcd965b92009-01-18 18:53:16 +00001561Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 llvm::SmallString<16> CharBuffer;
1563 CharBuffer.resize(Tok.getLength());
1564 const char *ThisTokBegin = &CharBuffer[0];
1565 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001566
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1568 Tok.getLocation(), PP);
1569 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001570 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001571
1572 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1573
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001574 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1575 Literal.isWide(),
1576 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001577}
1578
Sebastian Redlcd965b92009-01-18 18:53:16 +00001579Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1580 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1582 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001583 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001584 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001585 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001586 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 }
Ted Kremenek28396602009-01-13 23:19:12 +00001588
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001590 // Add padding so that NumericLiteralParser can overread by one character.
1591 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001593
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 // Get the spelling of the token, which eliminates trigraphs, etc.
1595 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001596
Mike Stump1eb44332009-09-09 15:08:12 +00001597 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 Tok.getLocation(), PP);
1599 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001600 return ExprError();
1601
Chris Lattner5d661452007-08-26 03:42:43 +00001602 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001603
Chris Lattner5d661452007-08-26 03:42:43 +00001604 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001605 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001606 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001607 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001608 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001609 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001610 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001611 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001612
1613 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1614
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001615 // isExact will be set by GetFloatValue().
1616 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001617 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1618 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001619
Chris Lattner5d661452007-08-26 03:42:43 +00001620 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001621 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001622 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001623 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001624
Neil Boothb9449512007-08-29 22:00:19 +00001625 // long long is a C99 feature.
1626 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001627 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001628 Diag(Tok.getLocation(), diag::ext_longlong);
1629
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001631 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001632
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 if (Literal.GetIntegerValue(ResultVal)) {
1634 // If this value didn't fit into uintmax_t, warn and force to ull.
1635 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001636 Ty = Context.UnsignedLongLongTy;
1637 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001638 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 } else {
1640 // If this value fits into a ULL, try to figure out what else it fits into
1641 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001642
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1644 // be an unsigned int.
1645 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1646
1647 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001648 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001649 if (!Literal.isLong && !Literal.isLongLong) {
1650 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001651 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001652
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 // Does it fit in a unsigned int?
1654 if (ResultVal.isIntN(IntSize)) {
1655 // Does it fit in a signed int?
1656 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001657 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001659 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001660 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001663
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001665 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001666 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001667
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 // Does it fit in a unsigned long?
1669 if (ResultVal.isIntN(LongSize)) {
1670 // Does it fit in a signed long?
1671 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001672 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001674 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001675 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001677 }
1678
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001680 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001681 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001682
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 // Does it fit in a unsigned long long?
1684 if (ResultVal.isIntN(LongLongSize)) {
1685 // Does it fit in a signed long long?
1686 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001687 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001689 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001690 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 }
1692 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001693
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 // If we still couldn't decide a type, we probably have something that
1695 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001696 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001698 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001699 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001701
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001702 if (ResultVal.getBitWidth() != Width)
1703 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001705 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001707
Chris Lattner5d661452007-08-26 03:42:43 +00001708 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1709 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001710 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001711 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001712
1713 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001714}
1715
Sebastian Redlcd965b92009-01-18 18:53:16 +00001716Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1717 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001718 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001719 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001720 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001721}
1722
1723/// The UsualUnaryConversions() function is *not* called by this routine.
1724/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001725bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001726 SourceLocation OpLoc,
1727 const SourceRange &ExprRange,
1728 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001729 if (exprType->isDependentType())
1730 return false;
1731
Sebastian Redl5d484e82009-11-23 17:18:46 +00001732 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1733 // the result is the size of the referenced type."
1734 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1735 // result shall be the alignment of the referenced type."
1736 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1737 exprType = Ref->getPointeeType();
1738
Reid Spencer5f016e22007-07-11 17:01:13 +00001739 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001740 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001741 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001742 if (isSizeof)
1743 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1744 return false;
1745 }
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Chris Lattner1efaa952009-04-24 00:30:45 +00001747 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001748 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001749 Diag(OpLoc, diag::ext_sizeof_void_type)
1750 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001751 return false;
1752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Chris Lattner1efaa952009-04-24 00:30:45 +00001754 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00001755 PDiag(diag::err_sizeof_alignof_incomplete_type)
1756 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001757 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Chris Lattner1efaa952009-04-24 00:30:45 +00001759 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001760 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001761 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001762 << exprType << isSizeof << ExprRange;
1763 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001764 }
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Chris Lattner1efaa952009-04-24 00:30:45 +00001766 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001767}
1768
Chris Lattner31e21e02009-01-24 20:17:12 +00001769bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1770 const SourceRange &ExprRange) {
1771 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001772
Mike Stump1eb44332009-09-09 15:08:12 +00001773 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001774 if (isa<DeclRefExpr>(E))
1775 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001776
1777 // Cannot know anything else if the expression is dependent.
1778 if (E->isTypeDependent())
1779 return false;
1780
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001781 if (E->getBitField()) {
1782 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1783 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001784 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001785
1786 // Alignment of a field access is always okay, so long as it isn't a
1787 // bit-field.
1788 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001789 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001790 return false;
1791
Chris Lattner31e21e02009-01-24 20:17:12 +00001792 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1793}
1794
Douglas Gregorba498172009-03-13 21:01:28 +00001795/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001796Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00001797Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00001798 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001799 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00001800 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001801 return ExprError();
1802
John McCalla93c9342009-12-07 02:54:59 +00001803 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00001804
Douglas Gregorba498172009-03-13 21:01:28 +00001805 if (!T->isDependentType() &&
1806 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1807 return ExprError();
1808
1809 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00001810 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001811 Context.getSizeType(), OpLoc,
1812 R.getEnd()));
1813}
1814
1815/// \brief Build a sizeof or alignof expression given an expression
1816/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001817Action::OwningExprResult
1818Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001819 bool isSizeOf, SourceRange R) {
1820 // Verify that the operand is valid.
1821 bool isInvalid = false;
1822 if (E->isTypeDependent()) {
1823 // Delay type-checking for type-dependent expressions.
1824 } else if (!isSizeOf) {
1825 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001826 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001827 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1828 isInvalid = true;
1829 } else {
1830 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1831 }
1832
1833 if (isInvalid)
1834 return ExprError();
1835
1836 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1837 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1838 Context.getSizeType(), OpLoc,
1839 R.getEnd()));
1840}
1841
Sebastian Redl05189992008-11-11 17:56:53 +00001842/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1843/// the same for @c alignof and @c __alignof
1844/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001845Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001846Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1847 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001849 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001850
Sebastian Redl05189992008-11-11 17:56:53 +00001851 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00001852 TypeSourceInfo *TInfo;
1853 (void) GetTypeFromParser(TyOrEx, &TInfo);
1854 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001855 }
Sebastian Redl05189992008-11-11 17:56:53 +00001856
Douglas Gregorba498172009-03-13 21:01:28 +00001857 Expr *ArgEx = (Expr *)TyOrEx;
1858 Action::OwningExprResult Result
1859 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1860
1861 if (Result.isInvalid())
1862 DeleteExpr(ArgEx);
1863
1864 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001865}
1866
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001867QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001868 if (V->isTypeDependent())
1869 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Chris Lattnercc26ed72007-08-26 05:39:26 +00001871 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001872 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001873 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Chris Lattnercc26ed72007-08-26 05:39:26 +00001875 // Otherwise they pass through real integer and floating point types here.
1876 if (V->getType()->isArithmeticType())
1877 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Chris Lattnercc26ed72007-08-26 05:39:26 +00001879 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001880 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1881 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001882 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001883}
1884
1885
Reid Spencer5f016e22007-07-11 17:01:13 +00001886
Sebastian Redl0eb23302009-01-19 00:08:26 +00001887Action::OwningExprResult
1888Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1889 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 UnaryOperator::Opcode Opc;
1891 switch (Kind) {
1892 default: assert(0 && "Unknown unary op!");
1893 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1894 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1895 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001896
Eli Friedmane4216e92009-11-18 03:38:04 +00001897 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001898}
1899
Sebastian Redl0eb23302009-01-19 00:08:26 +00001900Action::OwningExprResult
1901Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1902 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001903 // Since this might be a postfix expression, get rid of ParenListExprs.
1904 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1905
Sebastian Redl0eb23302009-01-19 00:08:26 +00001906 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1907 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregor337c6b92008-11-19 17:17:41 +00001909 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001910 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1911 Base.release();
1912 Idx.release();
1913 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1914 Context.DependentTy, RLoc));
1915 }
1916
Mike Stump1eb44332009-09-09 15:08:12 +00001917 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001918 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001919 LHSExp->getType()->isEnumeralType() ||
1920 RHSExp->getType()->isRecordType() ||
1921 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001922 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001923 }
1924
Sebastian Redlf322ed62009-10-29 20:17:01 +00001925 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1926}
1927
1928
1929Action::OwningExprResult
1930Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1931 ExprArg Idx, SourceLocation RLoc) {
1932 Expr *LHSExp = static_cast<Expr*>(Base.get());
1933 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1934
Chris Lattner12d9ff62007-07-16 00:14:47 +00001935 // Perform default conversions.
1936 DefaultFunctionArrayConversion(LHSExp);
1937 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001938
Chris Lattner12d9ff62007-07-16 00:14:47 +00001939 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001940
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001942 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001943 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001945 Expr *BaseExpr, *IndexExpr;
1946 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001947 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1948 BaseExpr = LHSExp;
1949 IndexExpr = RHSExp;
1950 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001951 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001952 BaseExpr = LHSExp;
1953 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001954 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001955 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001956 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001957 BaseExpr = RHSExp;
1958 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001959 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001960 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001961 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001962 BaseExpr = LHSExp;
1963 IndexExpr = RHSExp;
1964 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001965 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001966 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001967 // Handle the uncommon case of "123[Ptr]".
1968 BaseExpr = RHSExp;
1969 IndexExpr = LHSExp;
1970 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001971 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001972 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001973 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001974
Chris Lattner12d9ff62007-07-16 00:14:47 +00001975 // FIXME: need to deal with const...
1976 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001977 } else if (LHSTy->isArrayType()) {
1978 // If we see an array that wasn't promoted by
1979 // DefaultFunctionArrayConversion, it must be an array that
1980 // wasn't promoted because of the C90 rule that doesn't
1981 // allow promoting non-lvalue arrays. Warn, then
1982 // force the promotion here.
1983 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1984 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001985 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1986 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001987 LHSTy = LHSExp->getType();
1988
1989 BaseExpr = LHSExp;
1990 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001991 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001992 } else if (RHSTy->isArrayType()) {
1993 // Same as previous, except for 123[f().a] case
1994 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1995 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001996 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1997 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001998 RHSTy = RHSExp->getType();
1999
2000 BaseExpr = RHSExp;
2001 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002002 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002004 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2005 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002006 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00002008 if (!(IndexExpr->getType()->isIntegerType() &&
2009 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002010 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2011 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002012
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002013 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002014 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2015 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002016 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2017
Douglas Gregore7450f52009-03-24 19:52:54 +00002018 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002019 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2020 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002021 // incomplete types are not object types.
2022 if (ResultType->isFunctionType()) {
2023 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2024 << ResultType << BaseExpr->getSourceRange();
2025 return ExprError();
2026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Douglas Gregore7450f52009-03-24 19:52:54 +00002028 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002029 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002030 PDiag(diag::err_subscript_incomplete_type)
2031 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002032 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Chris Lattner1efaa952009-04-24 00:30:45 +00002034 // Diagnose bad cases where we step over interface counts.
2035 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2036 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2037 << ResultType << BaseExpr->getSourceRange();
2038 return ExprError();
2039 }
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Sebastian Redl0eb23302009-01-19 00:08:26 +00002041 Base.release();
2042 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002043 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002044 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002045}
2046
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002047QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002048CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002049 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002050 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002051 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2052 // see FIXME there.
2053 //
2054 // FIXME: This logic can be greatly simplified by splitting it along
2055 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002056 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002057
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002058 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002059 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002060
Mike Stumpeed9cac2009-02-19 03:04:26 +00002061 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002062 // special names that indicate a subset of exactly half the elements are
2063 // to be selected.
2064 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002065
Nate Begeman353417a2009-01-18 01:47:54 +00002066 // This flag determines whether or not CompName has an 's' char prefix,
2067 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002068 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002069
2070 // Check that we've found one of the special components, or that the component
2071 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002072 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002073 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2074 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002075 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002076 do
2077 compStr++;
2078 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002079 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002080 do
2081 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002082 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002083 }
Nate Begeman353417a2009-01-18 01:47:54 +00002084
Mike Stumpeed9cac2009-02-19 03:04:26 +00002085 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002086 // We didn't get to the end of the string. This means the component names
2087 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002088 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2089 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002090 return QualType();
2091 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002092
Nate Begeman353417a2009-01-18 01:47:54 +00002093 // Ensure no component accessor exceeds the width of the vector type it
2094 // operates on.
2095 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002096 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002097
2098 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002099 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002100
2101 while (*compStr) {
2102 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2103 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2104 << baseType << SourceRange(CompLoc);
2105 return QualType();
2106 }
2107 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002108 }
Nate Begeman8a997642008-05-09 06:41:27 +00002109
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002110 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002111 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002112 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002113 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002114 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002115 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002116 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002117 if (HexSwizzle)
2118 CompSize--;
2119
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002120 if (CompSize == 1)
2121 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002122
Nate Begeman213541a2008-04-18 23:10:10 +00002123 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002124 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002125 // diagostics look bad. We want extended vector types to appear built-in.
2126 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2127 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2128 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002129 }
2130 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002131}
2132
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002133static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002134 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002135 const Selector &Sel,
2136 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Anders Carlsson8f28f992009-08-26 18:25:21 +00002138 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002139 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002140 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002141 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002143 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2144 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002145 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002146 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002147 return D;
2148 }
2149 return 0;
2150}
2151
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002152static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002153 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002154 const Selector &Sel,
2155 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002156 // Check protocols on qualified interfaces.
2157 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002158 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002159 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002160 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002161 GDecl = PD;
2162 break;
2163 }
2164 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002165 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002166 GDecl = OMD;
2167 break;
2168 }
2169 }
2170 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002171 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002172 E = QIdTy->qual_end(); I != E; ++I) {
2173 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002174 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002175 if (GDecl)
2176 return GDecl;
2177 }
2178 }
2179 return GDecl;
2180}
Chris Lattner76a642f2009-02-15 22:43:40 +00002181
John McCall129e2df2009-11-30 22:42:35 +00002182Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002183Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2184 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002185 const CXXScopeSpec &SS,
2186 NamedDecl *FirstQualifierInScope,
2187 DeclarationName Name, SourceLocation NameLoc,
2188 const TemplateArgumentListInfo *TemplateArgs) {
2189 Expr *BaseExpr = Base.takeAs<Expr>();
2190
2191 // Even in dependent contexts, try to diagnose base expressions with
2192 // obviously wrong types, e.g.:
2193 //
2194 // T* t;
2195 // t.f;
2196 //
2197 // In Obj-C++, however, the above expression is valid, since it could be
2198 // accessing the 'f' property if T is an Obj-C interface. The extra check
2199 // allows this, while still reporting an error if T is a struct pointer.
2200 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002201 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002202 if (PT && (!getLangOptions().ObjC1 ||
2203 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002204 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002205 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002206 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002207 return ExprError();
2208 }
2209 }
2210
John McCallaa81e162009-12-01 22:10:20 +00002211 assert(BaseType->isDependentType());
John McCall129e2df2009-11-30 22:42:35 +00002212
2213 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2214 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002215 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002216 IsArrow, OpLoc,
2217 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2218 SS.getRange(),
2219 FirstQualifierInScope,
2220 Name, NameLoc,
2221 TemplateArgs));
2222}
2223
2224/// We know that the given qualified member reference points only to
2225/// declarations which do not belong to the static type of the base
2226/// expression. Diagnose the problem.
2227static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2228 Expr *BaseExpr,
2229 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002230 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002231 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002232 // If this is an implicit member access, use a different set of
2233 // diagnostics.
2234 if (!BaseExpr)
2235 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002236
2237 // FIXME: this is an exceedingly lame diagnostic for some of the more
2238 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002239 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002240 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002241 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002242}
2243
2244// Check whether the declarations we found through a nested-name
2245// specifier in a member expression are actually members of the base
2246// type. The restriction here is:
2247//
2248// C++ [expr.ref]p2:
2249// ... In these cases, the id-expression shall name a
2250// member of the class or of one of its base classes.
2251//
2252// So it's perfectly legitimate for the nested-name specifier to name
2253// an unrelated class, and for us to find an overload set including
2254// decls from classes which are not superclasses, as long as the decl
2255// we actually pick through overload resolution is from a superclass.
2256bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2257 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002258 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002259 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002260 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2261 if (!BaseRT) {
2262 // We can't check this yet because the base type is still
2263 // dependent.
2264 assert(BaseType->isDependentType());
2265 return false;
2266 }
2267 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002268
2269 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002270 // If this is an implicit member reference and we find a
2271 // non-instance member, it's not an error.
2272 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2273 return false;
John McCall129e2df2009-11-30 22:42:35 +00002274
John McCallaa81e162009-12-01 22:10:20 +00002275 // Note that we use the DC of the decl, not the underlying decl.
2276 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2277 while (RecordD->isAnonymousStructOrUnion())
2278 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2279
2280 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2281 MemberRecord.insert(RecordD->getCanonicalDecl());
2282
2283 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2284 return false;
2285 }
2286
John McCall2f841ba2009-12-02 03:53:29 +00002287 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002288 return true;
2289}
2290
2291static bool
2292LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2293 SourceRange BaseRange, const RecordType *RTy,
2294 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2295 RecordDecl *RDecl = RTy->getDecl();
2296 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2297 PDiag(diag::err_typecheck_incomplete_tag)
2298 << BaseRange))
2299 return true;
2300
2301 DeclContext *DC = RDecl;
2302 if (SS.isSet()) {
2303 // If the member name was a qualified-id, look into the
2304 // nested-name-specifier.
2305 DC = SemaRef.computeDeclContext(SS, false);
2306
John McCall2f841ba2009-12-02 03:53:29 +00002307 if (SemaRef.RequireCompleteDeclContext(SS)) {
2308 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2309 << SS.getRange() << DC;
2310 return true;
2311 }
2312
John McCallaa81e162009-12-01 22:10:20 +00002313 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2314
2315 if (!isa<TypeDecl>(DC)) {
2316 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2317 << DC << SS.getRange();
2318 return true;
John McCall129e2df2009-11-30 22:42:35 +00002319 }
2320 }
2321
John McCallaa81e162009-12-01 22:10:20 +00002322 // The record definition is complete, now look up the member.
2323 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002324
2325 return false;
2326}
2327
2328Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002329Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002330 SourceLocation OpLoc, bool IsArrow,
2331 const CXXScopeSpec &SS,
2332 NamedDecl *FirstQualifierInScope,
2333 DeclarationName Name, SourceLocation NameLoc,
2334 const TemplateArgumentListInfo *TemplateArgs) {
2335 Expr *Base = BaseArg.takeAs<Expr>();
2336
John McCall2f841ba2009-12-02 03:53:29 +00002337 if (BaseType->isDependentType() ||
2338 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002339 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002340 IsArrow, OpLoc,
2341 SS, FirstQualifierInScope,
2342 Name, NameLoc,
2343 TemplateArgs);
2344
2345 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002346
John McCallaa81e162009-12-01 22:10:20 +00002347 // Implicit member accesses.
2348 if (!Base) {
2349 QualType RecordTy = BaseType;
2350 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2351 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2352 RecordTy->getAs<RecordType>(),
2353 OpLoc, SS))
2354 return ExprError();
2355
2356 // Explicit member accesses.
2357 } else {
2358 OwningExprResult Result =
2359 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2360 SS, FirstQualifierInScope,
2361 /*ObjCImpDecl*/ DeclPtrTy());
2362
2363 if (Result.isInvalid()) {
2364 Owned(Base);
2365 return ExprError();
2366 }
2367
2368 if (Result.get())
2369 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002370 }
2371
John McCallaa81e162009-12-01 22:10:20 +00002372 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2373 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002374}
2375
2376Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002377Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2378 SourceLocation OpLoc, bool IsArrow,
2379 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002380 LookupResult &R,
2381 const TemplateArgumentListInfo *TemplateArgs) {
2382 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002383 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002384 if (IsArrow) {
2385 assert(BaseType->isPointerType());
2386 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2387 }
2388
2389 NestedNameSpecifier *Qualifier =
2390 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2391 DeclarationName MemberName = R.getLookupName();
2392 SourceLocation MemberLoc = R.getNameLoc();
2393
2394 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002395 return ExprError();
2396
John McCall129e2df2009-11-30 22:42:35 +00002397 if (R.empty()) {
2398 // Rederive where we looked up.
2399 DeclContext *DC = (SS.isSet()
2400 ? computeDeclContext(SS, false)
2401 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002402
John McCall129e2df2009-11-30 22:42:35 +00002403 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002404 << MemberName << DC
2405 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002406 return ExprError();
2407 }
2408
John McCall2f841ba2009-12-02 03:53:29 +00002409 // Diagnose qualified lookups that find only declarations from a
2410 // non-base type. Note that it's okay for lookup to find
2411 // declarations from a non-base type as long as those aren't the
2412 // ones picked by overload resolution.
2413 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002414 return ExprError();
2415
2416 // Construct an unresolved result if we in fact got an unresolved
2417 // result.
2418 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002419 bool Dependent =
2420 R.isUnresolvableResult() ||
2421 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002422
2423 UnresolvedMemberExpr *MemExpr
2424 = UnresolvedMemberExpr::Create(Context, Dependent,
2425 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002426 BaseExpr, BaseExprType,
2427 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002428 Qualifier, SS.getRange(),
2429 MemberName, MemberLoc,
2430 TemplateArgs);
2431 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2432 MemExpr->addDecl(*I);
2433
2434 return Owned(MemExpr);
2435 }
2436
2437 assert(R.isSingleResult());
2438 NamedDecl *MemberDecl = R.getFoundDecl();
2439
2440 // FIXME: diagnose the presence of template arguments now.
2441
2442 // If the decl being referenced had an error, return an error for this
2443 // sub-expr without emitting another error, in order to avoid cascading
2444 // error cases.
2445 if (MemberDecl->isInvalidDecl())
2446 return ExprError();
2447
John McCallaa81e162009-12-01 22:10:20 +00002448 // Handle the implicit-member-access case.
2449 if (!BaseExpr) {
2450 // If this is not an instance member, convert to a non-member access.
2451 if (!IsInstanceMember(MemberDecl))
2452 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2453
2454 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2455 }
2456
John McCall129e2df2009-11-30 22:42:35 +00002457 bool ShouldCheckUse = true;
2458 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2459 // Don't diagnose the use of a virtual member function unless it's
2460 // explicitly qualified.
2461 if (MD->isVirtual() && !SS.isSet())
2462 ShouldCheckUse = false;
2463 }
2464
2465 // Check the use of this member.
2466 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2467 Owned(BaseExpr);
2468 return ExprError();
2469 }
2470
2471 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2472 // We may have found a field within an anonymous union or struct
2473 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002474 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2475 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002476 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2477 BaseExpr, OpLoc);
2478
2479 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2480 QualType MemberType = FD->getType();
2481 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2482 MemberType = Ref->getPointeeType();
2483 else {
2484 Qualifiers BaseQuals = BaseType.getQualifiers();
2485 BaseQuals.removeObjCGCAttr();
2486 if (FD->isMutable()) BaseQuals.removeConst();
2487
2488 Qualifiers MemberQuals
2489 = Context.getCanonicalType(MemberType).getQualifiers();
2490
2491 Qualifiers Combined = BaseQuals + MemberQuals;
2492 if (Combined != MemberQuals)
2493 MemberType = Context.getQualifiedType(MemberType, Combined);
2494 }
2495
2496 MarkDeclarationReferenced(MemberLoc, FD);
2497 if (PerformObjectMemberConversion(BaseExpr, FD))
2498 return ExprError();
2499 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2500 FD, MemberLoc, MemberType));
2501 }
2502
2503 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2504 MarkDeclarationReferenced(MemberLoc, Var);
2505 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2506 Var, MemberLoc,
2507 Var->getType().getNonReferenceType()));
2508 }
2509
2510 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2511 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2512 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2513 MemberFn, MemberLoc,
2514 MemberFn->getType()));
2515 }
2516
2517 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2518 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2519 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2520 Enum, MemberLoc, Enum->getType()));
2521 }
2522
2523 Owned(BaseExpr);
2524
2525 if (isa<TypeDecl>(MemberDecl))
2526 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2527 << MemberName << int(IsArrow));
2528
2529 // We found a declaration kind that we didn't expect. This is a
2530 // generic error message that tells the user that she can't refer
2531 // to this member with '.' or '->'.
2532 return ExprError(Diag(MemberLoc,
2533 diag::err_typecheck_member_reference_unknown)
2534 << MemberName << int(IsArrow));
2535}
2536
2537/// Look up the given member of the given non-type-dependent
2538/// expression. This can return in one of two ways:
2539/// * If it returns a sentinel null-but-valid result, the caller will
2540/// assume that lookup was performed and the results written into
2541/// the provided structure. It will take over from there.
2542/// * Otherwise, the returned expression will be produced in place of
2543/// an ordinary member expression.
2544///
2545/// The ObjCImpDecl bit is a gross hack that will need to be properly
2546/// fixed for ObjC++.
2547Sema::OwningExprResult
2548Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002549 bool &IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002550 const CXXScopeSpec &SS,
2551 NamedDecl *FirstQualifierInScope,
2552 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002553 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002554
Steve Naroff3cc4af82007-12-16 21:42:28 +00002555 // Perform default conversions.
2556 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002557
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002558 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002559 assert(!BaseType->isDependentType());
2560
2561 DeclarationName MemberName = R.getLookupName();
2562 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002563
2564 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002565 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002566 // function. Suggest the addition of those parentheses, build the
2567 // call, and continue on.
2568 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2569 if (const FunctionProtoType *Fun
2570 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2571 QualType ResultTy = Fun->getResultType();
2572 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002573 ((!IsArrow && ResultTy->isRecordType()) ||
2574 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002575 ResultTy->getAs<PointerType>()->getPointeeType()
2576 ->isRecordType()))) {
2577 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2578 Diag(Loc, diag::err_member_reference_needs_call)
2579 << QualType(Fun, 0)
2580 << CodeModificationHint::CreateInsertion(Loc, "()");
2581
2582 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002583 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002584 MultiExprArg(*this, 0, 0), 0, Loc);
2585 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002586 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002587
2588 BaseExpr = NewBase.takeAs<Expr>();
2589 DefaultFunctionArrayConversion(BaseExpr);
2590 BaseType = BaseExpr->getType();
2591 }
2592 }
2593 }
2594
David Chisnall0f436562009-08-17 16:35:33 +00002595 // If this is an Objective-C pseudo-builtin and a definition is provided then
2596 // use that.
2597 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002598 if (IsArrow) {
2599 // Handle the following exceptional case PObj->isa.
2600 if (const ObjCObjectPointerType *OPT =
2601 BaseType->getAs<ObjCObjectPointerType>()) {
2602 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2603 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002604 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2605 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002606 }
2607 }
David Chisnall0f436562009-08-17 16:35:33 +00002608 // We have an 'id' type. Rather than fall through, we check if this
2609 // is a reference to 'isa'.
2610 if (BaseType != Context.ObjCIdRedefinitionType) {
2611 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002612 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002613 }
David Chisnall0f436562009-08-17 16:35:33 +00002614 }
John McCall129e2df2009-11-30 22:42:35 +00002615
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002616 // If this is an Objective-C pseudo-builtin and a definition is provided then
2617 // use that.
2618 if (Context.isObjCSelType(BaseType)) {
2619 // We have an 'SEL' type. Rather than fall through, we check if this
2620 // is a reference to 'sel_id'.
2621 if (BaseType != Context.ObjCSelRedefinitionType) {
2622 BaseType = Context.ObjCSelRedefinitionType;
2623 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2624 }
2625 }
John McCall129e2df2009-11-30 22:42:35 +00002626
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002627 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002628
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002629 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002630 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002631 // Also must look for a getter name which uses property syntax.
2632 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2633 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2634 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2635 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2636 ObjCMethodDecl *Getter;
2637 // FIXME: need to also look locally in the implementation.
2638 if ((Getter = IFace->lookupClassMethod(Sel))) {
2639 // Check the use of this method.
2640 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2641 return ExprError();
2642 }
2643 // If we found a getter then this may be a valid dot-reference, we
2644 // will look for the matching setter, in case it is needed.
2645 Selector SetterSel =
2646 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2647 PP.getSelectorTable(), Member);
2648 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2649 if (!Setter) {
2650 // If this reference is in an @implementation, also check for 'private'
2651 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002652 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002653 }
2654 // Look through local category implementations associated with the class.
2655 if (!Setter)
2656 Setter = IFace->getCategoryClassMethod(SetterSel);
2657
2658 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2659 return ExprError();
2660
2661 if (Getter || Setter) {
2662 QualType PType;
2663
2664 if (Getter)
2665 PType = Getter->getResultType();
2666 else
2667 // Get the expression type from Setter's incoming parameter.
2668 PType = (*(Setter->param_end() -1))->getType();
2669 // FIXME: we must check that the setter has property type.
2670 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2671 PType,
2672 Setter, MemberLoc, BaseExpr));
2673 }
2674 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2675 << MemberName << BaseType);
2676 }
2677 }
2678
2679 if (BaseType->isObjCClassType() &&
2680 BaseType != Context.ObjCClassRedefinitionType) {
2681 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002682 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002683 }
Mike Stump1eb44332009-09-09 15:08:12 +00002684
John McCall129e2df2009-11-30 22:42:35 +00002685 if (IsArrow) {
2686 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002687 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002688 else if (BaseType->isObjCObjectPointerType())
2689 ;
John McCall812c1542009-12-07 22:46:59 +00002690 else if (BaseType->isRecordType()) {
2691 // Recover from arrow accesses to records, e.g.:
2692 // struct MyRecord foo;
2693 // foo->bar
2694 // This is actually well-formed in C++ if MyRecord has an
2695 // overloaded operator->, but that should have been dealt with
2696 // by now.
2697 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2698 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2699 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2700 IsArrow = false;
2701 } else {
John McCall129e2df2009-11-30 22:42:35 +00002702 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2703 << BaseType << BaseExpr->getSourceRange();
2704 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002705 }
John McCall812c1542009-12-07 22:46:59 +00002706 } else {
2707 // Recover from dot accesses to pointers, e.g.:
2708 // type *foo;
2709 // foo.bar
2710 // This is actually well-formed in two cases:
2711 // - 'type' is an Objective C type
2712 // - 'bar' is a pseudo-destructor name which happens to refer to
2713 // the appropriate pointer type
2714 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2715 const PointerType *PT = BaseType->getAs<PointerType>();
2716 if (PT && PT->getPointeeType()->isRecordType()) {
2717 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2718 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2719 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2720 BaseType = PT->getPointeeType();
2721 IsArrow = true;
2722 }
2723 }
John McCall129e2df2009-11-30 22:42:35 +00002724 }
John McCall812c1542009-12-07 22:46:59 +00002725
John McCall129e2df2009-11-30 22:42:35 +00002726 // Handle field access to simple records. This also handles access
2727 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002728 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002729 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2730 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002731 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002732 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002733 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002734
Douglas Gregora71d8192009-09-04 17:36:40 +00002735 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2736 // into a record type was handled above, any destructor we see here is a
2737 // pseudo-destructor.
2738 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2739 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002740 // The left hand side of the dot operator shall be of scalar type. The
2741 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002742 // type.
2743 if (!BaseType->isScalarType())
2744 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2745 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Douglas Gregora71d8192009-09-04 17:36:40 +00002747 // [...] The type designated by the pseudo-destructor-name shall be the
2748 // same as the object type.
2749 if (!MemberName.getCXXNameType()->isDependentType() &&
2750 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2751 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2752 << BaseType << MemberName.getCXXNameType()
2753 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002754
2755 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002756 // the form
2757 //
Mike Stump1eb44332009-09-09 15:08:12 +00002758 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2759 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002760 // shall designate the same scalar type.
2761 //
2762 // FIXME: DPG can't see any way to trigger this particular clause, so it
2763 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Douglas Gregora71d8192009-09-04 17:36:40 +00002765 // FIXME: We've lost the precise spelling of the type by going through
2766 // DeclarationName. Can we do better?
2767 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002768 IsArrow, OpLoc,
2769 (NestedNameSpecifier *) SS.getScopeRep(),
2770 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002771 MemberName.getCXXNameType(),
2772 MemberLoc));
2773 }
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Chris Lattnera38e6b12008-07-21 04:59:05 +00002775 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2776 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002777 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2778 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002779 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002780 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002781 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002782 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002783 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2784
Steve Naroffc70e8d92009-07-16 00:25:06 +00002785 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2786 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002787 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002788
Steve Naroffc70e8d92009-07-16 00:25:06 +00002789 if (IV) {
2790 // If the decl being referenced had an error, return an error for this
2791 // sub-expr without emitting another error, in order to avoid cascading
2792 // error cases.
2793 if (IV->isInvalidDecl())
2794 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002795
Steve Naroffc70e8d92009-07-16 00:25:06 +00002796 // Check whether we can reference this field.
2797 if (DiagnoseUseOfDecl(IV, MemberLoc))
2798 return ExprError();
2799 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2800 IV->getAccessControl() != ObjCIvarDecl::Package) {
2801 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2802 if (ObjCMethodDecl *MD = getCurMethodDecl())
2803 ClassOfMethodDecl = MD->getClassInterface();
2804 else if (ObjCImpDecl && getCurFunctionDecl()) {
2805 // Case of a c-function declared inside an objc implementation.
2806 // FIXME: For a c-style function nested inside an objc implementation
2807 // class, there is no implementation context available, so we pass
2808 // down the context as argument to this routine. Ideally, this context
2809 // need be passed down in the AST node and somehow calculated from the
2810 // AST for a function decl.
2811 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002812 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002813 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2814 ClassOfMethodDecl = IMPD->getClassInterface();
2815 else if (ObjCCategoryImplDecl* CatImplClass =
2816 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2817 ClassOfMethodDecl = CatImplClass->getClassInterface();
2818 }
Mike Stump1eb44332009-09-09 15:08:12 +00002819
2820 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2821 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002822 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002823 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002824 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002825 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2826 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002827 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002828 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002829 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002830
2831 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2832 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002833 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002834 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002835 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002836 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002837 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002838 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002839 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002840 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002841 if (!IsArrow && (BaseType->isObjCIdType() ||
2842 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002843 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002844 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002845
Steve Naroff14108da2009-07-10 23:34:53 +00002846 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002847 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002848 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2849 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2850 // Check the use of this declaration
2851 if (DiagnoseUseOfDecl(PD, MemberLoc))
2852 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002853
Steve Naroff14108da2009-07-10 23:34:53 +00002854 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2855 MemberLoc, BaseExpr));
2856 }
2857 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2858 // Check the use of this method.
2859 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2860 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002861
Steve Naroff14108da2009-07-10 23:34:53 +00002862 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002863 OMD->getResultType(),
2864 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002865 NULL, 0));
2866 }
2867 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002868
Steve Naroff14108da2009-07-10 23:34:53 +00002869 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002870 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002871 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002872 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2873 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002874 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00002875 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00002876 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2877 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002878 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002879
Daniel Dunbar2307d312008-09-03 01:05:41 +00002880 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002881 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002882 // Check whether we can reference this property.
2883 if (DiagnoseUseOfDecl(PD, MemberLoc))
2884 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002885 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002886 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002887 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002888 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2889 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002890 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002891 MemberLoc, BaseExpr));
2892 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002893 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002894 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2895 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002896 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002897 // Check whether we can reference this property.
2898 if (DiagnoseUseOfDecl(PD, MemberLoc))
2899 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002900
Steve Naroff6ece14c2009-01-21 00:14:39 +00002901 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002902 MemberLoc, BaseExpr));
2903 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002904 // If that failed, look for an "implicit" property by seeing if the nullary
2905 // selector is implemented.
2906
2907 // FIXME: The logic for looking up nullary and unary selectors should be
2908 // shared with the code in ActOnInstanceMessage.
2909
Anders Carlsson8f28f992009-08-26 18:25:21 +00002910 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002911 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002912
Daniel Dunbar2307d312008-09-03 01:05:41 +00002913 // If this reference is in an @implementation, check for 'private' methods.
2914 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002915 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002916
Steve Naroff7692ed62008-10-22 19:16:27 +00002917 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002918 if (!Getter)
2919 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002920 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002921 // Check if we can reference this property.
2922 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2923 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002924 }
2925 // If we found a getter then this may be a valid dot-reference, we
2926 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002927 Selector SetterSel =
2928 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002929 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002930 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002931 if (!Setter) {
2932 // If this reference is in an @implementation, also check for 'private'
2933 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002934 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002935 }
2936 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002937 if (!Setter)
2938 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002939
Steve Naroff1ca66942009-03-11 13:48:17 +00002940 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2941 return ExprError();
2942
2943 if (Getter || Setter) {
2944 QualType PType;
2945
2946 if (Getter)
2947 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002948 else
2949 // Get the expression type from Setter's incoming parameter.
2950 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002951 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002952 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002953 Setter, MemberLoc, BaseExpr));
2954 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002955 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002956 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002957 }
Mike Stump1eb44332009-09-09 15:08:12 +00002958
Steve Narofff242b1b2009-07-24 17:54:45 +00002959 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00002960 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002961 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002962 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002963 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002964 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00002965
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002966 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002967 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002968 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002969 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2970 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002971 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002972 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002973 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002974 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002975
Douglas Gregor214f31a2009-03-27 06:00:30 +00002976 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2977 << BaseType << BaseExpr->getSourceRange();
2978
Douglas Gregor214f31a2009-03-27 06:00:30 +00002979 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002980}
2981
John McCall129e2df2009-11-30 22:42:35 +00002982static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2983 SourceLocation NameLoc,
2984 Sema::ExprArg MemExpr) {
2985 Expr *E = (Expr *) MemExpr.get();
2986 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2987 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002988 << isa<CXXPseudoDestructorExpr>(E)
2989 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2990
John McCall129e2df2009-11-30 22:42:35 +00002991 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2992 move(MemExpr),
2993 /*LPLoc*/ ExpectedLParenLoc,
2994 Sema::MultiExprArg(SemaRef, 0, 0),
2995 /*CommaLocs*/ 0,
2996 /*RPLoc*/ ExpectedLParenLoc);
2997}
2998
2999/// The main callback when the parser finds something like
3000/// expression . [nested-name-specifier] identifier
3001/// expression -> [nested-name-specifier] identifier
3002/// where 'identifier' encompasses a fairly broad spectrum of
3003/// possibilities, including destructor and operator references.
3004///
3005/// \param OpKind either tok::arrow or tok::period
3006/// \param HasTrailingLParen whether the next token is '(', which
3007/// is used to diagnose mis-uses of special members that can
3008/// only be called
3009/// \param ObjCImpDecl the current ObjC @implementation decl;
3010/// this is an ugly hack around the fact that ObjC @implementations
3011/// aren't properly put in the context chain
3012Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3013 SourceLocation OpLoc,
3014 tok::TokenKind OpKind,
3015 const CXXScopeSpec &SS,
3016 UnqualifiedId &Id,
3017 DeclPtrTy ObjCImpDecl,
3018 bool HasTrailingLParen) {
3019 if (SS.isSet() && SS.isInvalid())
3020 return ExprError();
3021
3022 TemplateArgumentListInfo TemplateArgsBuffer;
3023
3024 // Decompose the name into its component parts.
3025 DeclarationName Name;
3026 SourceLocation NameLoc;
3027 const TemplateArgumentListInfo *TemplateArgs;
3028 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3029 Name, NameLoc, TemplateArgs);
3030
3031 bool IsArrow = (OpKind == tok::arrow);
3032
3033 NamedDecl *FirstQualifierInScope
3034 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3035 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3036
3037 // This is a postfix expression, so get rid of ParenListExprs.
3038 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3039
3040 Expr *Base = BaseArg.takeAs<Expr>();
3041 OwningExprResult Result(*this);
3042 if (Base->getType()->isDependentType()) {
John McCallaa81e162009-12-01 22:10:20 +00003043 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003044 IsArrow, OpLoc,
3045 SS, FirstQualifierInScope,
3046 Name, NameLoc,
3047 TemplateArgs);
3048 } else {
3049 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3050 if (TemplateArgs) {
3051 // Re-use the lookup done for the template name.
3052 DecomposeTemplateName(R, Id);
3053 } else {
3054 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3055 SS, FirstQualifierInScope,
3056 ObjCImpDecl);
3057
3058 if (Result.isInvalid()) {
3059 Owned(Base);
3060 return ExprError();
3061 }
3062
3063 if (Result.get()) {
3064 // The only way a reference to a destructor can be used is to
3065 // immediately call it, which falls into this case. If the
3066 // next token is not a '(', produce a diagnostic and build the
3067 // call now.
3068 if (!HasTrailingLParen &&
3069 Id.getKind() == UnqualifiedId::IK_DestructorName)
3070 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3071
3072 return move(Result);
3073 }
3074 }
3075
John McCallaa81e162009-12-01 22:10:20 +00003076 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3077 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003078 }
3079
3080 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003081}
3082
Anders Carlsson56c5e332009-08-25 03:49:14 +00003083Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3084 FunctionDecl *FD,
3085 ParmVarDecl *Param) {
3086 if (Param->hasUnparsedDefaultArg()) {
3087 Diag (CallLoc,
3088 diag::err_use_of_default_argument_to_function_declared_later) <<
3089 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003090 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003091 diag::note_default_argument_declared_here);
3092 } else {
3093 if (Param->hasUninstantiatedDefaultArg()) {
3094 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3095
3096 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00003097 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003098
Mike Stump1eb44332009-09-09 15:08:12 +00003099 InstantiatingTemplate Inst(*this, CallLoc, Param,
3100 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003101 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003102
John McCallce3ff2b2009-08-25 22:02:44 +00003103 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003104 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003105 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003106
3107 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00003108 /*FIXME:EqualLoc*/
3109 UninstExpr->getSourceRange().getBegin()))
3110 return ExprError();
3111 }
Mike Stump1eb44332009-09-09 15:08:12 +00003112
Anders Carlsson56c5e332009-08-25 03:49:14 +00003113 // If the default expression creates temporaries, we need to
3114 // push them to the current stack of expression temporaries so they'll
3115 // be properly destroyed.
Anders Carlsson337cba42009-12-15 19:16:31 +00003116 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3117 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003118 }
3119
3120 // We already type-checked the argument, so we know it works.
3121 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3122}
3123
Douglas Gregor88a35142008-12-22 05:46:06 +00003124/// ConvertArgumentsForCall - Converts the arguments specified in
3125/// Args/NumArgs to the parameter types of the function FDecl with
3126/// function prototype Proto. Call is the call expression itself, and
3127/// Fn is the function expression. For a C++ member function, this
3128/// routine does not attempt to convert the object argument. Returns
3129/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003130bool
3131Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003132 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003133 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003134 Expr **Args, unsigned NumArgs,
3135 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003136 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003137 // assignment, to the types of the corresponding parameter, ...
3138 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003139 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003140
Douglas Gregor88a35142008-12-22 05:46:06 +00003141 // If too few arguments are available (and we don't have default
3142 // arguments for the remaining parameters), don't make the call.
3143 if (NumArgs < NumArgsInProto) {
3144 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3145 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3146 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003147 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003148 }
3149
3150 // If too many are passed and not variadic, error on the extras and drop
3151 // them.
3152 if (NumArgs > NumArgsInProto) {
3153 if (!Proto->isVariadic()) {
3154 Diag(Args[NumArgsInProto]->getLocStart(),
3155 diag::err_typecheck_call_too_many_args)
3156 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3157 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3158 Args[NumArgs-1]->getLocEnd());
3159 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003160 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003161 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003162 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003163 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003164 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003165 VariadicCallType CallType =
3166 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3167 if (Fn->getType()->isBlockPointerType())
3168 CallType = VariadicBlock; // Block
3169 else if (isa<MemberExpr>(Fn))
3170 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003171 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003172 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003173 if (Invalid)
3174 return true;
3175 unsigned TotalNumArgs = AllArgs.size();
3176 for (unsigned i = 0; i < TotalNumArgs; ++i)
3177 Call->setArg(i, AllArgs[i]);
3178
3179 return false;
3180}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003181
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003182bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3183 FunctionDecl *FDecl,
3184 const FunctionProtoType *Proto,
3185 unsigned FirstProtoArg,
3186 Expr **Args, unsigned NumArgs,
3187 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003188 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003189 unsigned NumArgsInProto = Proto->getNumArgs();
3190 unsigned NumArgsToCheck = NumArgs;
3191 bool Invalid = false;
3192 if (NumArgs != NumArgsInProto)
3193 // Use default arguments for missing arguments
3194 NumArgsToCheck = NumArgsInProto;
3195 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003196 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003197 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003198 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003199
Douglas Gregor88a35142008-12-22 05:46:06 +00003200 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003201 if (ArgIx < NumArgs) {
3202 Arg = Args[ArgIx++];
3203
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003204 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3205 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003206 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003207 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003208 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003209
Douglas Gregor61366e92008-12-24 00:01:03 +00003210 // Pass the argument.
Douglas Gregor68647482009-12-16 03:45:30 +00003211 if (PerformCopyInitialization(Arg, ProtoArgType, AA_Passing))
Douglas Gregor61366e92008-12-24 00:01:03 +00003212 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00003213
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00003214 if (!ProtoArgType->isReferenceType())
3215 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003216 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003217 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003218
Mike Stump1eb44332009-09-09 15:08:12 +00003219 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003220 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003221 if (ArgExpr.isInvalid())
3222 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003223
Anders Carlsson56c5e332009-08-25 03:49:14 +00003224 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003225 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003226 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003227 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003228
Douglas Gregor88a35142008-12-22 05:46:06 +00003229 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003230 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003231 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003232 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003233 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003234 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003235 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003236 }
3237 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003238 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003239}
3240
Steve Narofff69936d2007-09-16 03:34:24 +00003241/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003242/// This provides the location of the left/right parens and a list of comma
3243/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003244Action::OwningExprResult
3245Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3246 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003247 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003248 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003249
3250 // Since this might be a postfix expression, get rid of ParenListExprs.
3251 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003252
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003253 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003254 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003255 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Douglas Gregor88a35142008-12-22 05:46:06 +00003257 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003258 // If this is a pseudo-destructor expression, build the call immediately.
3259 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3260 if (NumArgs > 0) {
3261 // Pseudo-destructor calls should not have any arguments.
3262 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3263 << CodeModificationHint::CreateRemoval(
3264 SourceRange(Args[0]->getLocStart(),
3265 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003266
Douglas Gregora71d8192009-09-04 17:36:40 +00003267 for (unsigned I = 0; I != NumArgs; ++I)
3268 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Douglas Gregora71d8192009-09-04 17:36:40 +00003270 NumArgs = 0;
3271 }
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Douglas Gregora71d8192009-09-04 17:36:40 +00003273 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3274 RParenLoc));
3275 }
Mike Stump1eb44332009-09-09 15:08:12 +00003276
Douglas Gregor17330012009-02-04 15:01:18 +00003277 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003278 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003279 // FIXME: Will need to cache the results of name lookup (including ADL) in
3280 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003281 bool Dependent = false;
3282 if (Fn->isTypeDependent())
3283 Dependent = true;
3284 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3285 Dependent = true;
3286
3287 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003288 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003289 Context.DependentTy, RParenLoc));
3290
3291 // Determine whether this is a call to an object (C++ [over.call.object]).
3292 if (Fn->getType()->isRecordType())
3293 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3294 CommaLocs, RParenLoc));
3295
John McCall129e2df2009-11-30 22:42:35 +00003296 Expr *NakedFn = Fn->IgnoreParens();
3297
3298 // Determine whether this is a call to an unresolved member function.
3299 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3300 // If lookup was unresolved but not dependent (i.e. didn't find
3301 // an unresolved using declaration), it has to be an overloaded
3302 // function set, which means it must contain either multiple
3303 // declarations (all methods or method templates) or a single
3304 // method template.
3305 assert((MemE->getNumDecls() > 1) ||
3306 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003307 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003308
John McCallaa81e162009-12-01 22:10:20 +00003309 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3310 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003311 }
3312
Douglas Gregorfa047642009-02-04 00:32:51 +00003313 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003314 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003315 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003316 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003317 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3318 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003319 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003320
3321 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003322 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003323 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3324 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003325 if (const FunctionProtoType *FPT =
3326 dyn_cast<FunctionProtoType>(BO->getType())) {
3327 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003328
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003329 ExprOwningPtr<CXXMemberCallExpr>
3330 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3331 NumArgs, ResultTy,
3332 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003333
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003334 if (CheckCallReturnType(FPT->getResultType(),
3335 BO->getRHS()->getSourceRange().getBegin(),
3336 TheCall.get(), 0))
3337 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003338
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003339 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3340 RParenLoc))
3341 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003342
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003343 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3344 }
3345 return ExprError(Diag(Fn->getLocStart(),
3346 diag::err_typecheck_call_not_function)
3347 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003348 }
3349 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003350 }
3351
Douglas Gregorfa047642009-02-04 00:32:51 +00003352 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003353 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003354 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003355
John McCall3b4294e2009-12-16 12:17:52 +00003356 Expr *NakedFn = Fn->IgnoreParenCasts();
3357 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3358 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3359 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3360 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003361 }
Chris Lattner04421082008-04-08 04:40:51 +00003362
John McCall3b4294e2009-12-16 12:17:52 +00003363 NamedDecl *NDecl = 0;
3364 if (isa<DeclRefExpr>(NakedFn))
3365 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3366
John McCallaa81e162009-12-01 22:10:20 +00003367 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3368}
3369
John McCall3b4294e2009-12-16 12:17:52 +00003370/// BuildResolvedCallExpr - Build a call to a resolved expression,
3371/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003372/// unary-convert to an expression of function-pointer or
3373/// block-pointer type.
3374///
3375/// \param NDecl the declaration being called, if available
3376Sema::OwningExprResult
3377Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3378 SourceLocation LParenLoc,
3379 Expr **Args, unsigned NumArgs,
3380 SourceLocation RParenLoc) {
3381 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3382
Chris Lattner04421082008-04-08 04:40:51 +00003383 // Promote the function operand.
3384 UsualUnaryConversions(Fn);
3385
Chris Lattner925e60d2007-12-28 05:29:59 +00003386 // Make the call expr early, before semantic checks. This guarantees cleanup
3387 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003388 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3389 Args, NumArgs,
3390 Context.BoolTy,
3391 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003392
Steve Naroffdd972f22008-09-05 22:11:13 +00003393 const FunctionType *FuncT;
3394 if (!Fn->getType()->isBlockPointerType()) {
3395 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3396 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003397 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003398 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003399 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3400 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003401 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003402 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003403 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003404 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003405 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003406 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003407 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3408 << Fn->getType() << Fn->getSourceRange());
3409
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003410 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003411 if (CheckCallReturnType(FuncT->getResultType(),
3412 Fn->getSourceRange().getBegin(), TheCall.get(),
3413 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003414 return ExprError();
3415
Chris Lattner925e60d2007-12-28 05:29:59 +00003416 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003417 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003418
Douglas Gregor72564e72009-02-26 23:50:07 +00003419 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003420 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003421 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003422 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003423 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003424 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003425
Douglas Gregor74734d52009-04-02 15:37:10 +00003426 if (FDecl) {
3427 // Check if we have too few/too many template arguments, based
3428 // on our knowledge of the function definition.
3429 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003430 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003431 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003432 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003433 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3434 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3435 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3436 }
3437 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003438 }
3439
Steve Naroffb291ab62007-08-28 23:30:39 +00003440 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003441 for (unsigned i = 0; i != NumArgs; i++) {
3442 Expr *Arg = Args[i];
3443 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003444 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3445 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003446 PDiag(diag::err_call_incomplete_argument)
3447 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003448 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003449 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003450 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003451 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003452
Douglas Gregor88a35142008-12-22 05:46:06 +00003453 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3454 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003455 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3456 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003457
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003458 // Check for sentinels
3459 if (NDecl)
3460 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Chris Lattner59907c42007-08-10 20:18:51 +00003462 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003463 if (FDecl) {
3464 if (CheckFunctionCall(FDecl, TheCall.get()))
3465 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003466
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003467 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003468 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3469 } else if (NDecl) {
3470 if (CheckBlockCall(NDecl, TheCall.get()))
3471 return ExprError();
3472 }
Chris Lattner59907c42007-08-10 20:18:51 +00003473
Anders Carlssonec74c592009-08-16 03:06:32 +00003474 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003475}
3476
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003477Action::OwningExprResult
3478Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3479 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003480 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Douglas Gregor99a2e602009-12-16 01:38:02 +00003481
3482 TypeSourceInfo *TInfo = 0;
3483 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3484 if (!TInfo)
3485 TInfo = Context.getTrivialTypeSourceInfo(literalType, LParenLoc);
3486
Steve Naroffaff1edd2007-07-19 21:32:11 +00003487 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003488 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003489 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003490
Eli Friedman6223c222008-05-20 05:22:08 +00003491 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003492 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003493 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3494 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003495 } else if (!literalType->isDependentType() &&
3496 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003497 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003498 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003499 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003500 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003501
Douglas Gregor99a2e602009-12-16 01:38:02 +00003502 InitializedEntity Entity
3503 = InitializedEntity::InitializeTemporary(TInfo->getTypeLoc());
3504 InitializationKind Kind
3505 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3506 /*IsCStyleCast=*/true);
3507 if (CheckInitializerTypes(literalExpr, literalType, Entity, Kind))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003508 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003509
Chris Lattner371f2582008-12-04 23:50:19 +00003510 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003511 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003512 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003513 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003514 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003515 InitExpr.release();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003516
3517 // FIXME: Store the TInfo to preserve type information better.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003518 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003519 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003520}
3521
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003522Action::OwningExprResult
3523Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003524 SourceLocation RBraceLoc) {
3525 unsigned NumInit = initlist.size();
3526 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003527
Steve Naroff08d92e42007-09-15 18:49:24 +00003528 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003529 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003530
Mike Stumpeed9cac2009-02-19 03:04:26 +00003531 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003532 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003533 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003534 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003535}
3536
Anders Carlsson82debc72009-10-18 18:12:03 +00003537static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3538 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003539 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003540 return CastExpr::CK_NoOp;
3541
3542 if (SrcTy->hasPointerRepresentation()) {
3543 if (DestTy->hasPointerRepresentation())
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003544 return DestTy->isObjCObjectPointerType() ?
3545 CastExpr::CK_AnyPointerToObjCPointerCast :
3546 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003547 if (DestTy->isIntegerType())
3548 return CastExpr::CK_PointerToIntegral;
3549 }
3550
3551 if (SrcTy->isIntegerType()) {
3552 if (DestTy->isIntegerType())
3553 return CastExpr::CK_IntegralCast;
3554 if (DestTy->hasPointerRepresentation())
3555 return CastExpr::CK_IntegralToPointer;
3556 if (DestTy->isRealFloatingType())
3557 return CastExpr::CK_IntegralToFloating;
3558 }
3559
3560 if (SrcTy->isRealFloatingType()) {
3561 if (DestTy->isRealFloatingType())
3562 return CastExpr::CK_FloatingCast;
3563 if (DestTy->isIntegerType())
3564 return CastExpr::CK_FloatingToIntegral;
3565 }
3566
3567 // FIXME: Assert here.
3568 // assert(false && "Unhandled cast combination!");
3569 return CastExpr::CK_Unknown;
3570}
3571
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003572/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003573bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003574 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003575 CXXMethodDecl *& ConversionDecl,
3576 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003577 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003578 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3579 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003580
Eli Friedman199ea952009-08-15 19:02:19 +00003581 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003582
3583 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3584 // type needs to be scalar.
3585 if (castType->isVoidType()) {
3586 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003587 Kind = CastExpr::CK_ToVoid;
3588 return false;
3589 }
3590
3591 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003592 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003593 (castType->isStructureType() || castType->isUnionType())) {
3594 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003595 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003596 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3597 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003598 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003599 return false;
3600 }
3601
3602 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003603 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003604 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003605 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003606 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003607 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003608 if (Context.hasSameUnqualifiedType(Field->getType(),
3609 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003610 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3611 << castExpr->getSourceRange();
3612 break;
3613 }
3614 }
3615 if (Field == FieldEnd)
3616 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3617 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003618 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003619 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003620 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003621
3622 // Reject any other conversions to non-scalar types.
3623 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3624 << castType << castExpr->getSourceRange();
3625 }
3626
3627 if (!castExpr->getType()->isScalarType() &&
3628 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003629 return Diag(castExpr->getLocStart(),
3630 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003631 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003632 }
3633
Anders Carlsson16a89042009-10-16 05:23:41 +00003634 if (castType->isExtVectorType())
3635 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3636
Anders Carlssonc3516322009-10-16 02:48:28 +00003637 if (castType->isVectorType())
3638 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3639 if (castExpr->getType()->isVectorType())
3640 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3641
3642 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003643 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003644
Anders Carlsson16a89042009-10-16 05:23:41 +00003645 if (isa<ObjCSelectorExpr>(castExpr))
3646 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3647
Anders Carlssonc3516322009-10-16 02:48:28 +00003648 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003649 QualType castExprType = castExpr->getType();
3650 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3651 return Diag(castExpr->getLocStart(),
3652 diag::err_cast_pointer_from_non_pointer_int)
3653 << castExprType << castExpr->getSourceRange();
3654 } else if (!castExpr->getType()->isArithmeticType()) {
3655 if (!castType->isIntegralType() && castType->isArithmeticType())
3656 return Diag(castExpr->getLocStart(),
3657 diag::err_cast_pointer_to_non_pointer_int)
3658 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003659 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003660
3661 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003662 return false;
3663}
3664
Anders Carlssonc3516322009-10-16 02:48:28 +00003665bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3666 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003667 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003668
Anders Carlssona64db8f2007-11-27 05:51:55 +00003669 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003670 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003671 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003672 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003673 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003674 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003675 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003676 } else
3677 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003678 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003679 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003680
Anders Carlssonc3516322009-10-16 02:48:28 +00003681 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003682 return false;
3683}
3684
Anders Carlsson16a89042009-10-16 05:23:41 +00003685bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3686 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003687 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003688
3689 QualType SrcTy = CastExpr->getType();
3690
Nate Begeman9b10da62009-06-27 22:05:55 +00003691 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3692 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003693 if (SrcTy->isVectorType()) {
3694 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3695 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3696 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003697 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003698 return false;
3699 }
3700
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003701 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003702 // conversion will take place first from scalar to elt type, and then
3703 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003704 if (SrcTy->isPointerType())
3705 return Diag(R.getBegin(),
3706 diag::err_invalid_conversion_between_vector_and_scalar)
3707 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003708
3709 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3710 ImpCastExprToType(CastExpr, DestElemTy,
3711 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003712
3713 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003714 return false;
3715}
3716
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003717Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003718Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003719 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003720 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003722 assert((Ty != 0) && (Op.get() != 0) &&
3723 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003724
Nate Begeman2ef13e52009-08-10 23:49:36 +00003725 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003726 //FIXME: Preserve type source info.
3727 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Nate Begeman2ef13e52009-08-10 23:49:36 +00003729 // If the Expr being casted is a ParenListExpr, handle it specially.
3730 if (isa<ParenListExpr>(castExpr))
3731 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003732 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003733 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003734 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003735 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003736
3737 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003738 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003739 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003740
Anders Carlsson0aebc812009-09-09 21:33:21 +00003741 if (CastArg.isInvalid())
3742 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003743
Anders Carlsson0aebc812009-09-09 21:33:21 +00003744 castExpr = CastArg.takeAs<Expr>();
3745 } else {
3746 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003747 }
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003749 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003750 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003751 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003752}
3753
Nate Begeman2ef13e52009-08-10 23:49:36 +00003754/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3755/// of comma binary operators.
3756Action::OwningExprResult
3757Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3758 Expr *expr = EA.takeAs<Expr>();
3759 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3760 if (!E)
3761 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Nate Begeman2ef13e52009-08-10 23:49:36 +00003763 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003764
Nate Begeman2ef13e52009-08-10 23:49:36 +00003765 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3766 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3767 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003768
Nate Begeman2ef13e52009-08-10 23:49:36 +00003769 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3770}
3771
3772Action::OwningExprResult
3773Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3774 SourceLocation RParenLoc, ExprArg Op,
3775 QualType Ty) {
3776 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003777
3778 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003779 // then handle it as such.
3780 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3781 if (PE->getNumExprs() == 0) {
3782 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3783 return ExprError();
3784 }
3785
3786 llvm::SmallVector<Expr *, 8> initExprs;
3787 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3788 initExprs.push_back(PE->getExpr(i));
3789
3790 // FIXME: This means that pretty-printing the final AST will produce curly
3791 // braces instead of the original commas.
3792 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003793 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003794 initExprs.size(), RParenLoc);
3795 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003796 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003797 Owned(E));
3798 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003799 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003800 // sequence of BinOp comma operators.
3801 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3802 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3803 }
3804}
3805
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003806Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003807 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003808 MultiExprArg Val,
3809 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003810 unsigned nexprs = Val.size();
3811 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003812 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3813 Expr *expr;
3814 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3815 expr = new (Context) ParenExpr(L, R, exprs[0]);
3816 else
3817 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003818 return Owned(expr);
3819}
3820
Sebastian Redl28507842009-02-26 14:39:58 +00003821/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3822/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003823/// C99 6.5.15
3824QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3825 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003826 // C++ is sufficiently different to merit its own checker.
3827 if (getLangOptions().CPlusPlus)
3828 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3829
John McCallb13c87f2009-11-05 09:23:39 +00003830 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3831
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003832 UsualUnaryConversions(Cond);
3833 UsualUnaryConversions(LHS);
3834 UsualUnaryConversions(RHS);
3835 QualType CondTy = Cond->getType();
3836 QualType LHSTy = LHS->getType();
3837 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003838
Reid Spencer5f016e22007-07-11 17:01:13 +00003839 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003840 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3841 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3842 << CondTy;
3843 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003844 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003845
Chris Lattner70d67a92008-01-06 22:42:25 +00003846 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003847 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3848 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003849
Chris Lattner70d67a92008-01-06 22:42:25 +00003850 // If both operands have arithmetic type, do the usual arithmetic conversions
3851 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003852 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3853 UsualArithmeticConversions(LHS, RHS);
3854 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003855 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003856
Chris Lattner70d67a92008-01-06 22:42:25 +00003857 // If both operands are the same structure or union type, the result is that
3858 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003859 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3860 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003861 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003862 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003863 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003864 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003865 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003866 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003867
Chris Lattner70d67a92008-01-06 22:42:25 +00003868 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003869 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003870 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3871 if (!LHSTy->isVoidType())
3872 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3873 << RHS->getSourceRange();
3874 if (!RHSTy->isVoidType())
3875 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3876 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003877 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3878 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003879 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003880 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003881 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3882 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003883 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003884 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003885 // promote the null to a pointer.
3886 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003887 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003888 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003889 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003890 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003891 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003892 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003893 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003894
3895 // All objective-c pointer type analysis is done here.
3896 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
3897 QuestionLoc);
3898 if (!compositeType.isNull())
3899 return compositeType;
3900
3901
Steve Naroff7154a772009-07-01 14:36:47 +00003902 // Handle block pointer types.
3903 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3904 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3905 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3906 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003907 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3908 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003909 return destType;
3910 }
3911 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003912 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00003913 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003914 }
Steve Naroff7154a772009-07-01 14:36:47 +00003915 // We have 2 block pointer types.
3916 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3917 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003918 return LHSTy;
3919 }
Steve Naroff7154a772009-07-01 14:36:47 +00003920 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003921 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3922 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003923
Steve Naroff7154a772009-07-01 14:36:47 +00003924 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3925 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003926 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003927 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003928 // In this situation, we assume void* type. No especially good
3929 // reason, but this is what gcc does, and we do have to pick
3930 // to get a consistent AST.
3931 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003932 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3933 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003934 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003935 }
Steve Naroff7154a772009-07-01 14:36:47 +00003936 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003937 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3938 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003939 return LHSTy;
3940 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003941
Steve Naroff7154a772009-07-01 14:36:47 +00003942 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3943 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3944 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003945 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3946 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003947
3948 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3949 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3950 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00003951 QualType destPointee
3952 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003953 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003954 // Add qualifiers if necessary.
3955 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3956 // Promote to void*.
3957 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003958 return destType;
3959 }
3960 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00003961 QualType destPointee
3962 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003963 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003964 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003965 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003966 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003967 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003968 return destType;
3969 }
3970
3971 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3972 // Two identical pointer types are always compatible.
3973 return LHSTy;
3974 }
3975 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3976 rhptee.getUnqualifiedType())) {
3977 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3978 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3979 // In this situation, we assume void* type. No especially good
3980 // reason, but this is what gcc does, and we do have to pick
3981 // to get a consistent AST.
3982 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003983 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3984 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003985 return incompatTy;
3986 }
3987 // The pointer types are compatible.
3988 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3989 // differently qualified versions of compatible types, the result type is
3990 // a pointer to an appropriately qualified version of the *composite*
3991 // type.
3992 // FIXME: Need to calculate the composite type.
3993 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00003994 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3995 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003996 return LHSTy;
3997 }
Mike Stump1eb44332009-09-09 15:08:12 +00003998
Steve Naroff7154a772009-07-01 14:36:47 +00003999 // GCC compatibility: soften pointer/integer mismatch.
4000 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4001 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4002 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004003 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004004 return RHSTy;
4005 }
4006 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4007 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4008 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004009 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004010 return LHSTy;
4011 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004012
Chris Lattner70d67a92008-01-06 22:42:25 +00004013 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004014 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4015 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004016 return QualType();
4017}
4018
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004019/// FindCompositeObjCPointerType - Helper method to find composite type of
4020/// two objective-c pointer types of the two input expressions.
4021QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4022 SourceLocation QuestionLoc) {
4023 QualType LHSTy = LHS->getType();
4024 QualType RHSTy = RHS->getType();
4025
4026 // Handle things like Class and struct objc_class*. Here we case the result
4027 // to the pseudo-builtin, because that will be implicitly cast back to the
4028 // redefinition type if an attempt is made to access its fields.
4029 if (LHSTy->isObjCClassType() &&
4030 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4031 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4032 return LHSTy;
4033 }
4034 if (RHSTy->isObjCClassType() &&
4035 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4036 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4037 return RHSTy;
4038 }
4039 // And the same for struct objc_object* / id
4040 if (LHSTy->isObjCIdType() &&
4041 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4042 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4043 return LHSTy;
4044 }
4045 if (RHSTy->isObjCIdType() &&
4046 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4047 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4048 return RHSTy;
4049 }
4050 // And the same for struct objc_selector* / SEL
4051 if (Context.isObjCSelType(LHSTy) &&
4052 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4053 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4054 return LHSTy;
4055 }
4056 if (Context.isObjCSelType(RHSTy) &&
4057 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4058 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4059 return RHSTy;
4060 }
4061 // Check constraints for Objective-C object pointers types.
4062 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4063
4064 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4065 // Two identical object pointer types are always compatible.
4066 return LHSTy;
4067 }
4068 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4069 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4070 QualType compositeType = LHSTy;
4071
4072 // If both operands are interfaces and either operand can be
4073 // assigned to the other, use that type as the composite
4074 // type. This allows
4075 // xxx ? (A*) a : (B*) b
4076 // where B is a subclass of A.
4077 //
4078 // Additionally, as for assignment, if either type is 'id'
4079 // allow silent coercion. Finally, if the types are
4080 // incompatible then make sure to use 'id' as the composite
4081 // type so the result is acceptable for sending messages to.
4082
4083 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4084 // It could return the composite type.
4085 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4086 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4087 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4088 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4089 } else if ((LHSTy->isObjCQualifiedIdType() ||
4090 RHSTy->isObjCQualifiedIdType()) &&
4091 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4092 // Need to handle "id<xx>" explicitly.
4093 // GCC allows qualified id and any Objective-C type to devolve to
4094 // id. Currently localizing to here until clear this should be
4095 // part of ObjCQualifiedIdTypesAreCompatible.
4096 compositeType = Context.getObjCIdType();
4097 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4098 compositeType = Context.getObjCIdType();
4099 } else if (!(compositeType =
4100 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4101 ;
4102 else {
4103 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4104 << LHSTy << RHSTy
4105 << LHS->getSourceRange() << RHS->getSourceRange();
4106 QualType incompatTy = Context.getObjCIdType();
4107 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4108 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4109 return incompatTy;
4110 }
4111 // The object pointer types are compatible.
4112 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4113 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4114 return compositeType;
4115 }
4116 // Check Objective-C object pointer types and 'void *'
4117 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4118 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4119 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4120 QualType destPointee
4121 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4122 QualType destType = Context.getPointerType(destPointee);
4123 // Add qualifiers if necessary.
4124 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4125 // Promote to void*.
4126 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4127 return destType;
4128 }
4129 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4130 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4131 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4132 QualType destPointee
4133 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4134 QualType destType = Context.getPointerType(destPointee);
4135 // Add qualifiers if necessary.
4136 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4137 // Promote to void*.
4138 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4139 return destType;
4140 }
4141 return QualType();
4142}
4143
Steve Narofff69936d2007-09-16 03:34:24 +00004144/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004145/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004146Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4147 SourceLocation ColonLoc,
4148 ExprArg Cond, ExprArg LHS,
4149 ExprArg RHS) {
4150 Expr *CondExpr = (Expr *) Cond.get();
4151 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004152
4153 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4154 // was the condition.
4155 bool isLHSNull = LHSExpr == 0;
4156 if (isLHSNull)
4157 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004158
4159 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004160 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004161 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004162 return ExprError();
4163
4164 Cond.release();
4165 LHS.release();
4166 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004167 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004168 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004169 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004170}
4171
Reid Spencer5f016e22007-07-11 17:01:13 +00004172// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004173// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004174// routine is it effectively iqnores the qualifiers on the top level pointee.
4175// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4176// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004177Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004178Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4179 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004180
David Chisnall0f436562009-08-17 16:35:33 +00004181 if ((lhsType->isObjCClassType() &&
4182 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4183 (rhsType->isObjCClassType() &&
4184 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4185 return Compatible;
4186 }
4187
Reid Spencer5f016e22007-07-11 17:01:13 +00004188 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004189 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4190 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004191
Reid Spencer5f016e22007-07-11 17:01:13 +00004192 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004193 lhptee = Context.getCanonicalType(lhptee);
4194 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004195
Chris Lattner5cf216b2008-01-04 18:04:52 +00004196 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004197
4198 // C99 6.5.16.1p1: This following citation is common to constraints
4199 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4200 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004201 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004202 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004203 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004204
Mike Stumpeed9cac2009-02-19 03:04:26 +00004205 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4206 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004207 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004208 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004209 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004210 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004211
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004212 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004213 assert(rhptee->isFunctionType());
4214 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004215 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004216
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004217 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004218 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004219 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004220
4221 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004222 assert(lhptee->isFunctionType());
4223 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004224 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004225 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004226 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004227 lhptee = lhptee.getUnqualifiedType();
4228 rhptee = rhptee.getUnqualifiedType();
4229 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4230 // Check if the pointee types are compatible ignoring the sign.
4231 // We explicitly check for char so that we catch "char" vs
4232 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004233 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004234 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004235 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004236 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004237
4238 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004239 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004240 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004241 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004242
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004243 if (lhptee == rhptee) {
4244 // Types are compatible ignoring the sign. Qualifier incompatibility
4245 // takes priority over sign incompatibility because the sign
4246 // warning can be disabled.
4247 if (ConvTy != Compatible)
4248 return ConvTy;
4249 return IncompatiblePointerSign;
4250 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004251
4252 // If we are a multi-level pointer, it's possible that our issue is simply
4253 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4254 // the eventual target type is the same and the pointers have the same
4255 // level of indirection, this must be the issue.
4256 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4257 do {
4258 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4259 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4260
4261 lhptee = Context.getCanonicalType(lhptee);
4262 rhptee = Context.getCanonicalType(rhptee);
4263 } while (lhptee->isPointerType() && rhptee->isPointerType());
4264
Douglas Gregora4923eb2009-11-16 21:35:15 +00004265 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004266 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004267 }
4268
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004269 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004270 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004271 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004272 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004273}
4274
Steve Naroff1c7d0672008-09-04 15:10:53 +00004275/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4276/// block pointer types are compatible or whether a block and normal pointer
4277/// are compatible. It is more restrict than comparing two function pointer
4278// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004279Sema::AssignConvertType
4280Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004281 QualType rhsType) {
4282 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004283
Steve Naroff1c7d0672008-09-04 15:10:53 +00004284 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004285 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4286 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004287
Steve Naroff1c7d0672008-09-04 15:10:53 +00004288 // make sure we operate on the canonical type
4289 lhptee = Context.getCanonicalType(lhptee);
4290 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004291
Steve Naroff1c7d0672008-09-04 15:10:53 +00004292 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004293
Steve Naroff1c7d0672008-09-04 15:10:53 +00004294 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004295 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004296 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004297
Eli Friedman26784c12009-06-08 05:08:54 +00004298 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004299 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004300 return ConvTy;
4301}
4302
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004303/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4304/// for assignment compatibility.
4305Sema::AssignConvertType
4306Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4307 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4308 return Compatible;
4309 QualType lhptee =
4310 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4311 QualType rhptee =
4312 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4313 // make sure we operate on the canonical type
4314 lhptee = Context.getCanonicalType(lhptee);
4315 rhptee = Context.getCanonicalType(rhptee);
4316 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4317 return CompatiblePointerDiscardsQualifiers;
4318
4319 if (Context.typesAreCompatible(lhsType, rhsType))
4320 return Compatible;
4321 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4322 return IncompatibleObjCQualifiedId;
4323 return IncompatiblePointer;
4324}
4325
Mike Stumpeed9cac2009-02-19 03:04:26 +00004326/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4327/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004328/// pointers. Here are some objectionable examples that GCC considers warnings:
4329///
4330/// int a, *pint;
4331/// short *pshort;
4332/// struct foo *pfoo;
4333///
4334/// pint = pshort; // warning: assignment from incompatible pointer type
4335/// a = pint; // warning: assignment makes integer from pointer without a cast
4336/// pint = a; // warning: assignment makes pointer from integer without a cast
4337/// pint = pfoo; // warning: assignment from incompatible pointer type
4338///
4339/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004340/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004341///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004342Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004343Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004344 // Get canonical types. We're not formatting these types, just comparing
4345 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004346 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4347 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004348
4349 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004350 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004351
David Chisnall0f436562009-08-17 16:35:33 +00004352 if ((lhsType->isObjCClassType() &&
4353 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4354 (rhsType->isObjCClassType() &&
4355 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4356 return Compatible;
4357 }
4358
Douglas Gregor9d293df2008-10-28 00:22:11 +00004359 // If the left-hand side is a reference type, then we are in a
4360 // (rare!) case where we've allowed the use of references in C,
4361 // e.g., as a parameter type in a built-in function. In this case,
4362 // just make sure that the type referenced is compatible with the
4363 // right-hand side type. The caller is responsible for adjusting
4364 // lhsType so that the resulting expression does not have reference
4365 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004366 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004367 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004368 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004369 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004370 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004371 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4372 // to the same ExtVector type.
4373 if (lhsType->isExtVectorType()) {
4374 if (rhsType->isExtVectorType())
4375 return lhsType == rhsType ? Compatible : Incompatible;
4376 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4377 return Compatible;
4378 }
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Nate Begemanbe2341d2008-07-14 18:02:46 +00004380 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004381 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004382 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004383 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004384 if (getLangOptions().LaxVectorConversions &&
4385 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004386 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004387 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004388 }
4389 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004390 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004391
Chris Lattnere8b3e962008-01-04 23:32:24 +00004392 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004393 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004394
Chris Lattner78eca282008-04-07 06:49:41 +00004395 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004396 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004397 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004398
Chris Lattner78eca282008-04-07 06:49:41 +00004399 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004400 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004401
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004402 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004403 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004404 if (lhsType->isVoidPointerType()) // an exception to the rule.
4405 return Compatible;
4406 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004407 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004408 if (rhsType->getAs<BlockPointerType>()) {
4409 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004410 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004411
4412 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004413 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004414 return Compatible;
4415 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004416 return Incompatible;
4417 }
4418
4419 if (isa<BlockPointerType>(lhsType)) {
4420 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004421 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004422
Steve Naroffb4406862008-09-29 18:10:17 +00004423 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004424 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004425 return Compatible;
4426
Steve Naroff1c7d0672008-09-04 15:10:53 +00004427 if (rhsType->isBlockPointerType())
4428 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004429
Ted Kremenek6217b802009-07-29 21:53:49 +00004430 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004431 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004432 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004433 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004434 return Incompatible;
4435 }
4436
Steve Naroff14108da2009-07-10 23:34:53 +00004437 if (isa<ObjCObjectPointerType>(lhsType)) {
4438 if (rhsType->isIntegerType())
4439 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004440
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004441 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004442 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004443 if (rhsType->isVoidPointerType()) // an exception to the rule.
4444 return Compatible;
4445 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004446 }
4447 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004448 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004449 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004450 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004451 if (RHSPT->getPointeeType()->isVoidType())
4452 return Compatible;
4453 }
4454 // Treat block pointers as objects.
4455 if (rhsType->isBlockPointerType())
4456 return Compatible;
4457 return Incompatible;
4458 }
Chris Lattner78eca282008-04-07 06:49:41 +00004459 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004460 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004461 if (lhsType == Context.BoolTy)
4462 return Compatible;
4463
4464 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004465 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004466
Mike Stumpeed9cac2009-02-19 03:04:26 +00004467 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004468 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004469
4470 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004471 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004472 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004473 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004474 }
Steve Naroff14108da2009-07-10 23:34:53 +00004475 if (isa<ObjCObjectPointerType>(rhsType)) {
4476 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4477 if (lhsType == Context.BoolTy)
4478 return Compatible;
4479
4480 if (lhsType->isIntegerType())
4481 return PointerToInt;
4482
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004483 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004484 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004485 if (lhsType->isVoidPointerType()) // an exception to the rule.
4486 return Compatible;
4487 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004488 }
4489 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004490 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004491 return Compatible;
4492 return Incompatible;
4493 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004494
Chris Lattnerfc144e22008-01-04 23:18:45 +00004495 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004496 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004497 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004498 }
4499 return Incompatible;
4500}
4501
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004502/// \brief Constructs a transparent union from an expression that is
4503/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004504static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004505 QualType UnionType, FieldDecl *Field) {
4506 // Build an initializer list that designates the appropriate member
4507 // of the transparent union.
4508 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4509 &E, 1,
4510 SourceLocation());
4511 Initializer->setType(UnionType);
4512 Initializer->setInitializedFieldInUnion(Field);
4513
4514 // Build a compound literal constructing a value of the transparent
4515 // union type from this initializer list.
4516 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4517 false);
4518}
4519
4520Sema::AssignConvertType
4521Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4522 QualType FromType = rExpr->getType();
4523
Mike Stump1eb44332009-09-09 15:08:12 +00004524 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004525 // transparent_union GCC extension.
4526 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004527 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004528 return Incompatible;
4529
4530 // The field to initialize within the transparent union.
4531 RecordDecl *UD = UT->getDecl();
4532 FieldDecl *InitField = 0;
4533 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004534 for (RecordDecl::field_iterator it = UD->field_begin(),
4535 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004536 it != itend; ++it) {
4537 if (it->getType()->isPointerType()) {
4538 // If the transparent union contains a pointer type, we allow:
4539 // 1) void pointer
4540 // 2) null pointer constant
4541 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004542 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004543 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004544 InitField = *it;
4545 break;
4546 }
Mike Stump1eb44332009-09-09 15:08:12 +00004547
Douglas Gregorce940492009-09-25 04:25:58 +00004548 if (rExpr->isNullPointerConstant(Context,
4549 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004550 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004551 InitField = *it;
4552 break;
4553 }
4554 }
4555
4556 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4557 == Compatible) {
4558 InitField = *it;
4559 break;
4560 }
4561 }
4562
4563 if (!InitField)
4564 return Incompatible;
4565
4566 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4567 return Compatible;
4568}
4569
Chris Lattner5cf216b2008-01-04 18:04:52 +00004570Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004571Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004572 if (getLangOptions().CPlusPlus) {
4573 if (!lhsType->isRecordType()) {
4574 // C++ 5.17p3: If the left operand is not of class type, the
4575 // expression is implicitly converted (C++ 4) to the
4576 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004577 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004578 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004579 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004580 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004581 }
4582
4583 // FIXME: Currently, we fall through and treat C++ classes like C
4584 // structures.
4585 }
4586
Steve Naroff529a4ad2007-11-27 17:58:44 +00004587 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4588 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004589 if ((lhsType->isPointerType() ||
4590 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004591 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004592 && rExpr->isNullPointerConstant(Context,
4593 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004594 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004595 return Compatible;
4596 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004597
Chris Lattner943140e2007-10-16 02:55:40 +00004598 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004599 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004600 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004601 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004602 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004603 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004604 if (!lhsType->isReferenceType())
4605 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004606
Chris Lattner5cf216b2008-01-04 18:04:52 +00004607 Sema::AssignConvertType result =
4608 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004609
Steve Narofff1120de2007-08-24 22:33:52 +00004610 // C99 6.5.16.1p2: The value of the right operand is converted to the
4611 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004612 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4613 // so that we can use references in built-in functions even in C.
4614 // The getNonReferenceType() call makes sure that the resulting expression
4615 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004616 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004617 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4618 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004619 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004620}
4621
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004622QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004623 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004624 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004625 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004626 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004627}
4628
Mike Stumpeed9cac2009-02-19 03:04:26 +00004629inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004630 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004631 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004632 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004633 QualType lhsType =
4634 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4635 QualType rhsType =
4636 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004637
Nate Begemanbe2341d2008-07-14 18:02:46 +00004638 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004639 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004640 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004641
Nate Begemanbe2341d2008-07-14 18:02:46 +00004642 // Handle the case of a vector & extvector type of the same size and element
4643 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004644 if (getLangOptions().LaxVectorConversions) {
4645 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004646 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4647 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004648 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004649 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004650 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004651 }
4652 }
4653 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004654
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004655 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4656 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4657 bool swapped = false;
4658 if (rhsType->isExtVectorType()) {
4659 swapped = true;
4660 std::swap(rex, lex);
4661 std::swap(rhsType, lhsType);
4662 }
Mike Stump1eb44332009-09-09 15:08:12 +00004663
Nate Begemandde25982009-06-28 19:12:57 +00004664 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004665 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004666 QualType EltTy = LV->getElementType();
4667 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4668 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004669 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004670 if (swapped) std::swap(rex, lex);
4671 return lhsType;
4672 }
4673 }
4674 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4675 rhsType->isRealFloatingType()) {
4676 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004677 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004678 if (swapped) std::swap(rex, lex);
4679 return lhsType;
4680 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004681 }
4682 }
Mike Stump1eb44332009-09-09 15:08:12 +00004683
Nate Begemandde25982009-06-28 19:12:57 +00004684 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004685 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004686 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004687 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004688 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004689}
4690
Reid Spencer5f016e22007-07-11 17:01:13 +00004691inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004692 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004693 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004694 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004695
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004696 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004697
Steve Naroffa4332e22007-07-17 00:58:39 +00004698 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004699 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004700 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004701}
4702
4703inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004704 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004705 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4706 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4707 return CheckVectorOperands(Loc, lex, rex);
4708 return InvalidOperands(Loc, lex, rex);
4709 }
Steve Naroff90045e82007-07-13 23:32:42 +00004710
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004711 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004712
Steve Naroffa4332e22007-07-17 00:58:39 +00004713 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004714 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004715 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004716}
4717
4718inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004719 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004720 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4721 QualType compType = CheckVectorOperands(Loc, lex, rex);
4722 if (CompLHSTy) *CompLHSTy = compType;
4723 return compType;
4724 }
Steve Naroff49b45262007-07-13 16:58:59 +00004725
Eli Friedmanab3a8522009-03-28 01:22:36 +00004726 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004727
Reid Spencer5f016e22007-07-11 17:01:13 +00004728 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004729 if (lex->getType()->isArithmeticType() &&
4730 rex->getType()->isArithmeticType()) {
4731 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004732 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004733 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004734
Eli Friedmand72d16e2008-05-18 18:08:51 +00004735 // Put any potential pointer into PExp
4736 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004737 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004738 std::swap(PExp, IExp);
4739
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004740 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004741
Eli Friedmand72d16e2008-05-18 18:08:51 +00004742 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004743 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Chris Lattnerb5f15622009-04-24 23:50:08 +00004745 // Check for arithmetic on pointers to incomplete types.
4746 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004747 if (getLangOptions().CPlusPlus) {
4748 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004749 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004750 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004751 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004752
4753 // GNU extension: arithmetic on pointer to void
4754 Diag(Loc, diag::ext_gnu_void_ptr)
4755 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004756 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004757 if (getLangOptions().CPlusPlus) {
4758 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4759 << lex->getType() << lex->getSourceRange();
4760 return QualType();
4761 }
4762
4763 // GNU extension: arithmetic on pointer to function
4764 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4765 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004766 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004767 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004768 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004769 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004770 PExp->getType()->isObjCObjectPointerType()) &&
4771 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004772 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4773 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004774 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004775 return QualType();
4776 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004777 // Diagnose bad cases where we step over interface counts.
4778 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4779 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4780 << PointeeTy << PExp->getSourceRange();
4781 return QualType();
4782 }
Mike Stump1eb44332009-09-09 15:08:12 +00004783
Eli Friedmanab3a8522009-03-28 01:22:36 +00004784 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004785 QualType LHSTy = Context.isPromotableBitField(lex);
4786 if (LHSTy.isNull()) {
4787 LHSTy = lex->getType();
4788 if (LHSTy->isPromotableIntegerType())
4789 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004790 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004791 *CompLHSTy = LHSTy;
4792 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004793 return PExp->getType();
4794 }
4795 }
4796
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004797 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004798}
4799
Chris Lattnereca7be62008-04-07 05:30:13 +00004800// C99 6.5.6
4801QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004802 SourceLocation Loc, QualType* CompLHSTy) {
4803 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4804 QualType compType = CheckVectorOperands(Loc, lex, rex);
4805 if (CompLHSTy) *CompLHSTy = compType;
4806 return compType;
4807 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004808
Eli Friedmanab3a8522009-03-28 01:22:36 +00004809 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004810
Chris Lattner6e4ab612007-12-09 21:53:25 +00004811 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004812
Chris Lattner6e4ab612007-12-09 21:53:25 +00004813 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004814 if (lex->getType()->isArithmeticType()
4815 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004816 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004817 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004818 }
Mike Stump1eb44332009-09-09 15:08:12 +00004819
Chris Lattner6e4ab612007-12-09 21:53:25 +00004820 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004821 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004822 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004823
Douglas Gregore7450f52009-03-24 19:52:54 +00004824 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004825
Douglas Gregore7450f52009-03-24 19:52:54 +00004826 bool ComplainAboutVoid = false;
4827 Expr *ComplainAboutFunc = 0;
4828 if (lpointee->isVoidType()) {
4829 if (getLangOptions().CPlusPlus) {
4830 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4831 << lex->getSourceRange() << rex->getSourceRange();
4832 return QualType();
4833 }
4834
4835 // GNU C extension: arithmetic on pointer to void
4836 ComplainAboutVoid = true;
4837 } else if (lpointee->isFunctionType()) {
4838 if (getLangOptions().CPlusPlus) {
4839 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004840 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004841 return QualType();
4842 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004843
4844 // GNU C extension: arithmetic on pointer to function
4845 ComplainAboutFunc = lex;
4846 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004847 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004848 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004849 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004850 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004851 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004852
Chris Lattnerb5f15622009-04-24 23:50:08 +00004853 // Diagnose bad cases where we step over interface counts.
4854 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4855 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4856 << lpointee << lex->getSourceRange();
4857 return QualType();
4858 }
Mike Stump1eb44332009-09-09 15:08:12 +00004859
Chris Lattner6e4ab612007-12-09 21:53:25 +00004860 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004861 if (rex->getType()->isIntegerType()) {
4862 if (ComplainAboutVoid)
4863 Diag(Loc, diag::ext_gnu_void_ptr)
4864 << lex->getSourceRange() << rex->getSourceRange();
4865 if (ComplainAboutFunc)
4866 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004867 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004868 << ComplainAboutFunc->getSourceRange();
4869
Eli Friedmanab3a8522009-03-28 01:22:36 +00004870 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004871 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004872 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004873
Chris Lattner6e4ab612007-12-09 21:53:25 +00004874 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004875 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004876 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004877
Douglas Gregore7450f52009-03-24 19:52:54 +00004878 // RHS must be a completely-type object type.
4879 // Handle the GNU void* extension.
4880 if (rpointee->isVoidType()) {
4881 if (getLangOptions().CPlusPlus) {
4882 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4883 << lex->getSourceRange() << rex->getSourceRange();
4884 return QualType();
4885 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004886
Douglas Gregore7450f52009-03-24 19:52:54 +00004887 ComplainAboutVoid = true;
4888 } else if (rpointee->isFunctionType()) {
4889 if (getLangOptions().CPlusPlus) {
4890 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004891 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004892 return QualType();
4893 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004894
4895 // GNU extension: arithmetic on pointer to function
4896 if (!ComplainAboutFunc)
4897 ComplainAboutFunc = rex;
4898 } else if (!rpointee->isDependentType() &&
4899 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004900 PDiag(diag::err_typecheck_sub_ptr_object)
4901 << rex->getSourceRange()
4902 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004903 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004904
Eli Friedman88d936b2009-05-16 13:54:38 +00004905 if (getLangOptions().CPlusPlus) {
4906 // Pointee types must be the same: C++ [expr.add]
4907 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4908 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4909 << lex->getType() << rex->getType()
4910 << lex->getSourceRange() << rex->getSourceRange();
4911 return QualType();
4912 }
4913 } else {
4914 // Pointee types must be compatible C99 6.5.6p3
4915 if (!Context.typesAreCompatible(
4916 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4917 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4918 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4919 << lex->getType() << rex->getType()
4920 << lex->getSourceRange() << rex->getSourceRange();
4921 return QualType();
4922 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004923 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004924
Douglas Gregore7450f52009-03-24 19:52:54 +00004925 if (ComplainAboutVoid)
4926 Diag(Loc, diag::ext_gnu_void_ptr)
4927 << lex->getSourceRange() << rex->getSourceRange();
4928 if (ComplainAboutFunc)
4929 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004930 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004931 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004932
4933 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004934 return Context.getPointerDiffType();
4935 }
4936 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004937
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004938 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004939}
4940
Chris Lattnereca7be62008-04-07 05:30:13 +00004941// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004942QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004943 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004944 // C99 6.5.7p2: Each of the operands shall have integer type.
4945 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004946 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004947
Nate Begeman2207d792009-10-25 02:26:48 +00004948 // Vector shifts promote their scalar inputs to vector type.
4949 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4950 return CheckVectorOperands(Loc, lex, rex);
4951
Chris Lattnerca5eede2007-12-12 05:47:28 +00004952 // Shifts don't perform usual arithmetic conversions, they just do integer
4953 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004954 QualType LHSTy = Context.isPromotableBitField(lex);
4955 if (LHSTy.isNull()) {
4956 LHSTy = lex->getType();
4957 if (LHSTy->isPromotableIntegerType())
4958 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004959 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004960 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004961 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004962
Chris Lattnerca5eede2007-12-12 05:47:28 +00004963 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004964
Ryan Flynnd0439682009-08-07 16:20:20 +00004965 // Sanity-check shift operands
4966 llvm::APSInt Right;
4967 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004968 if (!rex->isValueDependent() &&
4969 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004970 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004971 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4972 else {
4973 llvm::APInt LeftBits(Right.getBitWidth(),
4974 Context.getTypeSize(lex->getType()));
4975 if (Right.uge(LeftBits))
4976 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4977 }
4978 }
4979
Chris Lattnerca5eede2007-12-12 05:47:28 +00004980 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004981 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004982}
4983
John McCall5dbad3d2009-11-06 08:49:08 +00004984/// \brief Implements -Wsign-compare.
4985///
4986/// \param lex the left-hand expression
4987/// \param rex the right-hand expression
4988/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004989/// \param Equality whether this is an "equality-like" join, which
4990/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004991void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004992 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004993 // Don't warn if we're in an unevaluated context.
Douglas Gregor2afce722009-11-26 00:44:06 +00004994 if (ExprEvalContexts.back().Context == Unevaluated)
John McCall7d62a8f2009-11-06 18:16:06 +00004995 return;
4996
John McCall45aa4552009-11-05 00:40:04 +00004997 QualType lt = lex->getType(), rt = rex->getType();
4998
4999 // Only warn if both operands are integral.
5000 if (!lt->isIntegerType() || !rt->isIntegerType())
5001 return;
5002
Sebastian Redl732429c2009-11-05 21:09:23 +00005003 // If either expression is value-dependent, don't warn. We'll get another
5004 // chance at instantiation time.
5005 if (lex->isValueDependent() || rex->isValueDependent())
5006 return;
5007
John McCall45aa4552009-11-05 00:40:04 +00005008 // The rule is that the signed operand becomes unsigned, so isolate the
5009 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00005010 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00005011 if (lt->isSignedIntegerType()) {
5012 if (rt->isSignedIntegerType()) return;
5013 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00005014 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00005015 } else {
5016 if (!rt->isSignedIntegerType()) return;
5017 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00005018 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00005019 }
5020
John McCall5dbad3d2009-11-06 08:49:08 +00005021 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00005022 // then (1) the result type will be signed and (2) the unsigned
5023 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00005024 // of the comparison will be exact.
5025 if (Context.getIntWidth(signedOperand->getType()) >
5026 Context.getIntWidth(unsignedOperand->getType()))
5027 return;
5028
John McCall45aa4552009-11-05 00:40:04 +00005029 // If the value is a non-negative integer constant, then the
5030 // signed->unsigned conversion won't change it.
5031 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00005032 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00005033 assert(value.isSigned() && "result of signed expression not signed");
5034
5035 if (value.isNonNegative())
5036 return;
5037 }
5038
John McCall5dbad3d2009-11-06 08:49:08 +00005039 if (Equality) {
5040 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00005041 // constant which cannot collide with a overflowed signed operand,
5042 // then reinterpreting the signed operand as unsigned will not
5043 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00005044 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5045 assert(!value.isSigned() && "result of unsigned expression is signed");
5046
5047 // 2's complement: test the top bit.
5048 if (value.isNonNegative())
5049 return;
5050 }
5051 }
5052
John McCallb13c87f2009-11-05 09:23:39 +00005053 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00005054 << lex->getType() << rex->getType()
5055 << lex->getSourceRange() << rex->getSourceRange();
5056}
5057
Douglas Gregor0c6db942009-05-04 06:07:12 +00005058// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005059QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005060 unsigned OpaqueOpc, bool isRelational) {
5061 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5062
Chris Lattner02dd4b12009-12-05 05:40:13 +00005063 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005064 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005065 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005066
John McCall5dbad3d2009-11-06 08:49:08 +00005067 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5068 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005069
Chris Lattnera5937dd2007-08-26 01:18:55 +00005070 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005071 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5072 UsualArithmeticConversions(lex, rex);
5073 else {
5074 UsualUnaryConversions(lex);
5075 UsualUnaryConversions(rex);
5076 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005077 QualType lType = lex->getType();
5078 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005079
Mike Stumpaf199f32009-05-07 18:43:07 +00005080 if (!lType->isFloatingType()
5081 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005082 // For non-floating point types, check for self-comparisons of the form
5083 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5084 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005085 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005086 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005087 Expr *LHSStripped = lex->IgnoreParens();
5088 Expr *RHSStripped = rex->IgnoreParens();
5089 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5090 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005091 if (DRL->getDecl() == DRR->getDecl() &&
5092 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00005093 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00005094
Chris Lattner55660a72009-03-08 19:39:53 +00005095 if (isa<CastExpr>(LHSStripped))
5096 LHSStripped = LHSStripped->IgnoreParenCasts();
5097 if (isa<CastExpr>(RHSStripped))
5098 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005099
Chris Lattner55660a72009-03-08 19:39:53 +00005100 // Warn about comparisons against a string constant (unless the other
5101 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005102 Expr *literalString = 0;
5103 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005104 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005105 !RHSStripped->isNullPointerConstant(Context,
5106 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005107 literalString = lex;
5108 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005109 } else if ((isa<StringLiteral>(RHSStripped) ||
5110 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005111 !LHSStripped->isNullPointerConstant(Context,
5112 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005113 literalString = rex;
5114 literalStringStripped = RHSStripped;
5115 }
5116
5117 if (literalString) {
5118 std::string resultComparison;
5119 switch (Opc) {
5120 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5121 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5122 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5123 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5124 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5125 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5126 default: assert(false && "Invalid comparison operator");
5127 }
5128 Diag(Loc, diag::warn_stringcompare)
5129 << isa<ObjCEncodeExpr>(literalStringStripped)
5130 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00005131 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5132 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5133 "strcmp(")
5134 << CodeModificationHint::CreateInsertion(
5135 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00005136 resultComparison);
5137 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005138 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005139
Douglas Gregor447b69e2008-11-19 03:25:36 +00005140 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005141 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005142
Chris Lattnera5937dd2007-08-26 01:18:55 +00005143 if (isRelational) {
5144 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005145 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005146 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005147 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005148 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005149 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005150
Chris Lattnera5937dd2007-08-26 01:18:55 +00005151 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005152 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005153 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005154
Douglas Gregorce940492009-09-25 04:25:58 +00005155 bool LHSIsNull = lex->isNullPointerConstant(Context,
5156 Expr::NPC_ValueDependentIsNull);
5157 bool RHSIsNull = rex->isNullPointerConstant(Context,
5158 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005159
Chris Lattnera5937dd2007-08-26 01:18:55 +00005160 // All of the following pointer related warnings are GCC extensions, except
5161 // when handling null pointer constants. One day, we can consider making them
5162 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005163 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005164 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005165 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005166 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005167 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005168
Douglas Gregor0c6db942009-05-04 06:07:12 +00005169 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005170 if (LCanPointeeTy == RCanPointeeTy)
5171 return ResultTy;
5172
Douglas Gregor0c6db942009-05-04 06:07:12 +00005173 // C++ [expr.rel]p2:
5174 // [...] Pointer conversions (4.10) and qualification
5175 // conversions (4.4) are performed on pointer operands (or on
5176 // a pointer operand and a null pointer constant) to bring
5177 // them to their composite pointer type. [...]
5178 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005179 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005180 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005181 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005182 if (T.isNull()) {
5183 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5184 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5185 return QualType();
5186 }
5187
Eli Friedman73c39ab2009-10-20 08:27:19 +00005188 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5189 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005190 return ResultTy;
5191 }
Eli Friedman3075e762009-08-23 00:27:47 +00005192 // C99 6.5.9p2 and C99 6.5.8p2
5193 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5194 RCanPointeeTy.getUnqualifiedType())) {
5195 // Valid unless a relational comparison of function pointers
5196 if (isRelational && LCanPointeeTy->isFunctionType()) {
5197 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5198 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5199 }
5200 } else if (!isRelational &&
5201 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5202 // Valid unless comparison between non-null pointer and function pointer
5203 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5204 && !LHSIsNull && !RHSIsNull) {
5205 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5206 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5207 }
5208 } else {
5209 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005210 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005211 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005212 }
Eli Friedman3075e762009-08-23 00:27:47 +00005213 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005214 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005215 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005216 }
Mike Stump1eb44332009-09-09 15:08:12 +00005217
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005218 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005219 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005220 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005221 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005222 (lType->isPointerType() ||
5223 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005224 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005225 return ResultTy;
5226 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005227 if (LHSIsNull &&
5228 (rType->isPointerType() ||
5229 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005230 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005231 return ResultTy;
5232 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005233
5234 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005235 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005236 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5237 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005238 // In addition, pointers to members can be compared, or a pointer to
5239 // member and a null pointer constant. Pointer to member conversions
5240 // (4.11) and qualification conversions (4.4) are performed to bring
5241 // them to a common type. If one operand is a null pointer constant,
5242 // the common type is the type of the other operand. Otherwise, the
5243 // common type is a pointer to member type similar (4.4) to the type
5244 // of one of the operands, with a cv-qualification signature (4.4)
5245 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005246 // types.
5247 QualType T = FindCompositePointerType(lex, rex);
5248 if (T.isNull()) {
5249 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5250 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5251 return QualType();
5252 }
Mike Stump1eb44332009-09-09 15:08:12 +00005253
Eli Friedman73c39ab2009-10-20 08:27:19 +00005254 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5255 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005256 return ResultTy;
5257 }
Mike Stump1eb44332009-09-09 15:08:12 +00005258
Douglas Gregor20b3e992009-08-24 17:42:35 +00005259 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005260 if (lType->isNullPtrType() && rType->isNullPtrType())
5261 return ResultTy;
5262 }
Mike Stump1eb44332009-09-09 15:08:12 +00005263
Steve Naroff1c7d0672008-09-04 15:10:53 +00005264 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005265 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005266 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5267 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005268
Steve Naroff1c7d0672008-09-04 15:10:53 +00005269 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005270 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005271 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005272 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005273 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005274 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005275 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005276 }
Steve Naroff59f53942008-09-28 01:11:11 +00005277 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005278 if (!isRelational
5279 && ((lType->isBlockPointerType() && rType->isPointerType())
5280 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005281 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005282 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005283 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005284 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005285 ->getPointeeType()->isVoidType())))
5286 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5287 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005288 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005289 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005290 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005291 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005292
Steve Naroff14108da2009-07-10 23:34:53 +00005293 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005294 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005295 const PointerType *LPT = lType->getAs<PointerType>();
5296 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005297 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005298 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005299 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005300 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005301
Steve Naroffa8069f12008-11-17 19:49:16 +00005302 if (!LPtrToVoid && !RPtrToVoid &&
5303 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005304 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005305 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005306 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005307 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005308 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005309 }
Steve Naroff14108da2009-07-10 23:34:53 +00005310 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005311 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005312 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5313 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005314 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005315 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005316 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005317 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005318 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005319 unsigned DiagID = 0;
5320 if (RHSIsNull) {
5321 if (isRelational)
5322 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5323 } else if (isRelational)
5324 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5325 else
5326 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005327
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005328 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005329 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005330 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005331 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005332 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005333 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005334 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005335 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005336 unsigned DiagID = 0;
5337 if (LHSIsNull) {
5338 if (isRelational)
5339 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5340 } else if (isRelational)
5341 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5342 else
5343 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005344
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005345 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005346 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005347 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005348 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005349 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005350 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005351 }
Steve Naroff39218df2008-09-04 16:56:14 +00005352 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005353 if (!isRelational && RHSIsNull
5354 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005355 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005356 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005357 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005358 if (!isRelational && LHSIsNull
5359 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005360 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005361 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005362 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005363 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005364}
5365
Nate Begemanbe2341d2008-07-14 18:02:46 +00005366/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005367/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005368/// like a scalar comparison, a vector comparison produces a vector of integer
5369/// types.
5370QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005371 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005372 bool isRelational) {
5373 // Check to make sure we're operating on vectors of the same type and width,
5374 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005375 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005376 if (vType.isNull())
5377 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005378
Nate Begemanbe2341d2008-07-14 18:02:46 +00005379 QualType lType = lex->getType();
5380 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005381
Nate Begemanbe2341d2008-07-14 18:02:46 +00005382 // For non-floating point types, check for self-comparisons of the form
5383 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5384 // often indicate logic errors in the program.
5385 if (!lType->isFloatingType()) {
5386 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5387 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5388 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005389 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005390 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005391
Nate Begemanbe2341d2008-07-14 18:02:46 +00005392 // Check for comparisons of floating point operands using != and ==.
5393 if (!isRelational && lType->isFloatingType()) {
5394 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005395 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005396 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005397
Nate Begemanbe2341d2008-07-14 18:02:46 +00005398 // Return the type for the comparison, which is the same as vector type for
5399 // integer vectors, or an integer type of identical size and number of
5400 // elements for floating point vectors.
5401 if (lType->isIntegerType())
5402 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005403
John McCall183700f2009-09-21 23:43:11 +00005404 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005405 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005406 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005407 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005408 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005409 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5410
Mike Stumpeed9cac2009-02-19 03:04:26 +00005411 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005412 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005413 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5414}
5415
Reid Spencer5f016e22007-07-11 17:01:13 +00005416inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005417 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005418 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005419 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005420
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005421 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005422
Steve Naroffa4332e22007-07-17 00:58:39 +00005423 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005424 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005425 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005426}
5427
5428inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005429 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005430 if (!Context.getLangOptions().CPlusPlus) {
5431 UsualUnaryConversions(lex);
5432 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005433
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005434 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5435 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005436
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005437 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005438 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005439
5440 // C++ [expr.log.and]p1
5441 // C++ [expr.log.or]p1
5442 // The operands are both implicitly converted to type bool (clause 4).
5443 StandardConversionSequence LHS;
5444 if (!IsStandardConversion(lex, Context.BoolTy,
5445 /*InOverloadResolution=*/false, LHS))
5446 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005447
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005448 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005449 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005450 return InvalidOperands(Loc, lex, rex);
5451
5452 StandardConversionSequence RHS;
5453 if (!IsStandardConversion(rex, Context.BoolTy,
5454 /*InOverloadResolution=*/false, RHS))
5455 return InvalidOperands(Loc, lex, rex);
5456
5457 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005458 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005459 return InvalidOperands(Loc, lex, rex);
5460
5461 // C++ [expr.log.and]p2
5462 // C++ [expr.log.or]p2
5463 // The result is a bool.
5464 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005465}
5466
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005467/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5468/// is a read-only property; return true if so. A readonly property expression
5469/// depends on various declarations and thus must be treated specially.
5470///
Mike Stump1eb44332009-09-09 15:08:12 +00005471static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005472 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5473 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5474 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5475 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005476 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005477 BaseType->getAsObjCInterfacePointerType())
5478 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5479 if (S.isPropertyReadonly(PDecl, IFace))
5480 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005481 }
5482 }
5483 return false;
5484}
5485
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005486/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5487/// emit an error and return true. If so, return false.
5488static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005489 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005490 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005491 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005492 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5493 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005494 if (IsLV == Expr::MLV_Valid)
5495 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005496
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005497 unsigned Diag = 0;
5498 bool NeedType = false;
5499 switch (IsLV) { // C99 6.5.16p2
5500 default: assert(0 && "Unknown result from isModifiableLvalue!");
5501 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005502 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005503 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5504 NeedType = true;
5505 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005506 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005507 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5508 NeedType = true;
5509 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005510 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005511 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5512 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005513 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005514 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5515 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005516 case Expr::MLV_IncompleteType:
5517 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005518 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005519 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5520 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005521 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005522 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5523 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005524 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005525 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5526 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005527 case Expr::MLV_ReadonlyProperty:
5528 Diag = diag::error_readonly_property_assignment;
5529 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005530 case Expr::MLV_NoSetterProperty:
5531 Diag = diag::error_nosetter_property_assignment;
5532 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005533 case Expr::MLV_SubObjCPropertySetting:
5534 Diag = diag::error_no_subobject_property_setting;
5535 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005536 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005537
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005538 SourceRange Assign;
5539 if (Loc != OrigLoc)
5540 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005541 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005542 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005543 else
Mike Stump1eb44332009-09-09 15:08:12 +00005544 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005545 return true;
5546}
5547
5548
5549
5550// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005551QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5552 SourceLocation Loc,
5553 QualType CompoundType) {
5554 // Verify that LHS is a modifiable lvalue, and emit error if not.
5555 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005556 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005557
5558 QualType LHSType = LHS->getType();
5559 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005560
Chris Lattner5cf216b2008-01-04 18:04:52 +00005561 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005562 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005563 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005564 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005565 // Special case of NSObject attributes on c-style pointer types.
5566 if (ConvTy == IncompatiblePointer &&
5567 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005568 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005569 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005570 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005571 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005572
Chris Lattner2c156472008-08-21 18:04:13 +00005573 // If the RHS is a unary plus or minus, check to see if they = and + are
5574 // right next to each other. If so, the user may have typo'd "x =+ 4"
5575 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005576 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005577 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5578 RHSCheck = ICE->getSubExpr();
5579 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5580 if ((UO->getOpcode() == UnaryOperator::Plus ||
5581 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005582 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005583 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005584 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5585 // And there is a space or other character before the subexpr of the
5586 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005587 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5588 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005589 Diag(Loc, diag::warn_not_compound_assign)
5590 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5591 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005592 }
Chris Lattner2c156472008-08-21 18:04:13 +00005593 }
5594 } else {
5595 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005596 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005597 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005598
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005599 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005600 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005601 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005602
Reid Spencer5f016e22007-07-11 17:01:13 +00005603 // C99 6.5.16p3: The type of an assignment expression is the type of the
5604 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005605 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005606 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5607 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005608 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005609 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005610 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005611}
5612
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005613// C99 6.5.17
5614QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005615 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005616 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005617
5618 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5619 // incomplete in C++).
5620
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005621 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005622}
5623
Steve Naroff49b45262007-07-13 16:58:59 +00005624/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5625/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005626QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5627 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005628 if (Op->isTypeDependent())
5629 return Context.DependentTy;
5630
Chris Lattner3528d352008-11-21 07:05:48 +00005631 QualType ResType = Op->getType();
5632 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005633
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005634 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5635 // Decrement of bool is not allowed.
5636 if (!isInc) {
5637 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5638 return QualType();
5639 }
5640 // Increment of bool sets it to true, but is deprecated.
5641 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5642 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005643 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005644 } else if (ResType->isAnyPointerType()) {
5645 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005646
Chris Lattner3528d352008-11-21 07:05:48 +00005647 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005648 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005649 if (getLangOptions().CPlusPlus) {
5650 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5651 << Op->getSourceRange();
5652 return QualType();
5653 }
5654
5655 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005656 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005657 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005658 if (getLangOptions().CPlusPlus) {
5659 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5660 << Op->getType() << Op->getSourceRange();
5661 return QualType();
5662 }
5663
5664 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005665 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005666 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005667 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005668 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005669 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005670 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005671 // Diagnose bad cases where we step over interface counts.
5672 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5673 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5674 << PointeeTy << Op->getSourceRange();
5675 return QualType();
5676 }
Chris Lattner3528d352008-11-21 07:05:48 +00005677 } else if (ResType->isComplexType()) {
5678 // C99 does not support ++/-- on complex types, we allow as an extension.
5679 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005680 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005681 } else {
5682 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00005683 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005684 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005685 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005686 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005687 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005688 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005689 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005690 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005691}
5692
Anders Carlsson369dee42008-02-01 07:15:58 +00005693/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005694/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005695/// where the declaration is needed for type checking. We only need to
5696/// handle cases when the expression references a function designator
5697/// or is an lvalue. Here are some examples:
5698/// - &(x) => x
5699/// - &*****f => f for f a function designator.
5700/// - &s.xx => s
5701/// - &s.zz[1].yy -> s, if zz is an array
5702/// - *(x + 1) -> x, if x is an array
5703/// - &"123"[2] -> 0
5704/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005705static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005706 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005707 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005708 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005709 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005710 // If this is an arrow operator, the address is an offset from
5711 // the base's value, so the object the base refers to is
5712 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005713 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005714 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005715 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005716 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005717 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005718 // FIXME: This code shouldn't be necessary! We should catch the implicit
5719 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005720 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5721 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5722 if (ICE->getSubExpr()->getType()->isArrayType())
5723 return getPrimaryDecl(ICE->getSubExpr());
5724 }
5725 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005726 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005727 case Stmt::UnaryOperatorClass: {
5728 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005729
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005730 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005731 case UnaryOperator::Real:
5732 case UnaryOperator::Imag:
5733 case UnaryOperator::Extension:
5734 return getPrimaryDecl(UO->getSubExpr());
5735 default:
5736 return 0;
5737 }
5738 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005739 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005740 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005741 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005742 // If the result of an implicit cast is an l-value, we care about
5743 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005744 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005745 default:
5746 return 0;
5747 }
5748}
5749
5750/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005751/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005752/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005753/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005754/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005755/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005756/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005757QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005758 // Make sure to ignore parentheses in subsequent checks
5759 op = op->IgnoreParens();
5760
Douglas Gregor9103bb22008-12-17 22:52:20 +00005761 if (op->isTypeDependent())
5762 return Context.DependentTy;
5763
Steve Naroff08f19672008-01-13 17:10:08 +00005764 if (getLangOptions().C99) {
5765 // Implement C99-only parts of addressof rules.
5766 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5767 if (uOp->getOpcode() == UnaryOperator::Deref)
5768 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5769 // (assuming the deref expression is valid).
5770 return uOp->getSubExpr()->getType();
5771 }
5772 // Technically, there should be a check for array subscript
5773 // expressions here, but the result of one is always an lvalue anyway.
5774 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005775 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005776 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005777
Eli Friedman441cf102009-05-16 23:27:50 +00005778 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5779 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005780 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005781 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005782 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005783 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5784 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005785 return QualType();
5786 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005787 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005788 // The operand cannot be a bit-field
5789 Diag(OpLoc, diag::err_typecheck_address_of)
5790 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005791 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005792 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5793 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005794 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005795 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005796 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005797 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005798 } else if (isa<ObjCPropertyRefExpr>(op)) {
5799 // cannot take address of a property expression.
5800 Diag(OpLoc, diag::err_typecheck_address_of)
5801 << "property expression" << op->getSourceRange();
5802 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005803 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5804 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005805 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5806 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005807 } else if (isa<UnresolvedLookupExpr>(op)) {
5808 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005809 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005810 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005811 // with the register storage-class specifier.
5812 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5813 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005814 Diag(OpLoc, diag::err_typecheck_address_of)
5815 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005816 return QualType();
5817 }
John McCallba135432009-11-21 08:51:07 +00005818 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005819 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005820 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005821 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005822 // Could be a pointer to member, though, if there is an explicit
5823 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005824 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005825 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005826 if (Ctx && Ctx->isRecord()) {
5827 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005828 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005829 diag::err_cannot_form_pointer_to_member_of_reference_type)
5830 << FD->getDeclName() << FD->getType();
5831 return QualType();
5832 }
Mike Stump1eb44332009-09-09 15:08:12 +00005833
Sebastian Redlebc07d52009-02-03 20:19:35 +00005834 return Context.getMemberPointerType(op->getType(),
5835 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005836 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005837 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005838 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005839 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005840 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005841 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5842 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005843 return Context.getMemberPointerType(op->getType(),
5844 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5845 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005846 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005847 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005848
Eli Friedman441cf102009-05-16 23:27:50 +00005849 if (lval == Expr::LV_IncompleteVoidType) {
5850 // Taking the address of a void variable is technically illegal, but we
5851 // allow it in cases which are otherwise valid.
5852 // Example: "extern void x; void* y = &x;".
5853 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5854 }
5855
Reid Spencer5f016e22007-07-11 17:01:13 +00005856 // If the operand has type "type", the result has type "pointer to type".
5857 return Context.getPointerType(op->getType());
5858}
5859
Chris Lattner22caddc2008-11-23 09:13:29 +00005860QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005861 if (Op->isTypeDependent())
5862 return Context.DependentTy;
5863
Chris Lattner22caddc2008-11-23 09:13:29 +00005864 UsualUnaryConversions(Op);
5865 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005866
Chris Lattner22caddc2008-11-23 09:13:29 +00005867 // Note that per both C89 and C99, this is always legal, even if ptype is an
5868 // incomplete type or void. It would be possible to warn about dereferencing
5869 // a void pointer, but it's completely well-defined, and such a warning is
5870 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005871 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005872 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005873
John McCall183700f2009-09-21 23:43:11 +00005874 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005875 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005876
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005877 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005878 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005879 return QualType();
5880}
5881
5882static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5883 tok::TokenKind Kind) {
5884 BinaryOperator::Opcode Opc;
5885 switch (Kind) {
5886 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005887 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5888 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005889 case tok::star: Opc = BinaryOperator::Mul; break;
5890 case tok::slash: Opc = BinaryOperator::Div; break;
5891 case tok::percent: Opc = BinaryOperator::Rem; break;
5892 case tok::plus: Opc = BinaryOperator::Add; break;
5893 case tok::minus: Opc = BinaryOperator::Sub; break;
5894 case tok::lessless: Opc = BinaryOperator::Shl; break;
5895 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5896 case tok::lessequal: Opc = BinaryOperator::LE; break;
5897 case tok::less: Opc = BinaryOperator::LT; break;
5898 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5899 case tok::greater: Opc = BinaryOperator::GT; break;
5900 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5901 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5902 case tok::amp: Opc = BinaryOperator::And; break;
5903 case tok::caret: Opc = BinaryOperator::Xor; break;
5904 case tok::pipe: Opc = BinaryOperator::Or; break;
5905 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5906 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5907 case tok::equal: Opc = BinaryOperator::Assign; break;
5908 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5909 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5910 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5911 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5912 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5913 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5914 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5915 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5916 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5917 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5918 case tok::comma: Opc = BinaryOperator::Comma; break;
5919 }
5920 return Opc;
5921}
5922
5923static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5924 tok::TokenKind Kind) {
5925 UnaryOperator::Opcode Opc;
5926 switch (Kind) {
5927 default: assert(0 && "Unknown unary op!");
5928 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5929 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5930 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5931 case tok::star: Opc = UnaryOperator::Deref; break;
5932 case tok::plus: Opc = UnaryOperator::Plus; break;
5933 case tok::minus: Opc = UnaryOperator::Minus; break;
5934 case tok::tilde: Opc = UnaryOperator::Not; break;
5935 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005936 case tok::kw___real: Opc = UnaryOperator::Real; break;
5937 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5938 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5939 }
5940 return Opc;
5941}
5942
Douglas Gregoreaebc752008-11-06 23:29:22 +00005943/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5944/// operator @p Opc at location @c TokLoc. This routine only supports
5945/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005946Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5947 unsigned Op,
5948 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005949 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005950 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005951 // The following two variables are used for compound assignment operators
5952 QualType CompLHSTy; // Type of LHS after promotions for computation
5953 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005954
5955 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005956 case BinaryOperator::Assign:
5957 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5958 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005959 case BinaryOperator::PtrMemD:
5960 case BinaryOperator::PtrMemI:
5961 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5962 Opc == BinaryOperator::PtrMemI);
5963 break;
5964 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005965 case BinaryOperator::Div:
5966 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5967 break;
5968 case BinaryOperator::Rem:
5969 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5970 break;
5971 case BinaryOperator::Add:
5972 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5973 break;
5974 case BinaryOperator::Sub:
5975 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5976 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005977 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005978 case BinaryOperator::Shr:
5979 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5980 break;
5981 case BinaryOperator::LE:
5982 case BinaryOperator::LT:
5983 case BinaryOperator::GE:
5984 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005985 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005986 break;
5987 case BinaryOperator::EQ:
5988 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005989 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005990 break;
5991 case BinaryOperator::And:
5992 case BinaryOperator::Xor:
5993 case BinaryOperator::Or:
5994 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5995 break;
5996 case BinaryOperator::LAnd:
5997 case BinaryOperator::LOr:
5998 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5999 break;
6000 case BinaryOperator::MulAssign:
6001 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006002 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6003 CompLHSTy = CompResultTy;
6004 if (!CompResultTy.isNull())
6005 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006006 break;
6007 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006008 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6009 CompLHSTy = CompResultTy;
6010 if (!CompResultTy.isNull())
6011 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006012 break;
6013 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006014 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6015 if (!CompResultTy.isNull())
6016 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006017 break;
6018 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006019 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6020 if (!CompResultTy.isNull())
6021 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006022 break;
6023 case BinaryOperator::ShlAssign:
6024 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006025 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6026 CompLHSTy = CompResultTy;
6027 if (!CompResultTy.isNull())
6028 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006029 break;
6030 case BinaryOperator::AndAssign:
6031 case BinaryOperator::XorAssign:
6032 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006033 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6034 CompLHSTy = CompResultTy;
6035 if (!CompResultTy.isNull())
6036 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006037 break;
6038 case BinaryOperator::Comma:
6039 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6040 break;
6041 }
6042 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006043 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006044 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006045 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6046 else
6047 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006048 CompLHSTy, CompResultTy,
6049 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006050}
6051
Sebastian Redlaee3c932009-10-27 12:10:02 +00006052/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6053/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006054static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6055 const PartialDiagnostic &PD,
6056 SourceRange ParenRange)
6057{
6058 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6059 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6060 // We can't display the parentheses, so just dig the
6061 // warning/error and return.
6062 Self.Diag(Loc, PD);
6063 return;
6064 }
6065
6066 Self.Diag(Loc, PD)
6067 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6068 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6069}
6070
Sebastian Redlaee3c932009-10-27 12:10:02 +00006071/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6072/// operators are mixed in a way that suggests that the programmer forgot that
6073/// comparison operators have higher precedence. The most typical example of
6074/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006075static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6076 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006077 typedef BinaryOperator BinOp;
6078 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6079 rhsopc = static_cast<BinOp::Opcode>(-1);
6080 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006081 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006082 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006083 rhsopc = BO->getOpcode();
6084
6085 // Subs are not binary operators.
6086 if (lhsopc == -1 && rhsopc == -1)
6087 return;
6088
6089 // Bitwise operations are sometimes used as eager logical ops.
6090 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006091 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6092 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006093 return;
6094
Sebastian Redlaee3c932009-10-27 12:10:02 +00006095 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006096 SuggestParentheses(Self, OpLoc,
6097 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006098 << SourceRange(lhs->getLocStart(), OpLoc)
6099 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6100 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6101 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006102 SuggestParentheses(Self, OpLoc,
6103 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006104 << SourceRange(OpLoc, rhs->getLocEnd())
6105 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6106 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006107}
6108
6109/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6110/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6111/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6112static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6113 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006114 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006115 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6116}
6117
Reid Spencer5f016e22007-07-11 17:01:13 +00006118// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006119Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6120 tok::TokenKind Kind,
6121 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006122 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006123 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006124
Steve Narofff69936d2007-09-16 03:34:24 +00006125 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6126 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006127
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006128 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6129 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6130
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006131 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6132}
6133
6134Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6135 BinaryOperator::Opcode Opc,
6136 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006137 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006138 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006139 rhs->getType()->isOverloadableType())) {
6140 // Find all of the overloaded operators visible from this
6141 // point. We perform both an operator-name lookup from the local
6142 // scope and an argument-dependent lookup based on the types of
6143 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006144 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006145 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6146 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006147 if (S)
6148 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6149 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006150 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006151 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006152 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006153 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006154 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006155
Douglas Gregor063daf62009-03-13 18:40:31 +00006156 // Build the (potentially-overloaded, potentially-dependent)
6157 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006158 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006159 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006160
Douglas Gregoreaebc752008-11-06 23:29:22 +00006161 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006162 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006163}
6164
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006165Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006166 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006167 ExprArg InputArg) {
6168 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006169
Mike Stump390b4cc2009-05-16 07:39:55 +00006170 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006171 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006172 QualType resultType;
6173 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006174 case UnaryOperator::OffsetOf:
6175 assert(false && "Invalid unary operator");
6176 break;
6177
Reid Spencer5f016e22007-07-11 17:01:13 +00006178 case UnaryOperator::PreInc:
6179 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006180 case UnaryOperator::PostInc:
6181 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006182 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006183 Opc == UnaryOperator::PreInc ||
6184 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006185 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006186 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006187 resultType = CheckAddressOfOperand(Input, OpLoc);
6188 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006189 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006190 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006191 resultType = CheckIndirectionOperand(Input, OpLoc);
6192 break;
6193 case UnaryOperator::Plus:
6194 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006195 UsualUnaryConversions(Input);
6196 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006197 if (resultType->isDependentType())
6198 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006199 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6200 break;
6201 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6202 resultType->isEnumeralType())
6203 break;
6204 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6205 Opc == UnaryOperator::Plus &&
6206 resultType->isPointerType())
6207 break;
6208
Sebastian Redl0eb23302009-01-19 00:08:26 +00006209 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6210 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006211 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006212 UsualUnaryConversions(Input);
6213 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006214 if (resultType->isDependentType())
6215 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006216 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6217 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6218 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006219 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006220 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006221 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006222 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6223 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006224 break;
6225 case UnaryOperator::LNot: // logical negation
6226 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006227 DefaultFunctionArrayConversion(Input);
6228 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006229 if (resultType->isDependentType())
6230 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006231 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006232 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6233 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006234 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006235 // In C++, it's bool. C++ 5.3.1p8
6236 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006237 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006238 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006239 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006240 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006241 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006242 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006243 resultType = Input->getType();
6244 break;
6245 }
6246 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006247 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006248
6249 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006250 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006251}
6252
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006253Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6254 UnaryOperator::Opcode Opc,
6255 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006256 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006257 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6258 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006259 // Find all of the overloaded operators visible from this
6260 // point. We perform both an operator-name lookup from the local
6261 // scope and an argument-dependent lookup based on the types of
6262 // the arguments.
6263 FunctionSet Functions;
6264 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6265 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006266 if (S)
6267 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6268 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006269 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006270 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006271 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006272 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006273
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006274 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6275 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006276
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006277 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6278}
6279
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006280// Unary Operators. 'Tok' is the token for the operator.
6281Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6282 tok::TokenKind Op, ExprArg input) {
6283 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6284}
6285
Steve Naroff1b273c42007-09-16 14:56:35 +00006286/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006287Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6288 SourceLocation LabLoc,
6289 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006290 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006291 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006292
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006293 // If we haven't seen this label yet, create a forward reference. It
6294 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006295 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006296 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006297
Reid Spencer5f016e22007-07-11 17:01:13 +00006298 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006299 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6300 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006301}
6302
Sebastian Redlf53597f2009-03-15 17:47:39 +00006303Sema::OwningExprResult
6304Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6305 SourceLocation RPLoc) { // "({..})"
6306 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006307 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6308 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6309
Eli Friedmandca2b732009-01-24 23:09:00 +00006310 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006311 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006312 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006313
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006314 // FIXME: there are a variety of strange constraints to enforce here, for
6315 // example, it is not possible to goto into a stmt expression apparently.
6316 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006317
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006318 // If there are sub stmts in the compound stmt, take the type of the last one
6319 // as the type of the stmtexpr.
6320 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006321
Chris Lattner611b2ec2008-07-26 19:51:01 +00006322 if (!Compound->body_empty()) {
6323 Stmt *LastStmt = Compound->body_back();
6324 // If LastStmt is a label, skip down through into the body.
6325 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6326 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006327
Chris Lattner611b2ec2008-07-26 19:51:01 +00006328 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006329 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006330 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006331
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006332 // FIXME: Check that expression type is complete/non-abstract; statement
6333 // expressions are not lvalues.
6334
Sebastian Redlf53597f2009-03-15 17:47:39 +00006335 substmt.release();
6336 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006337}
Steve Naroffd34e9152007-08-01 22:05:33 +00006338
Sebastian Redlf53597f2009-03-15 17:47:39 +00006339Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6340 SourceLocation BuiltinLoc,
6341 SourceLocation TypeLoc,
6342 TypeTy *argty,
6343 OffsetOfComponent *CompPtr,
6344 unsigned NumComponents,
6345 SourceLocation RPLoc) {
6346 // FIXME: This function leaks all expressions in the offset components on
6347 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006348 // FIXME: Preserve type source info.
6349 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006350 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006351
Sebastian Redl28507842009-02-26 14:39:58 +00006352 bool Dependent = ArgTy->isDependentType();
6353
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006354 // We must have at least one component that refers to the type, and the first
6355 // one is known to be a field designator. Verify that the ArgTy represents
6356 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006357 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006358 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006359
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006360 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6361 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006362
Eli Friedman35183ac2009-02-27 06:44:11 +00006363 // Otherwise, create a null pointer as the base, and iteratively process
6364 // the offsetof designators.
6365 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6366 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006367 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006368 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006369
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006370 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6371 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006372 // FIXME: This diagnostic isn't actually visible because the location is in
6373 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006374 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006375 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6376 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006377
Sebastian Redl28507842009-02-26 14:39:58 +00006378 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006379 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006380
John McCalld00f2002009-11-04 03:03:43 +00006381 if (RequireCompleteType(TypeLoc, Res->getType(),
6382 diag::err_offsetof_incomplete_type))
6383 return ExprError();
6384
Sebastian Redl28507842009-02-26 14:39:58 +00006385 // FIXME: Dependent case loses a lot of information here. And probably
6386 // leaks like a sieve.
6387 for (unsigned i = 0; i != NumComponents; ++i) {
6388 const OffsetOfComponent &OC = CompPtr[i];
6389 if (OC.isBrackets) {
6390 // Offset of an array sub-field. TODO: Should we allow vector elements?
6391 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6392 if (!AT) {
6393 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006394 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6395 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006396 }
6397
6398 // FIXME: C++: Verify that operator[] isn't overloaded.
6399
Eli Friedman35183ac2009-02-27 06:44:11 +00006400 // Promote the array so it looks more like a normal array subscript
6401 // expression.
6402 DefaultFunctionArrayConversion(Res);
6403
Sebastian Redl28507842009-02-26 14:39:58 +00006404 // C99 6.5.2.1p1
6405 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006406 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006407 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006408 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006409 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006410 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006411
6412 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6413 OC.LocEnd);
6414 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006415 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006416
Ted Kremenek6217b802009-07-29 21:53:49 +00006417 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006418 if (!RC) {
6419 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006420 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6421 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006422 }
Chris Lattner704fe352007-08-30 17:59:59 +00006423
Sebastian Redl28507842009-02-26 14:39:58 +00006424 // Get the decl corresponding to this.
6425 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006426 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006427 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Douglas Gregor75b699a2009-12-12 07:25:49 +00006428 switch (ExprEvalContexts.back().Context ) {
6429 case Unevaluated:
6430 // The argument will never be evaluated, so don't complain.
6431 break;
6432
6433 case PotentiallyEvaluated:
6434 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6435 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6436 << Res->getType());
6437 DidWarnAboutNonPOD = true;
6438 break;
6439
6440 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +00006441 ExprEvalContexts.back().addDiagnostic(BuiltinLoc,
6442 PDiag(diag::warn_offsetof_non_pod_type)
6443 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6444 << Res->getType());
Douglas Gregor75b699a2009-12-12 07:25:49 +00006445 DidWarnAboutNonPOD = true;
6446 break;
6447 }
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006448 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006449 }
Mike Stump1eb44332009-09-09 15:08:12 +00006450
John McCalla24dc2e2009-11-17 02:14:36 +00006451 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6452 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006453
John McCall1bcee0a2009-12-02 08:25:40 +00006454 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006455 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006456 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006457 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6458 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006459
Sebastian Redl28507842009-02-26 14:39:58 +00006460 // FIXME: C++: Verify that MemberDecl isn't a static field.
6461 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006462 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006463 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006464 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006465 } else {
Eli Friedman16c53782009-12-04 07:18:51 +00006466 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006467 // MemberDecl->getType() doesn't get the right qualifiers, but it
6468 // doesn't matter here.
6469 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6470 MemberDecl->getType().getNonReferenceType());
6471 }
Sebastian Redl28507842009-02-26 14:39:58 +00006472 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006473 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006474
Sebastian Redlf53597f2009-03-15 17:47:39 +00006475 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6476 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006477}
6478
6479
Sebastian Redlf53597f2009-03-15 17:47:39 +00006480Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6481 TypeTy *arg1,TypeTy *arg2,
6482 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006483 // FIXME: Preserve type source info.
6484 QualType argT1 = GetTypeFromParser(arg1);
6485 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006486
Steve Naroffd34e9152007-08-01 22:05:33 +00006487 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006488
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006489 if (getLangOptions().CPlusPlus) {
6490 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6491 << SourceRange(BuiltinLoc, RPLoc);
6492 return ExprError();
6493 }
6494
Sebastian Redlf53597f2009-03-15 17:47:39 +00006495 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6496 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006497}
6498
Sebastian Redlf53597f2009-03-15 17:47:39 +00006499Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6500 ExprArg cond,
6501 ExprArg expr1, ExprArg expr2,
6502 SourceLocation RPLoc) {
6503 Expr *CondExpr = static_cast<Expr*>(cond.get());
6504 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6505 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006506
Steve Naroffd04fdd52007-08-03 21:21:27 +00006507 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6508
Sebastian Redl28507842009-02-26 14:39:58 +00006509 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006510 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006511 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006512 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006513 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006514 } else {
6515 // The conditional expression is required to be a constant expression.
6516 llvm::APSInt condEval(32);
6517 SourceLocation ExpLoc;
6518 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006519 return ExprError(Diag(ExpLoc,
6520 diag::err_typecheck_choose_expr_requires_constant)
6521 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006522
Sebastian Redl28507842009-02-26 14:39:58 +00006523 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6524 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006525 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6526 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006527 }
6528
Sebastian Redlf53597f2009-03-15 17:47:39 +00006529 cond.release(); expr1.release(); expr2.release();
6530 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006531 resType, RPLoc,
6532 resType->isDependentType(),
6533 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006534}
6535
Steve Naroff4eb206b2008-09-03 18:15:37 +00006536//===----------------------------------------------------------------------===//
6537// Clang Extensions.
6538//===----------------------------------------------------------------------===//
6539
6540/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006541void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006542 // Analyze block parameters.
6543 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006544
Steve Naroff4eb206b2008-09-03 18:15:37 +00006545 // Add BSI to CurBlock.
6546 BSI->PrevBlockInfo = CurBlock;
6547 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006548
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006549 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006550 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006551 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006552 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006553 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6554 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006555
Steve Naroff090276f2008-10-10 01:28:17 +00006556 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek3cdff232009-12-07 22:01:30 +00006557 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor44b43212008-12-11 16:49:14 +00006558 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006559}
6560
Mike Stump98eb8a72009-02-04 22:31:32 +00006561void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006562 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006563
6564 if (ParamInfo.getNumTypeObjects() == 0
6565 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006566 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006567 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6568
Mike Stump4eeab842009-04-28 01:10:27 +00006569 if (T->isArrayType()) {
6570 Diag(ParamInfo.getSourceRange().getBegin(),
6571 diag::err_block_returns_array);
6572 return;
6573 }
6574
Mike Stump98eb8a72009-02-04 22:31:32 +00006575 // The parameter list is optional, if there was none, assume ().
6576 if (!T->isFunctionType())
6577 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6578
6579 CurBlock->hasPrototype = true;
6580 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006581 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006582 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006583 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006584 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006585 // FIXME: remove the attribute.
6586 }
John McCall183700f2009-09-21 23:43:11 +00006587 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006588
Chris Lattner9097af12009-04-11 19:27:54 +00006589 // Do not allow returning a objc interface by-value.
6590 if (RetTy->isObjCInterfaceType()) {
6591 Diag(ParamInfo.getSourceRange().getBegin(),
6592 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6593 return;
6594 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006595 return;
6596 }
6597
Steve Naroff4eb206b2008-09-03 18:15:37 +00006598 // Analyze arguments to block.
6599 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6600 "Not a function declarator!");
6601 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006602
Steve Naroff090276f2008-10-10 01:28:17 +00006603 CurBlock->hasPrototype = FTI.hasPrototype;
6604 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006605
Steve Naroff4eb206b2008-09-03 18:15:37 +00006606 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6607 // no arguments, not a function that takes a single void argument.
6608 if (FTI.hasPrototype &&
6609 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006610 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6611 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006612 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006613 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006614 } else if (FTI.hasPrototype) {
6615 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006616 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006617 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006618 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006619 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006620 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006621 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006622 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006623 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6624 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6625 // If this has an identifier, add it to the scope stack.
6626 if ((*AI)->getIdentifier())
6627 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006628
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006629 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006630 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006631 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006632 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006633 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006634 // FIXME: remove the attribute.
6635 }
Mike Stump1eb44332009-09-09 15:08:12 +00006636
Chris Lattner9097af12009-04-11 19:27:54 +00006637 // Analyze the return type.
6638 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006639 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006640
Chris Lattner9097af12009-04-11 19:27:54 +00006641 // Do not allow returning a objc interface by-value.
6642 if (RetTy->isObjCInterfaceType()) {
6643 Diag(ParamInfo.getSourceRange().getBegin(),
6644 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6645 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006646 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006647}
6648
6649/// ActOnBlockError - If there is an error parsing a block, this callback
6650/// is invoked to pop the information about the block from the action impl.
6651void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6652 // Ensure that CurBlock is deleted.
6653 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006654
Chris Lattner17a78302009-04-19 05:28:12 +00006655 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6656
Steve Naroff4eb206b2008-09-03 18:15:37 +00006657 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006658 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006659 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006660 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006661}
6662
6663/// ActOnBlockStmtExpr - This is called when the body of a block statement
6664/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006665Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6666 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006667 // If blocks are disabled, emit an error.
6668 if (!LangOpts.Blocks)
6669 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006670
Steve Naroff4eb206b2008-09-03 18:15:37 +00006671 // Ensure that CurBlock is deleted.
6672 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006673
Steve Naroff090276f2008-10-10 01:28:17 +00006674 PopDeclContext();
6675
Steve Naroff4eb206b2008-09-03 18:15:37 +00006676 // Pop off CurBlock, handle nested blocks.
6677 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006678
Steve Naroff4eb206b2008-09-03 18:15:37 +00006679 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006680 if (!BSI->ReturnType.isNull())
6681 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006682
Steve Naroff4eb206b2008-09-03 18:15:37 +00006683 llvm::SmallVector<QualType, 8> ArgTypes;
6684 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6685 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006686
Mike Stump56925862009-07-28 22:04:01 +00006687 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006688 QualType BlockTy;
6689 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006690 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6691 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006692 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006693 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006694 BSI->isVariadic, 0, false, false, 0, 0,
6695 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006696
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006697 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006698 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006699 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006700
Chris Lattner17a78302009-04-19 05:28:12 +00006701 // If needed, diagnose invalid gotos and switches in the block.
6702 if (CurFunctionNeedsScopeChecking)
6703 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6704 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006705
Anders Carlssone9146f22009-05-01 19:49:17 +00006706 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006707 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006708 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6709 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006710}
6711
Sebastian Redlf53597f2009-03-15 17:47:39 +00006712Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6713 ExprArg expr, TypeTy *type,
6714 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006715 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006716 Expr *E = static_cast<Expr*>(expr.get());
6717 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006718
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006719 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006720
6721 // Get the va_list type
6722 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006723 if (VaListType->isArrayType()) {
6724 // Deal with implicit array decay; for example, on x86-64,
6725 // va_list is an array, but it's supposed to decay to
6726 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006727 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006728 // Make sure the input expression also decays appropriately.
6729 UsualUnaryConversions(E);
6730 } else {
6731 // Otherwise, the va_list argument must be an l-value because
6732 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006733 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006734 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006735 return ExprError();
6736 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006737
Douglas Gregordd027302009-05-19 23:10:31 +00006738 if (!E->isTypeDependent() &&
6739 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006740 return ExprError(Diag(E->getLocStart(),
6741 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006742 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006743 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006744
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006745 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006746 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006747
Sebastian Redlf53597f2009-03-15 17:47:39 +00006748 expr.release();
6749 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6750 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006751}
6752
Sebastian Redlf53597f2009-03-15 17:47:39 +00006753Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006754 // The type of __null will be int or long, depending on the size of
6755 // pointers on the target.
6756 QualType Ty;
6757 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6758 Ty = Context.IntTy;
6759 else
6760 Ty = Context.LongTy;
6761
Sebastian Redlf53597f2009-03-15 17:47:39 +00006762 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006763}
6764
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006765static void
6766MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6767 QualType DstType,
6768 Expr *SrcExpr,
6769 CodeModificationHint &Hint) {
6770 if (!SemaRef.getLangOptions().ObjC1)
6771 return;
6772
6773 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6774 if (!PT)
6775 return;
6776
6777 // Check if the destination is of type 'id'.
6778 if (!PT->isObjCIdType()) {
6779 // Check if the destination is the 'NSString' interface.
6780 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6781 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6782 return;
6783 }
6784
6785 // Strip off any parens and casts.
6786 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6787 if (!SL || SL->isWide())
6788 return;
6789
6790 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6791}
6792
Chris Lattner5cf216b2008-01-04 18:04:52 +00006793bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6794 SourceLocation Loc,
6795 QualType DstType, QualType SrcType,
Douglas Gregor68647482009-12-16 03:45:30 +00006796 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00006797 // Decode the result (notice that AST's are still created for extensions).
6798 bool isInvalid = false;
6799 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006800 CodeModificationHint Hint;
6801
Chris Lattner5cf216b2008-01-04 18:04:52 +00006802 switch (ConvTy) {
6803 default: assert(0 && "Unknown conversion type");
6804 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006805 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006806 DiagKind = diag::ext_typecheck_convert_pointer_int;
6807 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006808 case IntToPointer:
6809 DiagKind = diag::ext_typecheck_convert_int_pointer;
6810 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006811 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006812 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006813 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6814 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006815 case IncompatiblePointerSign:
6816 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6817 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006818 case FunctionVoidPointer:
6819 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6820 break;
6821 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006822 // If the qualifiers lost were because we were applying the
6823 // (deprecated) C++ conversion from a string literal to a char*
6824 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6825 // Ideally, this check would be performed in
6826 // CheckPointerTypesForAssignment. However, that would require a
6827 // bit of refactoring (so that the second argument is an
6828 // expression, rather than a type), which should be done as part
6829 // of a larger effort to fix CheckPointerTypesForAssignment for
6830 // C++ semantics.
6831 if (getLangOptions().CPlusPlus &&
6832 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6833 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006834 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6835 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006836 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006837 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006838 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006839 case IntToBlockPointer:
6840 DiagKind = diag::err_int_to_block_pointer;
6841 break;
6842 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006843 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006844 break;
Steve Naroff39579072008-10-14 22:18:38 +00006845 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006846 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006847 // it can give a more specific diagnostic.
6848 DiagKind = diag::warn_incompatible_qualified_id;
6849 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006850 case IncompatibleVectors:
6851 DiagKind = diag::warn_incompatible_vectors;
6852 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006853 case Incompatible:
6854 DiagKind = diag::err_typecheck_convert_incompatible;
6855 isInvalid = true;
6856 break;
6857 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006858
Douglas Gregor68647482009-12-16 03:45:30 +00006859 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006860 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006861 return isInvalid;
6862}
Anders Carlssone21555e2008-11-30 19:50:32 +00006863
Chris Lattner3bf68932009-04-25 21:59:05 +00006864bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006865 llvm::APSInt ICEResult;
6866 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6867 if (Result)
6868 *Result = ICEResult;
6869 return false;
6870 }
6871
Anders Carlssone21555e2008-11-30 19:50:32 +00006872 Expr::EvalResult EvalResult;
6873
Mike Stumpeed9cac2009-02-19 03:04:26 +00006874 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006875 EvalResult.HasSideEffects) {
6876 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6877
6878 if (EvalResult.Diag) {
6879 // We only show the note if it's not the usual "invalid subexpression"
6880 // or if it's actually in a subexpression.
6881 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6882 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6883 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6884 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006885
Anders Carlssone21555e2008-11-30 19:50:32 +00006886 return true;
6887 }
6888
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006889 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6890 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006891
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006892 if (EvalResult.Diag &&
6893 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6894 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006895
Anders Carlssone21555e2008-11-30 19:50:32 +00006896 if (Result)
6897 *Result = EvalResult.Val.getInt();
6898 return false;
6899}
Douglas Gregore0762c92009-06-19 23:52:42 +00006900
Douglas Gregor2afce722009-11-26 00:44:06 +00006901void
Mike Stump1eb44332009-09-09 15:08:12 +00006902Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00006903 ExprEvalContexts.push_back(
6904 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00006905}
6906
Mike Stump1eb44332009-09-09 15:08:12 +00006907void
Douglas Gregor2afce722009-11-26 00:44:06 +00006908Sema::PopExpressionEvaluationContext() {
6909 // Pop the current expression evaluation context off the stack.
6910 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6911 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006912
Douglas Gregor06d33692009-12-12 07:57:52 +00006913 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
6914 if (Rec.PotentiallyReferenced) {
6915 // Mark any remaining declarations in the current position of the stack
6916 // as "referenced". If they were not meant to be referenced, semantic
6917 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6918 for (PotentiallyReferencedDecls::iterator
6919 I = Rec.PotentiallyReferenced->begin(),
6920 IEnd = Rec.PotentiallyReferenced->end();
6921 I != IEnd; ++I)
6922 MarkDeclarationReferenced(I->first, I->second);
6923 }
6924
6925 if (Rec.PotentiallyDiagnosed) {
6926 // Emit any pending diagnostics.
6927 for (PotentiallyEmittedDiagnostics::iterator
6928 I = Rec.PotentiallyDiagnosed->begin(),
6929 IEnd = Rec.PotentiallyDiagnosed->end();
6930 I != IEnd; ++I)
6931 Diag(I->first, I->second);
6932 }
Douglas Gregor2afce722009-11-26 00:44:06 +00006933 }
6934
6935 // When are coming out of an unevaluated context, clear out any
6936 // temporaries that we may have created as part of the evaluation of
6937 // the expression in that context: they aren't relevant because they
6938 // will never be constructed.
6939 if (Rec.Context == Unevaluated &&
6940 ExprTemporaries.size() > Rec.NumTemporaries)
6941 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6942 ExprTemporaries.end());
6943
6944 // Destroy the popped expression evaluation record.
6945 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006946}
Douglas Gregore0762c92009-06-19 23:52:42 +00006947
6948/// \brief Note that the given declaration was referenced in the source code.
6949///
6950/// This routine should be invoke whenever a given declaration is referenced
6951/// in the source code, and where that reference occurred. If this declaration
6952/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6953/// C99 6.9p3), then the declaration will be marked as used.
6954///
6955/// \param Loc the location where the declaration was referenced.
6956///
6957/// \param D the declaration that has been referenced by the source code.
6958void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6959 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006960
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006961 if (D->isUsed())
6962 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006963
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006964 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6965 // template or not. The reason for this is that unevaluated expressions
6966 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6967 // -Wunused-parameters)
6968 if (isa<ParmVarDecl>(D) ||
6969 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006970 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006971
Douglas Gregore0762c92009-06-19 23:52:42 +00006972 // Do not mark anything as "used" within a dependent context; wait for
6973 // an instantiation.
6974 if (CurContext->isDependentContext())
6975 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006976
Douglas Gregor2afce722009-11-26 00:44:06 +00006977 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006978 case Unevaluated:
6979 // We are in an expression that is not potentially evaluated; do nothing.
6980 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006981
Douglas Gregorac7610d2009-06-22 20:57:11 +00006982 case PotentiallyEvaluated:
6983 // We are in a potentially-evaluated expression, so this declaration is
6984 // "used"; handle this below.
6985 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006986
Douglas Gregorac7610d2009-06-22 20:57:11 +00006987 case PotentiallyPotentiallyEvaluated:
6988 // We are in an expression that may be potentially evaluated; queue this
6989 // declaration reference until we know whether the expression is
6990 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00006991 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00006992 return;
6993 }
Mike Stump1eb44332009-09-09 15:08:12 +00006994
Douglas Gregore0762c92009-06-19 23:52:42 +00006995 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006996 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006997 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006998 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6999 if (!Constructor->isUsed())
7000 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007001 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007002 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007003 if (!Constructor->isUsed())
7004 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7005 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007006
7007 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007008 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7009 if (Destructor->isImplicit() && !Destructor->isUsed())
7010 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007011
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007012 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7013 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7014 MethodDecl->getOverloadedOperator() == OO_Equal) {
7015 if (!MethodDecl->isUsed())
7016 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7017 }
7018 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007019 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007020 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007021 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007022 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007023 bool AlreadyInstantiated = false;
7024 if (FunctionTemplateSpecializationInfo *SpecInfo
7025 = Function->getTemplateSpecializationInfo()) {
7026 if (SpecInfo->getPointOfInstantiation().isInvalid())
7027 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007028 else if (SpecInfo->getTemplateSpecializationKind()
7029 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007030 AlreadyInstantiated = true;
7031 } else if (MemberSpecializationInfo *MSInfo
7032 = Function->getMemberSpecializationInfo()) {
7033 if (MSInfo->getPointOfInstantiation().isInvalid())
7034 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007035 else if (MSInfo->getTemplateSpecializationKind()
7036 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007037 AlreadyInstantiated = true;
7038 }
7039
7040 if (!AlreadyInstantiated)
7041 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7042 }
7043
Douglas Gregore0762c92009-06-19 23:52:42 +00007044 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007045 Function->setUsed(true);
7046 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007047 }
Mike Stump1eb44332009-09-09 15:08:12 +00007048
Douglas Gregore0762c92009-06-19 23:52:42 +00007049 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007050 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007051 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007052 Var->getInstantiatedFromStaticDataMember()) {
7053 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7054 assert(MSInfo && "Missing member specialization information?");
7055 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7056 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7057 MSInfo->setPointOfInstantiation(Loc);
7058 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7059 }
7060 }
Mike Stump1eb44332009-09-09 15:08:12 +00007061
Douglas Gregore0762c92009-06-19 23:52:42 +00007062 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007063
Douglas Gregore0762c92009-06-19 23:52:42 +00007064 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007065 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007066 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007067}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007068
7069bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7070 CallExpr *CE, FunctionDecl *FD) {
7071 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7072 return false;
7073
7074 PartialDiagnostic Note =
7075 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7076 << FD->getDeclName() : PDiag();
7077 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7078
7079 if (RequireCompleteType(Loc, ReturnType,
7080 FD ?
7081 PDiag(diag::err_call_function_incomplete_return)
7082 << CE->getSourceRange() << FD->getDeclName() :
7083 PDiag(diag::err_call_incomplete_return)
7084 << CE->getSourceRange(),
7085 std::make_pair(NoteLoc, Note)))
7086 return true;
7087
7088 return false;
7089}
7090
John McCall5a881bb2009-10-12 21:59:07 +00007091// Diagnose the common s/=/==/ typo. Note that adding parentheses
7092// will prevent this condition from triggering, which is what we want.
7093void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7094 SourceLocation Loc;
7095
John McCalla52ef082009-11-11 02:41:58 +00007096 unsigned diagnostic = diag::warn_condition_is_assignment;
7097
John McCall5a881bb2009-10-12 21:59:07 +00007098 if (isa<BinaryOperator>(E)) {
7099 BinaryOperator *Op = cast<BinaryOperator>(E);
7100 if (Op->getOpcode() != BinaryOperator::Assign)
7101 return;
7102
John McCallc8d8ac52009-11-12 00:06:05 +00007103 // Greylist some idioms by putting them into a warning subcategory.
7104 if (ObjCMessageExpr *ME
7105 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7106 Selector Sel = ME->getSelector();
7107
John McCallc8d8ac52009-11-12 00:06:05 +00007108 // self = [<foo> init...]
7109 if (isSelfExpr(Op->getLHS())
7110 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7111 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7112
7113 // <foo> = [<bar> nextObject]
7114 else if (Sel.isUnarySelector() &&
7115 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7116 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7117 }
John McCalla52ef082009-11-11 02:41:58 +00007118
John McCall5a881bb2009-10-12 21:59:07 +00007119 Loc = Op->getOperatorLoc();
7120 } else if (isa<CXXOperatorCallExpr>(E)) {
7121 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7122 if (Op->getOperator() != OO_Equal)
7123 return;
7124
7125 Loc = Op->getOperatorLoc();
7126 } else {
7127 // Not an assignment.
7128 return;
7129 }
7130
John McCall5a881bb2009-10-12 21:59:07 +00007131 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007132 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007133
John McCalla52ef082009-11-11 02:41:58 +00007134 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007135 << E->getSourceRange()
7136 << CodeModificationHint::CreateInsertion(Open, "(")
7137 << CodeModificationHint::CreateInsertion(Close, ")");
7138}
7139
7140bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7141 DiagnoseAssignmentAsCondition(E);
7142
7143 if (!E->isTypeDependent()) {
7144 DefaultFunctionArrayConversion(E);
7145
7146 QualType T = E->getType();
7147
7148 if (getLangOptions().CPlusPlus) {
7149 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7150 return true;
7151 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7152 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7153 << T << E->getSourceRange();
7154 return true;
7155 }
7156 }
7157
7158 return false;
7159}