blob: 7cdc275c7ec8f8e4ca16cb3d8f704164ba185f0b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000018#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000027#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000028#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000029#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
David Chisnall0f436562009-08-17 16:35:33 +000032
Douglas Gregor48f3bb92009-02-18 21:56:37 +000033/// \brief Determine whether the use of this declaration is valid, and
34/// emit any corresponding diagnostics.
35///
36/// This routine diagnoses various problems with referencing
37/// declarations that can occur when using a declaration. For example,
38/// it might warn if a deprecated or unavailable declaration is being
39/// used, or produce an error (and return true) if a C++0x deleted
40/// function is being used.
41///
Chris Lattner52338262009-10-25 22:31:57 +000042/// If IgnoreDeprecated is set to true, this should not want about deprecated
43/// decls.
44///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000045/// \returns true if there was an error (this declaration cannot be
46/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000047///
John McCall54abf7d2009-11-04 02:18:39 +000048bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000049 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000050 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000051 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000052 }
53
Chris Lattnerffb93682009-10-25 17:21:40 +000054 // See if the decl is unavailable
55 if (D->getAttr<UnavailableAttr>()) {
56 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
57 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
58 }
59
Douglas Gregor48f3bb92009-02-18 21:56:37 +000060 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000061 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000062 if (FD->isDeleted()) {
63 Diag(Loc, diag::err_deleted_function_use);
64 Diag(D->getLocation(), diag::note_unavailable_here) << true;
65 return true;
66 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000067 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000068
Douglas Gregor48f3bb92009-02-18 21:56:37 +000069 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000070}
71
Fariborz Jahanian5b530052009-05-13 18:09:35 +000072/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000073/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000074/// attribute. It warns if call does not have the sentinel argument.
75///
76void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000077 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000078 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000079 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000080 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000081 int sentinelPos = attr->getSentinel();
82 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000083
Mike Stump390b4cc2009-05-16 07:39:55 +000084 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
85 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000086 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000087 bool warnNotEnoughArgs = false;
88 int isMethod = 0;
89 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
90 // skip over named parameters.
91 ObjCMethodDecl::param_iterator P, E = MD->param_end();
92 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
93 if (nullPos)
94 --nullPos;
95 else
96 ++i;
97 }
98 warnNotEnoughArgs = (P != E || i >= NumArgs);
99 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000100 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000101 // skip over named parameters.
102 ObjCMethodDecl::param_iterator P, E = FD->param_end();
103 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
104 if (nullPos)
105 --nullPos;
106 else
107 ++i;
108 }
109 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000110 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000111 // block or function pointer call.
112 QualType Ty = V->getType();
113 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000114 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000115 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
116 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000117 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
118 unsigned NumArgsInProto = Proto->getNumArgs();
119 unsigned k;
120 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
121 if (nullPos)
122 --nullPos;
123 else
124 ++i;
125 }
126 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
127 }
128 if (Ty->isBlockPointerType())
129 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000130 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000131 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000133 return;
134
135 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000136 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000137 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000138 return;
139 }
140 int sentinel = i;
141 while (sentinelPos > 0 && i < NumArgs-1) {
142 --sentinelPos;
143 ++i;
144 }
145 if (sentinelPos > 0) {
146 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000148 return;
149 }
150 while (i < NumArgs-1) {
151 ++i;
152 ++sentinel;
153 }
154 Expr *sentinelExpr = Args[sentinel];
Anders Carlssone4d2bdd2009-11-24 17:24:21 +0000155 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
156 (!sentinelExpr->getType()->isPointerType() ||
157 !sentinelExpr->isNullPointerConstant(Context,
158 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000159 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000161 }
162 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000163}
164
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000165SourceRange Sema::getExprRange(ExprTy *E) const {
166 Expr *Ex = (Expr *)E;
167 return Ex? Ex->getSourceRange() : SourceRange();
168}
169
Chris Lattnere7a2e912008-07-25 21:10:04 +0000170//===----------------------------------------------------------------------===//
171// Standard Promotions and Conversions
172//===----------------------------------------------------------------------===//
173
Chris Lattnere7a2e912008-07-25 21:10:04 +0000174/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
175void Sema::DefaultFunctionArrayConversion(Expr *&E) {
176 QualType Ty = E->getType();
177 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
178
Chris Lattnere7a2e912008-07-25 21:10:04 +0000179 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000180 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000181 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000182 else if (Ty->isArrayType()) {
183 // In C90 mode, arrays only promote to pointers if the array expression is
184 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
185 // type 'array of type' is converted to an expression that has type 'pointer
186 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
187 // that has type 'array of type' ...". The relevant change is "an lvalue"
188 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000189 //
190 // C++ 4.2p1:
191 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
192 // T" can be converted to an rvalue of type "pointer to T".
193 //
194 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
195 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000196 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
197 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000198 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000199}
200
201/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000202/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000203/// sometimes surpressed. For example, the array->pointer conversion doesn't
204/// apply if the array is an argument to the sizeof or address (&) operators.
205/// In these instances, this routine should *not* be called.
206Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
207 QualType Ty = Expr->getType();
208 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Douglas Gregorfc24e442009-05-01 20:41:21 +0000210 // C99 6.3.1.1p2:
211 //
212 // The following may be used in an expression wherever an int or
213 // unsigned int may be used:
214 // - an object or expression with an integer type whose integer
215 // conversion rank is less than or equal to the rank of int
216 // and unsigned int.
217 // - A bit-field of type _Bool, int, signed int, or unsigned int.
218 //
219 // If an int can represent all values of the original type, the
220 // value is converted to an int; otherwise, it is converted to an
221 // unsigned int. These are called the integer promotions. All
222 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000223 QualType PTy = Context.isPromotableBitField(Expr);
224 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000225 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000226 return Expr;
227 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000228 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000229 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000230 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000231 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000232 }
233
Douglas Gregorfc24e442009-05-01 20:41:21 +0000234 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000235 return Expr;
236}
237
Chris Lattner05faf172008-07-25 22:25:12 +0000238/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000239/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000240/// double. All other argument types are converted by UsualUnaryConversions().
241void Sema::DefaultArgumentPromotion(Expr *&Expr) {
242 QualType Ty = Expr->getType();
243 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattner05faf172008-07-25 22:25:12 +0000245 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000246 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000247 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000248 return ImpCastExprToType(Expr, Context.DoubleTy,
249 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattner05faf172008-07-25 22:25:12 +0000251 UsualUnaryConversions(Expr);
252}
253
Chris Lattner312531a2009-04-12 08:11:20 +0000254/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
255/// will warn if the resulting type is not a POD type, and rejects ObjC
256/// interfaces passed by value. This returns true if the argument type is
257/// completely illegal.
258bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000259 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattner312531a2009-04-12 08:11:20 +0000261 if (Expr->getType()->isObjCInterfaceType()) {
Douglas Gregor75b699a2009-12-12 07:25:49 +0000262 switch (ExprEvalContexts.back().Context ) {
263 case Unevaluated:
264 // The argument will never be evaluated, so don't complain.
265 break;
266
267 case PotentiallyEvaluated:
268 Diag(Expr->getLocStart(),
269 diag::err_cannot_pass_objc_interface_to_vararg)
270 << Expr->getType() << CT;
271 return true;
272
273 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +0000274 ExprEvalContexts.back().addDiagnostic(Expr->getLocStart(),
275 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
276 << Expr->getType() << CT);
Douglas Gregor75b699a2009-12-12 07:25:49 +0000277 break;
278 }
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000279 }
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Douglas Gregor75b699a2009-12-12 07:25:49 +0000281 if (!Expr->getType()->isPODType()) {
282 switch (ExprEvalContexts.back().Context ) {
283 case Unevaluated:
284 // The argument will never be evaluated, so don't complain.
285 break;
286
287 case PotentiallyEvaluated:
288 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
289 << Expr->getType() << CT;
290 break;
291
292 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +0000293 ExprEvalContexts.back().addDiagnostic(Expr->getLocStart(),
294 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
295 << Expr->getType() << CT);
Douglas Gregor75b699a2009-12-12 07:25:49 +0000296 break;
297 }
298 }
Chris Lattner312531a2009-04-12 08:11:20 +0000299
300 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000301}
302
303
Chris Lattnere7a2e912008-07-25 21:10:04 +0000304/// UsualArithmeticConversions - Performs various conversions that are common to
305/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000306/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000307/// responsible for emitting appropriate error diagnostics.
308/// FIXME: verify the conversion rules for "complex int" are consistent with
309/// GCC.
310QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
311 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000312 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000313 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000314
315 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000316
Mike Stump1eb44332009-09-09 15:08:12 +0000317 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000318 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000319 QualType lhs =
320 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000321 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000322 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000323
324 // If both types are identical, no conversion is needed.
325 if (lhs == rhs)
326 return lhs;
327
328 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
329 // The caller can deal with this (e.g. pointer + int).
330 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
331 return lhs;
332
Douglas Gregor2d833e32009-05-02 00:36:19 +0000333 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000334 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000335 if (!LHSBitfieldPromoteTy.isNull())
336 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000337 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000338 if (!RHSBitfieldPromoteTy.isNull())
339 rhs = RHSBitfieldPromoteTy;
340
Eli Friedmana95d7572009-08-19 07:44:53 +0000341 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000342 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000343 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
344 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000345 return destType;
346}
347
Chris Lattnere7a2e912008-07-25 21:10:04 +0000348//===----------------------------------------------------------------------===//
349// Semantic Analysis for various Expression Types
350//===----------------------------------------------------------------------===//
351
352
Steve Narofff69936d2007-09-16 03:34:24 +0000353/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000354/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
355/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
356/// multiple tokens. However, the common case is that StringToks points to one
357/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000358///
359Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000360Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 assert(NumStringToks && "Must have at least one string!");
362
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000363 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000365 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000366
367 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
368 for (unsigned i = 0; i != NumStringToks; ++i)
369 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000370
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000371 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000372 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000373 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000374
375 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
376 if (getLangOptions().CPlusPlus)
377 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000378
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000379 // Get an array type for the string, according to C99 6.4.5. This includes
380 // the nul terminator character as well as the string length for pascal
381 // strings.
382 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000383 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000384 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000387 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000388 Literal.GetStringLength(),
389 Literal.AnyWide, StrTy,
390 &StringTokLocs[0],
391 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000392}
393
Chris Lattner639e2d32008-10-20 05:16:36 +0000394/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
395/// CurBlock to VD should cause it to be snapshotted (as we do for auto
396/// variables defined outside the block) or false if this is not needed (e.g.
397/// for values inside the block or for globals).
398///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000399/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
400/// up-to-date.
401///
Chris Lattner639e2d32008-10-20 05:16:36 +0000402static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
403 ValueDecl *VD) {
404 // If the value is defined inside the block, we couldn't snapshot it even if
405 // we wanted to.
406 if (CurBlock->TheDecl == VD->getDeclContext())
407 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner639e2d32008-10-20 05:16:36 +0000409 // If this is an enum constant or function, it is constant, don't snapshot.
410 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
411 return false;
412
413 // If this is a reference to an extern, static, or global variable, no need to
414 // snapshot it.
415 // FIXME: What about 'const' variables in C++?
416 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000417 if (!Var->hasLocalStorage())
418 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000420 // Blocks that have these can't be constant.
421 CurBlock->hasBlockDeclRefExprs = true;
422
423 // If we have nested blocks, the decl may be declared in an outer block (in
424 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
425 // be defined outside all of the current blocks (in which case the blocks do
426 // all get the bit). Walk the nesting chain.
427 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
428 NextBlock = NextBlock->PrevBlockInfo) {
429 // If we found the defining block for the variable, don't mark the block as
430 // having a reference outside it.
431 if (NextBlock->TheDecl == VD->getDeclContext())
432 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000434 // Otherwise, the DeclRef from the inner block causes the outer one to need
435 // a snapshot as well.
436 NextBlock->hasBlockDeclRefExprs = true;
437 }
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner639e2d32008-10-20 05:16:36 +0000439 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000440}
441
Chris Lattner639e2d32008-10-20 05:16:36 +0000442
443
Douglas Gregora2813ce2009-10-23 18:54:35 +0000444/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000445Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000446Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000447 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000448 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
449 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000450 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000451 << D->getDeclName();
452 return ExprError();
453 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Anders Carlssone41590d2009-06-24 00:10:43 +0000455 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
456 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
457 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
458 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000459 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000460 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000461 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000462 << D->getIdentifier();
463 return ExprError();
464 }
465 }
466 }
467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Douglas Gregore0762c92009-06-19 23:52:42 +0000469 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Douglas Gregora2813ce2009-10-23 18:54:35 +0000471 return Owned(DeclRefExpr::Create(Context,
472 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
473 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000474 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000475}
476
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000477/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
478/// variable corresponding to the anonymous union or struct whose type
479/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000480static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
481 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000482 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000483 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Mike Stump390b4cc2009-05-16 07:39:55 +0000485 // FIXME: Once Decls are directly linked together, this will be an O(1)
486 // operation rather than a slow walk through DeclContext's vector (which
487 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000488 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000489 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000490 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000491 D != DEnd; ++D) {
492 if (*D == Record) {
493 // The object for the anonymous struct/union directly
494 // follows its type in the list of declarations.
495 ++D;
496 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000497 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000498 return *D;
499 }
500 }
501
502 assert(false && "Missing object for anonymous record");
503 return 0;
504}
505
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000506/// \brief Given a field that represents a member of an anonymous
507/// struct/union, build the path from that field's context to the
508/// actual member.
509///
510/// Construct the sequence of field member references we'll have to
511/// perform to get to the field in the anonymous union/struct. The
512/// list of members is built from the field outward, so traverse it
513/// backwards to go from an object in the current context to the field
514/// we found.
515///
516/// \returns The variable from which the field access should begin,
517/// for an anonymous struct/union that is not a member of another
518/// class. Otherwise, returns NULL.
519VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
520 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000521 assert(Field->getDeclContext()->isRecord() &&
522 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
523 && "Field must be stored inside an anonymous struct or union");
524
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000525 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000526 VarDecl *BaseObject = 0;
527 DeclContext *Ctx = Field->getDeclContext();
528 do {
529 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000530 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000531 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000532 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000533 else {
534 BaseObject = cast<VarDecl>(AnonObject);
535 break;
536 }
537 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000538 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000539 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000540
541 return BaseObject;
542}
543
544Sema::OwningExprResult
545Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
546 FieldDecl *Field,
547 Expr *BaseObjectExpr,
548 SourceLocation OpLoc) {
549 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000550 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000551 AnonFields);
552
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000553 // Build the expression that refers to the base object, from
554 // which we will build a sequence of member references to each
555 // of the anonymous union objects and, eventually, the field we
556 // found via name lookup.
557 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000558 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000559 if (BaseObject) {
560 // BaseObject is an anonymous struct/union variable (and is,
561 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000562 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000563 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000564 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000565 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000566 BaseQuals
567 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000568 } else if (BaseObjectExpr) {
569 // The caller provided the base object expression. Determine
570 // whether its a pointer and whether it adds any qualifiers to the
571 // anonymous struct/union fields we're looking into.
572 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000573 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000574 BaseObjectIsPointer = true;
575 ObjectType = ObjectPtr->getPointeeType();
576 }
John McCall0953e762009-09-24 19:53:00 +0000577 BaseQuals
578 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000579 } else {
580 // We've found a member of an anonymous struct/union that is
581 // inside a non-anonymous struct/union, so in a well-formed
582 // program our base object expression is "this".
583 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
584 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000585 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000586 = Context.getTagDeclType(
587 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
588 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000589 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000590 == Context.getCanonicalType(ThisType)) ||
591 IsDerivedFrom(ThisType, AnonFieldType)) {
592 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000593 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000594 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000595 BaseObjectIsPointer = true;
596 }
597 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000598 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
599 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000600 }
John McCall0953e762009-09-24 19:53:00 +0000601 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000602 }
603
Mike Stump1eb44332009-09-09 15:08:12 +0000604 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000605 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
606 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000607 }
608
609 // Build the implicit member references to the field of the
610 // anonymous struct/union.
611 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000612 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000613 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
614 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
615 FI != FIEnd; ++FI) {
616 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000617 Qualifiers MemberTypeQuals =
618 Context.getCanonicalType(MemberType).getQualifiers();
619
620 // CVR attributes from the base are picked up by members,
621 // except that 'mutable' members don't pick up 'const'.
622 if ((*FI)->isMutable())
623 ResultQuals.removeConst();
624
625 // GC attributes are never picked up by members.
626 ResultQuals.removeObjCGCAttr();
627
628 // TR 18037 does not allow fields to be declared with address spaces.
629 assert(!MemberTypeQuals.hasAddressSpace());
630
631 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
632 if (NewQuals != MemberTypeQuals)
633 MemberType = Context.getQualifiedType(MemberType, NewQuals);
634
Douglas Gregore0762c92009-06-19 23:52:42 +0000635 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman16c53782009-12-04 07:18:51 +0000636 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000637 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000638 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
639 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000640 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000641 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000642 }
643
Sebastian Redlcd965b92009-01-18 18:53:16 +0000644 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000645}
646
John McCall129e2df2009-11-30 22:42:35 +0000647/// Decomposes the given name into a DeclarationName, its location, and
648/// possibly a list of template arguments.
649///
650/// If this produces template arguments, it is permitted to call
651/// DecomposeTemplateName.
652///
653/// This actually loses a lot of source location information for
654/// non-standard name kinds; we should consider preserving that in
655/// some way.
656static void DecomposeUnqualifiedId(Sema &SemaRef,
657 const UnqualifiedId &Id,
658 TemplateArgumentListInfo &Buffer,
659 DeclarationName &Name,
660 SourceLocation &NameLoc,
661 const TemplateArgumentListInfo *&TemplateArgs) {
662 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
663 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
664 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
665
666 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
667 Id.TemplateId->getTemplateArgs(),
668 Id.TemplateId->NumArgs);
669 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
670 TemplateArgsPtr.release();
671
672 TemplateName TName =
673 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
674
675 Name = SemaRef.Context.getNameForTemplate(TName);
676 NameLoc = Id.TemplateId->TemplateNameLoc;
677 TemplateArgs = &Buffer;
678 } else {
679 Name = SemaRef.GetNameFromUnqualifiedId(Id);
680 NameLoc = Id.StartLocation;
681 TemplateArgs = 0;
682 }
683}
684
685/// Decompose the given template name into a list of lookup results.
686///
687/// The unqualified ID must name a non-dependent template, which can
688/// be more easily tested by checking whether DecomposeUnqualifiedId
689/// found template arguments.
690static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
691 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
692 TemplateName TName =
693 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
694
John McCallf7a1a742009-11-24 19:00:30 +0000695 if (TemplateDecl *TD = TName.getAsTemplateDecl())
696 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000697 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
698 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
699 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000700 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000701
John McCallf7a1a742009-11-24 19:00:30 +0000702 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000703}
704
John McCall129e2df2009-11-30 22:42:35 +0000705static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
706 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
707 E = Record->bases_end(); I != E; ++I) {
708 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
709 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
710 if (!BaseRT) return false;
711
712 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
713 if (!BaseRecord->isDefinition() ||
714 !IsFullyFormedScope(SemaRef, BaseRecord))
715 return false;
716 }
717
718 return true;
719}
720
John McCalle1599ce2009-11-30 23:50:49 +0000721/// Determines whether we can lookup this id-expression now or whether
722/// we have to wait until template instantiation is complete.
723static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000724 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000725
John McCalle1599ce2009-11-30 23:50:49 +0000726 // If the qualifier scope isn't computable, it's definitely dependent.
727 if (!DC) return true;
728
729 // If the qualifier scope doesn't name a record, we can always look into it.
730 if (!isa<CXXRecordDecl>(DC)) return false;
731
732 // We can't look into record types unless they're fully-formed.
733 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
734
John McCallaa81e162009-12-01 22:10:20 +0000735 return false;
736}
John McCalle1599ce2009-11-30 23:50:49 +0000737
John McCallaa81e162009-12-01 22:10:20 +0000738/// Determines if the given class is provably not derived from all of
739/// the prospective base classes.
740static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
741 CXXRecordDecl *Record,
742 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000743 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000744 return false;
745
John McCallb1b42562009-12-01 22:28:41 +0000746 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
747 if (!RD) return false;
748 Record = cast<CXXRecordDecl>(RD);
749
John McCallaa81e162009-12-01 22:10:20 +0000750 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
751 E = Record->bases_end(); I != E; ++I) {
752 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
753 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
754 if (!BaseRT) return false;
755
756 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000757 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
758 return false;
759 }
760
761 return true;
762}
763
John McCall144238e2009-12-02 20:26:00 +0000764/// Determines if this a C++ class member.
765static bool IsClassMember(NamedDecl *D) {
766 DeclContext *DC = D->getDeclContext();
John McCall336e7742009-12-02 19:59:55 +0000767
John McCall144238e2009-12-02 20:26:00 +0000768 // C++0x [class.mem]p1:
769 // The enumerators of an unscoped enumeration defined in
770 // the class are members of the class.
771 // FIXME: support C++0x scoped enumerations.
772 if (isa<EnumDecl>(DC))
773 DC = DC->getParent();
774
775 return DC->isRecord();
776}
777
778/// Determines if this is an instance member of a class.
779static bool IsInstanceMember(NamedDecl *D) {
780 assert(IsClassMember(D) &&
John McCallaa81e162009-12-01 22:10:20 +0000781 "checking whether non-member is instance member");
782
783 if (isa<FieldDecl>(D)) return true;
784
785 if (isa<CXXMethodDecl>(D))
786 return !cast<CXXMethodDecl>(D)->isStatic();
787
788 if (isa<FunctionTemplateDecl>(D)) {
789 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
790 return !cast<CXXMethodDecl>(D)->isStatic();
791 }
792
793 return false;
794}
795
796enum IMAKind {
797 /// The reference is definitely not an instance member access.
798 IMA_Static,
799
800 /// The reference may be an implicit instance member access.
801 IMA_Mixed,
802
803 /// The reference may be to an instance member, but it is invalid if
804 /// so, because the context is not an instance method.
805 IMA_Mixed_StaticContext,
806
807 /// The reference may be to an instance member, but it is invalid if
808 /// so, because the context is from an unrelated class.
809 IMA_Mixed_Unrelated,
810
811 /// The reference is definitely an implicit instance member access.
812 IMA_Instance,
813
814 /// The reference may be to an unresolved using declaration.
815 IMA_Unresolved,
816
817 /// The reference may be to an unresolved using declaration and the
818 /// context is not an instance method.
819 IMA_Unresolved_StaticContext,
820
821 /// The reference is to a member of an anonymous structure in a
822 /// non-class context.
823 IMA_AnonymousMember,
824
825 /// All possible referrents are instance members and the current
826 /// context is not an instance method.
827 IMA_Error_StaticContext,
828
829 /// All possible referrents are instance members of an unrelated
830 /// class.
831 IMA_Error_Unrelated
832};
833
834/// The given lookup names class member(s) and is not being used for
835/// an address-of-member expression. Classify the type of access
836/// according to whether it's possible that this reference names an
837/// instance member. This is best-effort; it is okay to
838/// conservatively answer "yes", in which case some errors will simply
839/// not be caught until template-instantiation.
840static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
841 const LookupResult &R) {
John McCall144238e2009-12-02 20:26:00 +0000842 assert(!R.empty() && IsClassMember(*R.begin()));
John McCallaa81e162009-12-01 22:10:20 +0000843
844 bool isStaticContext =
845 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
846 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
847
848 if (R.isUnresolvableResult())
849 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
850
851 // Collect all the declaring classes of instance members we find.
852 bool hasNonInstance = false;
853 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
854 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
855 NamedDecl *D = (*I)->getUnderlyingDecl();
856 if (IsInstanceMember(D)) {
857 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
858
859 // If this is a member of an anonymous record, move out to the
860 // innermost non-anonymous struct or union. If there isn't one,
861 // that's a special case.
862 while (R->isAnonymousStructOrUnion()) {
863 R = dyn_cast<CXXRecordDecl>(R->getParent());
864 if (!R) return IMA_AnonymousMember;
865 }
866 Classes.insert(R->getCanonicalDecl());
867 }
868 else
869 hasNonInstance = true;
870 }
871
872 // If we didn't find any instance members, it can't be an implicit
873 // member reference.
874 if (Classes.empty())
875 return IMA_Static;
876
877 // If the current context is not an instance method, it can't be
878 // an implicit member reference.
879 if (isStaticContext)
880 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
881
882 // If we can prove that the current context is unrelated to all the
883 // declaring classes, it can't be an implicit member reference (in
884 // which case it's an error if any of those members are selected).
885 if (IsProvablyNotDerivedFrom(SemaRef,
886 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
887 Classes))
888 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
889
890 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
891}
892
893/// Diagnose a reference to a field with no object available.
894static void DiagnoseInstanceReference(Sema &SemaRef,
895 const CXXScopeSpec &SS,
896 const LookupResult &R) {
897 SourceLocation Loc = R.getNameLoc();
898 SourceRange Range(Loc);
899 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
900
901 if (R.getAsSingle<FieldDecl>()) {
902 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
903 if (MD->isStatic()) {
904 // "invalid use of member 'x' in static member function"
905 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
906 << Range << R.getLookupName();
907 return;
908 }
909 }
910
911 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
912 << R.getLookupName() << Range;
913 return;
914 }
915
916 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000917}
918
John McCallf7a1a742009-11-24 19:00:30 +0000919Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
920 const CXXScopeSpec &SS,
921 UnqualifiedId &Id,
922 bool HasTrailingLParen,
923 bool isAddressOfOperand) {
924 assert(!(isAddressOfOperand && HasTrailingLParen) &&
925 "cannot be direct & operand and have a trailing lparen");
926
927 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000928 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000929
John McCall129e2df2009-11-30 22:42:35 +0000930 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +0000931
932 // Decompose the UnqualifiedId into the following data.
933 DeclarationName Name;
934 SourceLocation NameLoc;
935 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +0000936 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
937 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000938
Douglas Gregor10c42622008-11-18 15:03:34 +0000939 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +0000940
John McCallf7a1a742009-11-24 19:00:30 +0000941 // C++ [temp.dep.expr]p3:
942 // An id-expression is type-dependent if it contains:
943 // -- a nested-name-specifier that contains a class-name that
944 // names a dependent type.
945 // Determine whether this is a member of an unknown specialization;
946 // we need to handle these differently.
John McCalle1599ce2009-11-30 23:50:49 +0000947 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCallf7a1a742009-11-24 19:00:30 +0000948 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000949 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000950 TemplateArgs);
951 }
John McCallba135432009-11-21 08:51:07 +0000952
John McCallf7a1a742009-11-24 19:00:30 +0000953 // Perform the required lookup.
954 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
955 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +0000956 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +0000957 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +0000958 } else {
959 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +0000960
John McCallf7a1a742009-11-24 19:00:30 +0000961 // If this reference is in an Objective-C method, then we need to do
962 // some special Objective-C lookup, too.
963 if (!SS.isSet() && II && getCurMethodDecl()) {
964 OwningExprResult E(LookupInObjCMethod(R, S, II));
965 if (E.isInvalid())
966 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000967
John McCallf7a1a742009-11-24 19:00:30 +0000968 Expr *Ex = E.takeAs<Expr>();
969 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000970 }
Chris Lattner8a934232008-03-31 00:36:02 +0000971 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000972
John McCallf7a1a742009-11-24 19:00:30 +0000973 if (R.isAmbiguous())
974 return ExprError();
975
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000976 // Determine whether this name might be a candidate for
977 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +0000978 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000979
John McCallf7a1a742009-11-24 19:00:30 +0000980 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000981 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +0000982 // in C90, extension in C99, forbidden in C++).
983 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
984 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
985 if (D) R.addDecl(D);
986 }
987
988 // If this name wasn't predeclared and if this is not a function
989 // call, diagnose the problem.
990 if (R.empty()) {
991 if (!SS.isEmpty())
992 return ExprError(Diag(NameLoc, diag::err_no_member)
993 << Name << computeDeclContext(SS, false)
994 << SS.getRange());
Douglas Gregor3f093272009-10-13 21:16:44 +0000995 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Sean Hunt3e518bd2009-11-29 07:34:05 +0000996 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000997 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCallf7a1a742009-11-24 19:00:30 +0000998 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
999 << Name);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001000 else
John McCallf7a1a742009-11-24 19:00:30 +00001001 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 }
1003 }
Mike Stump1eb44332009-09-09 15:08:12 +00001004
John McCallf7a1a742009-11-24 19:00:30 +00001005 // This is guaranteed from this point on.
1006 assert(!R.empty() || ADL);
1007
1008 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001009 // Warn about constructs like:
1010 // if (void *X = foo()) { ... } else { X }.
1011 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Douglas Gregor751f9a42009-06-30 15:47:41 +00001013 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1014 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001015 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001016 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001017 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001018 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001019 << Var->getDeclName()
1020 << (Var->getType()->isPointerType()? 2 :
1021 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001022 break;
1023 }
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001025 // Move to the parent of this scope.
1026 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001027 }
1028 }
John McCallf7a1a742009-11-24 19:00:30 +00001029 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001030 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1031 // C99 DR 316 says that, if a function type comes from a
1032 // function definition (without a prototype), that type is only
1033 // used for checking compatibility. Therefore, when referencing
1034 // the function, we pretend that we don't have the full function
1035 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001036 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001037 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001038
Douglas Gregor751f9a42009-06-30 15:47:41 +00001039 QualType T = Func->getType();
1040 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001041 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001042 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001043 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001044 }
1045 }
Mike Stump1eb44332009-09-09 15:08:12 +00001046
John McCallaa81e162009-12-01 22:10:20 +00001047 // Check whether this might be a C++ implicit instance member access.
1048 // C++ [expr.prim.general]p6:
1049 // Within the definition of a non-static member function, an
1050 // identifier that names a non-static member is transformed to a
1051 // class member access expression.
1052 // But note that &SomeClass::foo is grammatically distinct, even
1053 // though we don't parse it that way.
John McCall144238e2009-12-02 20:26:00 +00001054 if (!R.empty() && IsClassMember(*R.begin())) {
John McCallf7a1a742009-11-24 19:00:30 +00001055 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall5b3f9132009-11-22 01:44:31 +00001056
John McCallaa81e162009-12-01 22:10:20 +00001057 if (!isAbstractMemberPointer) {
1058 switch (ClassifyImplicitMemberAccess(*this, R)) {
1059 case IMA_Instance:
1060 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1061
1062 case IMA_AnonymousMember:
1063 assert(R.isSingleResult());
1064 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1065 R.getAsSingle<FieldDecl>());
1066
1067 case IMA_Mixed:
1068 case IMA_Mixed_Unrelated:
1069 case IMA_Unresolved:
1070 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1071
1072 case IMA_Static:
1073 case IMA_Mixed_StaticContext:
1074 case IMA_Unresolved_StaticContext:
1075 break;
1076
1077 case IMA_Error_StaticContext:
1078 case IMA_Error_Unrelated:
1079 DiagnoseInstanceReference(*this, SS, R);
1080 return ExprError();
1081 }
John McCall5b3f9132009-11-22 01:44:31 +00001082 }
1083 }
1084
John McCallf7a1a742009-11-24 19:00:30 +00001085 if (TemplateArgs)
1086 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001087
John McCallf7a1a742009-11-24 19:00:30 +00001088 return BuildDeclarationNameExpr(SS, R, ADL);
1089}
1090
John McCall129e2df2009-11-30 22:42:35 +00001091/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1092/// declaration name, generally during template instantiation.
1093/// There's a large number of things which don't need to be done along
1094/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001095Sema::OwningExprResult
1096Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1097 DeclarationName Name,
1098 SourceLocation NameLoc) {
1099 DeclContext *DC;
1100 if (!(DC = computeDeclContext(SS, false)) ||
1101 DC->isDependentContext() ||
1102 RequireCompleteDeclContext(SS))
1103 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1104
1105 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1106 LookupQualifiedName(R, DC);
1107
1108 if (R.isAmbiguous())
1109 return ExprError();
1110
1111 if (R.empty()) {
1112 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1113 return ExprError();
1114 }
1115
1116 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1117}
1118
1119/// LookupInObjCMethod - The parser has read a name in, and Sema has
1120/// detected that we're currently inside an ObjC method. Perform some
1121/// additional lookup.
1122///
1123/// Ideally, most of this would be done by lookup, but there's
1124/// actually quite a lot of extra work involved.
1125///
1126/// Returns a null sentinel to indicate trivial success.
1127Sema::OwningExprResult
1128Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1129 IdentifierInfo *II) {
1130 SourceLocation Loc = Lookup.getNameLoc();
1131
1132 // There are two cases to handle here. 1) scoped lookup could have failed,
1133 // in which case we should look for an ivar. 2) scoped lookup could have
1134 // found a decl, but that decl is outside the current instance method (i.e.
1135 // a global variable). In these two cases, we do a lookup for an ivar with
1136 // this name, if the lookup sucedes, we replace it our current decl.
1137
1138 // If we're in a class method, we don't normally want to look for
1139 // ivars. But if we don't find anything else, and there's an
1140 // ivar, that's an error.
1141 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1142
1143 bool LookForIvars;
1144 if (Lookup.empty())
1145 LookForIvars = true;
1146 else if (IsClassMethod)
1147 LookForIvars = false;
1148 else
1149 LookForIvars = (Lookup.isSingleResult() &&
1150 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1151
1152 if (LookForIvars) {
1153 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1154 ObjCInterfaceDecl *ClassDeclared;
1155 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1156 // Diagnose using an ivar in a class method.
1157 if (IsClassMethod)
1158 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1159 << IV->getDeclName());
1160
1161 // If we're referencing an invalid decl, just return this as a silent
1162 // error node. The error diagnostic was already emitted on the decl.
1163 if (IV->isInvalidDecl())
1164 return ExprError();
1165
1166 // Check if referencing a field with __attribute__((deprecated)).
1167 if (DiagnoseUseOfDecl(IV, Loc))
1168 return ExprError();
1169
1170 // Diagnose the use of an ivar outside of the declaring class.
1171 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1172 ClassDeclared != IFace)
1173 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1174
1175 // FIXME: This should use a new expr for a direct reference, don't
1176 // turn this into Self->ivar, just return a BareIVarExpr or something.
1177 IdentifierInfo &II = Context.Idents.get("self");
1178 UnqualifiedId SelfName;
1179 SelfName.setIdentifier(&II, SourceLocation());
1180 CXXScopeSpec SelfScopeSpec;
1181 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1182 SelfName, false, false);
1183 MarkDeclarationReferenced(Loc, IV);
1184 return Owned(new (Context)
1185 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1186 SelfExpr.takeAs<Expr>(), true, true));
1187 }
1188 } else if (getCurMethodDecl()->isInstanceMethod()) {
1189 // We should warn if a local variable hides an ivar.
1190 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1191 ObjCInterfaceDecl *ClassDeclared;
1192 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1193 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1194 IFace == ClassDeclared)
1195 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1196 }
1197 }
1198
1199 // Needed to implement property "super.method" notation.
1200 if (Lookup.empty() && II->isStr("super")) {
1201 QualType T;
1202
1203 if (getCurMethodDecl()->isInstanceMethod())
1204 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1205 getCurMethodDecl()->getClassInterface()));
1206 else
1207 T = Context.getObjCClassType();
1208 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1209 }
1210
1211 // Sentinel value saying that we didn't do anything special.
1212 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001213}
John McCallba135432009-11-21 08:51:07 +00001214
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001215/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001216bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001217Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1218 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001219 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001220 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001221 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001222 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001223 if (DestType->isDependentType() || From->getType()->isDependentType())
1224 return false;
1225 QualType FromRecordType = From->getType();
1226 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001227 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001228 DestType = Context.getPointerType(DestType);
1229 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001230 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001231 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1232 CheckDerivedToBaseConversion(FromRecordType,
1233 DestRecordType,
1234 From->getSourceRange().getBegin(),
1235 From->getSourceRange()))
1236 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001237 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1238 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001239 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001240 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001241}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001242
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001243/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001244static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001245 const CXXScopeSpec &SS, ValueDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001246 SourceLocation Loc, QualType Ty,
1247 const TemplateArgumentListInfo *TemplateArgs = 0) {
1248 NestedNameSpecifier *Qualifier = 0;
1249 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001250 if (SS.isSet()) {
1251 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1252 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001253 }
Mike Stump1eb44332009-09-09 15:08:12 +00001254
John McCallf7a1a742009-11-24 19:00:30 +00001255 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1256 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001257}
1258
John McCallaa81e162009-12-01 22:10:20 +00001259/// Builds an implicit member access expression. The current context
1260/// is known to be an instance method, and the given unqualified lookup
1261/// set is known to contain only instance members, at least one of which
1262/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001263Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001264Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1265 LookupResult &R,
1266 const TemplateArgumentListInfo *TemplateArgs,
1267 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001268 assert(!R.empty() && !R.isAmbiguous());
1269
John McCallba135432009-11-21 08:51:07 +00001270 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001271
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001272 // We may have found a field within an anonymous union or struct
1273 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001274 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001275 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001276 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001277 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001278 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001279
John McCallaa81e162009-12-01 22:10:20 +00001280 // If this is known to be an instance access, go ahead and build a
1281 // 'this' expression now.
1282 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1283 Expr *This = 0; // null signifies implicit access
1284 if (IsKnownInstance) {
1285 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001286 }
1287
John McCallaa81e162009-12-01 22:10:20 +00001288 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1289 /*OpLoc*/ SourceLocation(),
1290 /*IsArrow*/ true,
1291 SS, R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001292}
1293
John McCallf7a1a742009-11-24 19:00:30 +00001294bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001295 const LookupResult &R,
1296 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001297 // Only when used directly as the postfix-expression of a call.
1298 if (!HasTrailingLParen)
1299 return false;
1300
1301 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001302 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001303 return false;
1304
1305 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001306 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001307 return false;
1308
1309 // Turn off ADL when we find certain kinds of declarations during
1310 // normal lookup:
1311 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1312 NamedDecl *D = *I;
1313
1314 // C++0x [basic.lookup.argdep]p3:
1315 // -- a declaration of a class member
1316 // Since using decls preserve this property, we check this on the
1317 // original decl.
John McCall144238e2009-12-02 20:26:00 +00001318 if (IsClassMember(D))
John McCallba135432009-11-21 08:51:07 +00001319 return false;
1320
1321 // C++0x [basic.lookup.argdep]p3:
1322 // -- a block-scope function declaration that is not a
1323 // using-declaration
1324 // NOTE: we also trigger this for function templates (in fact, we
1325 // don't check the decl type at all, since all other decl types
1326 // turn off ADL anyway).
1327 if (isa<UsingShadowDecl>(D))
1328 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1329 else if (D->getDeclContext()->isFunctionOrMethod())
1330 return false;
1331
1332 // C++0x [basic.lookup.argdep]p3:
1333 // -- a declaration that is neither a function or a function
1334 // template
1335 // And also for builtin functions.
1336 if (isa<FunctionDecl>(D)) {
1337 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1338
1339 // But also builtin functions.
1340 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1341 return false;
1342 } else if (!isa<FunctionTemplateDecl>(D))
1343 return false;
1344 }
1345
1346 return true;
1347}
1348
1349
John McCallba135432009-11-21 08:51:07 +00001350/// Diagnoses obvious problems with the use of the given declaration
1351/// as an expression. This is only actually called for lookups that
1352/// were not overloaded, and it doesn't promise that the declaration
1353/// will in fact be used.
1354static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1355 if (isa<TypedefDecl>(D)) {
1356 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1357 return true;
1358 }
1359
1360 if (isa<ObjCInterfaceDecl>(D)) {
1361 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1362 return true;
1363 }
1364
1365 if (isa<NamespaceDecl>(D)) {
1366 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1367 return true;
1368 }
1369
1370 return false;
1371}
1372
1373Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001374Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001375 LookupResult &R,
1376 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001377 // If this is a single, fully-resolved result and we don't need ADL,
1378 // just build an ordinary singleton decl ref.
1379 if (!NeedsADL && R.isSingleResult())
John McCall5b3f9132009-11-22 01:44:31 +00001380 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001381
1382 // We only need to check the declaration if there's exactly one
1383 // result, because in the overloaded case the results can only be
1384 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001385 if (R.isSingleResult() &&
1386 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001387 return ExprError();
1388
John McCallf7a1a742009-11-24 19:00:30 +00001389 bool Dependent
1390 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001391 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001392 = UnresolvedLookupExpr::Create(Context, Dependent,
1393 (NestedNameSpecifier*) SS.getScopeRep(),
1394 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001395 R.getLookupName(), R.getNameLoc(),
1396 NeedsADL, R.isOverloadedResult());
1397 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1398 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001399
1400 return Owned(ULE);
1401}
1402
1403
1404/// \brief Complete semantic analysis for a reference to the given declaration.
1405Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001406Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001407 SourceLocation Loc, NamedDecl *D) {
1408 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001409 assert(!isa<FunctionTemplateDecl>(D) &&
1410 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001411 DeclarationName Name = D->getDeclName();
1412
1413 if (CheckDeclInExpr(*this, Loc, D))
1414 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001415
Douglas Gregor9af2f522009-12-01 16:58:18 +00001416 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1417 // Specifically diagnose references to class templates that are missing
1418 // a template argument list.
1419 Diag(Loc, diag::err_template_decl_ref)
1420 << Template << SS.getRange();
1421 Diag(Template->getLocation(), diag::note_template_decl_here);
1422 return ExprError();
1423 }
1424
1425 // Make sure that we're referring to a value.
1426 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1427 if (!VD) {
1428 Diag(Loc, diag::err_ref_non_value)
1429 << D << SS.getRange();
1430 Diag(D->getLocation(), diag::note_previous_decl);
1431 return ExprError();
1432 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001433
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001434 // Check whether this declaration can be used. Note that we suppress
1435 // this check when we're going to perform argument-dependent lookup
1436 // on this function name, because this might not be the function
1437 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001438 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001439 return ExprError();
1440
Steve Naroffdd972f22008-09-05 22:11:13 +00001441 // Only create DeclRefExpr's for valid Decl's.
1442 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001443 return ExprError();
1444
Chris Lattner639e2d32008-10-20 05:16:36 +00001445 // If the identifier reference is inside a block, and it refers to a value
1446 // that is outside the block, create a BlockDeclRefExpr instead of a
1447 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1448 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001449 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001450 // We do not do this for things like enum constants, global variables, etc,
1451 // as they do not get snapshotted.
1452 //
1453 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001454 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001455 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001456 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001457 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001458 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001459 // This is to record that a 'const' was actually synthesize and added.
1460 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001461 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Eli Friedman5fdeae12009-03-22 23:00:19 +00001463 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001464 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001465 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001466 }
1467 // If this reference is not in a block or if the referenced variable is
1468 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001469
John McCallf7a1a742009-11-24 19:00:30 +00001470 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001471}
1472
Sebastian Redlcd965b92009-01-18 18:53:16 +00001473Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1474 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001475 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001476
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001478 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001479 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1480 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1481 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001483
Chris Lattnerfa28b302008-01-12 08:14:25 +00001484 // Pre-defined identifiers are of type char[x], where x is the length of the
1485 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Anders Carlsson3a082d82009-09-08 18:24:21 +00001487 Decl *currentDecl = getCurFunctionOrMethodDecl();
1488 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001489 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001490 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001491 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001492
Anders Carlsson773f3972009-09-11 01:22:35 +00001493 QualType ResTy;
1494 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1495 ResTy = Context.DependentTy;
1496 } else {
1497 unsigned Length =
1498 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001499
Anders Carlsson773f3972009-09-11 01:22:35 +00001500 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001501 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001502 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1503 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001504 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001505}
1506
Sebastian Redlcd965b92009-01-18 18:53:16 +00001507Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 llvm::SmallString<16> CharBuffer;
1509 CharBuffer.resize(Tok.getLength());
1510 const char *ThisTokBegin = &CharBuffer[0];
1511 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001512
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1514 Tok.getLocation(), PP);
1515 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001516 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001517
1518 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1519
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001520 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1521 Literal.isWide(),
1522 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001523}
1524
Sebastian Redlcd965b92009-01-18 18:53:16 +00001525Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1526 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1528 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001529 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001530 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001531 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001532 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 }
Ted Kremenek28396602009-01-13 23:19:12 +00001534
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001536 // Add padding so that NumericLiteralParser can overread by one character.
1537 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001539
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 // Get the spelling of the token, which eliminates trigraphs, etc.
1541 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001542
Mike Stump1eb44332009-09-09 15:08:12 +00001543 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 Tok.getLocation(), PP);
1545 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001546 return ExprError();
1547
Chris Lattner5d661452007-08-26 03:42:43 +00001548 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001549
Chris Lattner5d661452007-08-26 03:42:43 +00001550 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001551 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001552 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001553 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001554 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001555 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001556 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001557 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001558
1559 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1560
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001561 // isExact will be set by GetFloatValue().
1562 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001563 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1564 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001565
Chris Lattner5d661452007-08-26 03:42:43 +00001566 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001567 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001568 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001569 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001570
Neil Boothb9449512007-08-29 22:00:19 +00001571 // long long is a C99 feature.
1572 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001573 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001574 Diag(Tok.getLocation(), diag::ext_longlong);
1575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001577 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001578
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 if (Literal.GetIntegerValue(ResultVal)) {
1580 // If this value didn't fit into uintmax_t, warn and force to ull.
1581 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001582 Ty = Context.UnsignedLongLongTy;
1583 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001584 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 } else {
1586 // If this value fits into a ULL, try to figure out what else it fits into
1587 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001588
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1590 // be an unsigned int.
1591 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1592
1593 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001594 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001595 if (!Literal.isLong && !Literal.isLongLong) {
1596 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001597 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001598
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 // Does it fit in a unsigned int?
1600 if (ResultVal.isIntN(IntSize)) {
1601 // Does it fit in a signed int?
1602 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001603 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001605 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001606 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001609
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001611 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001612 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001613
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 // Does it fit in a unsigned long?
1615 if (ResultVal.isIntN(LongSize)) {
1616 // Does it fit in a signed long?
1617 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001618 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001620 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001621 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001623 }
1624
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001626 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001627 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001628
Reid Spencer5f016e22007-07-11 17:01:13 +00001629 // Does it fit in a unsigned long long?
1630 if (ResultVal.isIntN(LongLongSize)) {
1631 // Does it fit in a signed long long?
1632 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001633 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001635 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001636 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 }
1638 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001639
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 // If we still couldn't decide a type, we probably have something that
1641 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001642 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001644 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001645 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001647
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001648 if (ResultVal.getBitWidth() != Width)
1649 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001650 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001651 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001653
Chris Lattner5d661452007-08-26 03:42:43 +00001654 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1655 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001656 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001657 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001658
1659 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001660}
1661
Sebastian Redlcd965b92009-01-18 18:53:16 +00001662Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1663 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001664 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001665 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001666 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001667}
1668
1669/// The UsualUnaryConversions() function is *not* called by this routine.
1670/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001671bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001672 SourceLocation OpLoc,
1673 const SourceRange &ExprRange,
1674 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001675 if (exprType->isDependentType())
1676 return false;
1677
Sebastian Redl5d484e82009-11-23 17:18:46 +00001678 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1679 // the result is the size of the referenced type."
1680 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1681 // result shall be the alignment of the referenced type."
1682 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1683 exprType = Ref->getPointeeType();
1684
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001686 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001687 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001688 if (isSizeof)
1689 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1690 return false;
1691 }
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Chris Lattner1efaa952009-04-24 00:30:45 +00001693 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001694 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001695 Diag(OpLoc, diag::ext_sizeof_void_type)
1696 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001697 return false;
1698 }
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Chris Lattner1efaa952009-04-24 00:30:45 +00001700 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001701 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001702 PDiag(diag::err_alignof_incomplete_type)
1703 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001704 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Chris Lattner1efaa952009-04-24 00:30:45 +00001706 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001707 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001708 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001709 << exprType << isSizeof << ExprRange;
1710 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Chris Lattner1efaa952009-04-24 00:30:45 +00001713 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001714}
1715
Chris Lattner31e21e02009-01-24 20:17:12 +00001716bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1717 const SourceRange &ExprRange) {
1718 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001719
Mike Stump1eb44332009-09-09 15:08:12 +00001720 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001721 if (isa<DeclRefExpr>(E))
1722 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001723
1724 // Cannot know anything else if the expression is dependent.
1725 if (E->isTypeDependent())
1726 return false;
1727
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001728 if (E->getBitField()) {
1729 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1730 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001731 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001732
1733 // Alignment of a field access is always okay, so long as it isn't a
1734 // bit-field.
1735 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001736 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001737 return false;
1738
Chris Lattner31e21e02009-01-24 20:17:12 +00001739 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1740}
1741
Douglas Gregorba498172009-03-13 21:01:28 +00001742/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001743Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00001744Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00001745 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001746 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00001747 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001748 return ExprError();
1749
John McCalla93c9342009-12-07 02:54:59 +00001750 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00001751
Douglas Gregorba498172009-03-13 21:01:28 +00001752 if (!T->isDependentType() &&
1753 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1754 return ExprError();
1755
1756 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00001757 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001758 Context.getSizeType(), OpLoc,
1759 R.getEnd()));
1760}
1761
1762/// \brief Build a sizeof or alignof expression given an expression
1763/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001764Action::OwningExprResult
1765Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001766 bool isSizeOf, SourceRange R) {
1767 // Verify that the operand is valid.
1768 bool isInvalid = false;
1769 if (E->isTypeDependent()) {
1770 // Delay type-checking for type-dependent expressions.
1771 } else if (!isSizeOf) {
1772 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001773 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001774 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1775 isInvalid = true;
1776 } else {
1777 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1778 }
1779
1780 if (isInvalid)
1781 return ExprError();
1782
1783 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1784 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1785 Context.getSizeType(), OpLoc,
1786 R.getEnd()));
1787}
1788
Sebastian Redl05189992008-11-11 17:56:53 +00001789/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1790/// the same for @c alignof and @c __alignof
1791/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001792Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001793Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1794 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001796 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001797
Sebastian Redl05189992008-11-11 17:56:53 +00001798 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00001799 TypeSourceInfo *TInfo;
1800 (void) GetTypeFromParser(TyOrEx, &TInfo);
1801 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001802 }
Sebastian Redl05189992008-11-11 17:56:53 +00001803
Douglas Gregorba498172009-03-13 21:01:28 +00001804 Expr *ArgEx = (Expr *)TyOrEx;
1805 Action::OwningExprResult Result
1806 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1807
1808 if (Result.isInvalid())
1809 DeleteExpr(ArgEx);
1810
1811 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001812}
1813
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001814QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001815 if (V->isTypeDependent())
1816 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Chris Lattnercc26ed72007-08-26 05:39:26 +00001818 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001819 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001820 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Chris Lattnercc26ed72007-08-26 05:39:26 +00001822 // Otherwise they pass through real integer and floating point types here.
1823 if (V->getType()->isArithmeticType())
1824 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Chris Lattnercc26ed72007-08-26 05:39:26 +00001826 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001827 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1828 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001829 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001830}
1831
1832
Reid Spencer5f016e22007-07-11 17:01:13 +00001833
Sebastian Redl0eb23302009-01-19 00:08:26 +00001834Action::OwningExprResult
1835Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1836 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001837 UnaryOperator::Opcode Opc;
1838 switch (Kind) {
1839 default: assert(0 && "Unknown unary op!");
1840 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1841 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1842 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001843
Eli Friedmane4216e92009-11-18 03:38:04 +00001844 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001845}
1846
Sebastian Redl0eb23302009-01-19 00:08:26 +00001847Action::OwningExprResult
1848Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1849 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001850 // Since this might be a postfix expression, get rid of ParenListExprs.
1851 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1852
Sebastian Redl0eb23302009-01-19 00:08:26 +00001853 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1854 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Douglas Gregor337c6b92008-11-19 17:17:41 +00001856 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001857 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1858 Base.release();
1859 Idx.release();
1860 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1861 Context.DependentTy, RLoc));
1862 }
1863
Mike Stump1eb44332009-09-09 15:08:12 +00001864 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001865 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001866 LHSExp->getType()->isEnumeralType() ||
1867 RHSExp->getType()->isRecordType() ||
1868 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001869 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001870 }
1871
Sebastian Redlf322ed62009-10-29 20:17:01 +00001872 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1873}
1874
1875
1876Action::OwningExprResult
1877Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1878 ExprArg Idx, SourceLocation RLoc) {
1879 Expr *LHSExp = static_cast<Expr*>(Base.get());
1880 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1881
Chris Lattner12d9ff62007-07-16 00:14:47 +00001882 // Perform default conversions.
1883 DefaultFunctionArrayConversion(LHSExp);
1884 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001885
Chris Lattner12d9ff62007-07-16 00:14:47 +00001886 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001887
Reid Spencer5f016e22007-07-11 17:01:13 +00001888 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001889 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001890 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001892 Expr *BaseExpr, *IndexExpr;
1893 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001894 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1895 BaseExpr = LHSExp;
1896 IndexExpr = RHSExp;
1897 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001898 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001899 BaseExpr = LHSExp;
1900 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001901 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001902 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001903 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001904 BaseExpr = RHSExp;
1905 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001906 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001907 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001908 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001909 BaseExpr = LHSExp;
1910 IndexExpr = RHSExp;
1911 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001912 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001913 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001914 // Handle the uncommon case of "123[Ptr]".
1915 BaseExpr = RHSExp;
1916 IndexExpr = LHSExp;
1917 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001918 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001919 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001920 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001921
Chris Lattner12d9ff62007-07-16 00:14:47 +00001922 // FIXME: need to deal with const...
1923 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001924 } else if (LHSTy->isArrayType()) {
1925 // If we see an array that wasn't promoted by
1926 // DefaultFunctionArrayConversion, it must be an array that
1927 // wasn't promoted because of the C90 rule that doesn't
1928 // allow promoting non-lvalue arrays. Warn, then
1929 // force the promotion here.
1930 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1931 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001932 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1933 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001934 LHSTy = LHSExp->getType();
1935
1936 BaseExpr = LHSExp;
1937 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001938 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001939 } else if (RHSTy->isArrayType()) {
1940 // Same as previous, except for 123[f().a] case
1941 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1942 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001943 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1944 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001945 RHSTy = RHSExp->getType();
1946
1947 BaseExpr = RHSExp;
1948 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001949 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001951 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1952 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001953 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001955 if (!(IndexExpr->getType()->isIntegerType() &&
1956 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001957 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1958 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001959
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001960 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001961 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1962 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001963 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1964
Douglas Gregore7450f52009-03-24 19:52:54 +00001965 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001966 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1967 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001968 // incomplete types are not object types.
1969 if (ResultType->isFunctionType()) {
1970 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1971 << ResultType << BaseExpr->getSourceRange();
1972 return ExprError();
1973 }
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Douglas Gregore7450f52009-03-24 19:52:54 +00001975 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001976 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001977 PDiag(diag::err_subscript_incomplete_type)
1978 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001979 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Chris Lattner1efaa952009-04-24 00:30:45 +00001981 // Diagnose bad cases where we step over interface counts.
1982 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1983 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1984 << ResultType << BaseExpr->getSourceRange();
1985 return ExprError();
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Sebastian Redl0eb23302009-01-19 00:08:26 +00001988 Base.release();
1989 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001990 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001991 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001992}
1993
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001994QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001995CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001996 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001997 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001998 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1999 // see FIXME there.
2000 //
2001 // FIXME: This logic can be greatly simplified by splitting it along
2002 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002003 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002004
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002005 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002006 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002007
Mike Stumpeed9cac2009-02-19 03:04:26 +00002008 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002009 // special names that indicate a subset of exactly half the elements are
2010 // to be selected.
2011 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002012
Nate Begeman353417a2009-01-18 01:47:54 +00002013 // This flag determines whether or not CompName has an 's' char prefix,
2014 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002015 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002016
2017 // Check that we've found one of the special components, or that the component
2018 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002019 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002020 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2021 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002022 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002023 do
2024 compStr++;
2025 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002026 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002027 do
2028 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002029 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002030 }
Nate Begeman353417a2009-01-18 01:47:54 +00002031
Mike Stumpeed9cac2009-02-19 03:04:26 +00002032 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002033 // We didn't get to the end of the string. This means the component names
2034 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002035 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2036 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002037 return QualType();
2038 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002039
Nate Begeman353417a2009-01-18 01:47:54 +00002040 // Ensure no component accessor exceeds the width of the vector type it
2041 // operates on.
2042 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002043 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002044
2045 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002046 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002047
2048 while (*compStr) {
2049 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2050 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2051 << baseType << SourceRange(CompLoc);
2052 return QualType();
2053 }
2054 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002055 }
Nate Begeman8a997642008-05-09 06:41:27 +00002056
Nate Begeman353417a2009-01-18 01:47:54 +00002057 // If this is a halving swizzle, verify that the base type has an even
2058 // number of elements.
2059 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002060 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00002061 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00002062 return QualType();
2063 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002064
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002065 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002066 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002067 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002068 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002069 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00002070 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002071 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002072 if (HexSwizzle)
2073 CompSize--;
2074
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002075 if (CompSize == 1)
2076 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002077
Nate Begeman213541a2008-04-18 23:10:10 +00002078 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002079 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002080 // diagostics look bad. We want extended vector types to appear built-in.
2081 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2082 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2083 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002084 }
2085 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002086}
2087
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002088static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002089 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002090 const Selector &Sel,
2091 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Anders Carlsson8f28f992009-08-26 18:25:21 +00002093 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002094 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002095 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002096 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002098 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2099 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002100 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002101 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002102 return D;
2103 }
2104 return 0;
2105}
2106
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002107static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002108 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002109 const Selector &Sel,
2110 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002111 // Check protocols on qualified interfaces.
2112 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002113 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002114 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002115 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002116 GDecl = PD;
2117 break;
2118 }
2119 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002120 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002121 GDecl = OMD;
2122 break;
2123 }
2124 }
2125 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002126 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002127 E = QIdTy->qual_end(); I != E; ++I) {
2128 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002129 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002130 if (GDecl)
2131 return GDecl;
2132 }
2133 }
2134 return GDecl;
2135}
Chris Lattner76a642f2009-02-15 22:43:40 +00002136
John McCall129e2df2009-11-30 22:42:35 +00002137Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002138Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2139 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002140 const CXXScopeSpec &SS,
2141 NamedDecl *FirstQualifierInScope,
2142 DeclarationName Name, SourceLocation NameLoc,
2143 const TemplateArgumentListInfo *TemplateArgs) {
2144 Expr *BaseExpr = Base.takeAs<Expr>();
2145
2146 // Even in dependent contexts, try to diagnose base expressions with
2147 // obviously wrong types, e.g.:
2148 //
2149 // T* t;
2150 // t.f;
2151 //
2152 // In Obj-C++, however, the above expression is valid, since it could be
2153 // accessing the 'f' property if T is an Obj-C interface. The extra check
2154 // allows this, while still reporting an error if T is a struct pointer.
2155 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002156 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002157 if (PT && (!getLangOptions().ObjC1 ||
2158 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002159 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002160 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002161 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002162 return ExprError();
2163 }
2164 }
2165
John McCallaa81e162009-12-01 22:10:20 +00002166 assert(BaseType->isDependentType());
John McCall129e2df2009-11-30 22:42:35 +00002167
2168 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2169 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002170 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002171 IsArrow, OpLoc,
2172 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2173 SS.getRange(),
2174 FirstQualifierInScope,
2175 Name, NameLoc,
2176 TemplateArgs));
2177}
2178
2179/// We know that the given qualified member reference points only to
2180/// declarations which do not belong to the static type of the base
2181/// expression. Diagnose the problem.
2182static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2183 Expr *BaseExpr,
2184 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002185 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002186 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002187 // If this is an implicit member access, use a different set of
2188 // diagnostics.
2189 if (!BaseExpr)
2190 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002191
2192 // FIXME: this is an exceedingly lame diagnostic for some of the more
2193 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002194 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002195 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002196 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002197}
2198
2199// Check whether the declarations we found through a nested-name
2200// specifier in a member expression are actually members of the base
2201// type. The restriction here is:
2202//
2203// C++ [expr.ref]p2:
2204// ... In these cases, the id-expression shall name a
2205// member of the class or of one of its base classes.
2206//
2207// So it's perfectly legitimate for the nested-name specifier to name
2208// an unrelated class, and for us to find an overload set including
2209// decls from classes which are not superclasses, as long as the decl
2210// we actually pick through overload resolution is from a superclass.
2211bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2212 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002213 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002214 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002215 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2216 if (!BaseRT) {
2217 // We can't check this yet because the base type is still
2218 // dependent.
2219 assert(BaseType->isDependentType());
2220 return false;
2221 }
2222 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002223
2224 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002225 // If this is an implicit member reference and we find a
2226 // non-instance member, it's not an error.
2227 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2228 return false;
John McCall129e2df2009-11-30 22:42:35 +00002229
John McCallaa81e162009-12-01 22:10:20 +00002230 // Note that we use the DC of the decl, not the underlying decl.
2231 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2232 while (RecordD->isAnonymousStructOrUnion())
2233 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2234
2235 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2236 MemberRecord.insert(RecordD->getCanonicalDecl());
2237
2238 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2239 return false;
2240 }
2241
John McCall2f841ba2009-12-02 03:53:29 +00002242 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002243 return true;
2244}
2245
2246static bool
2247LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2248 SourceRange BaseRange, const RecordType *RTy,
2249 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2250 RecordDecl *RDecl = RTy->getDecl();
2251 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2252 PDiag(diag::err_typecheck_incomplete_tag)
2253 << BaseRange))
2254 return true;
2255
2256 DeclContext *DC = RDecl;
2257 if (SS.isSet()) {
2258 // If the member name was a qualified-id, look into the
2259 // nested-name-specifier.
2260 DC = SemaRef.computeDeclContext(SS, false);
2261
John McCall2f841ba2009-12-02 03:53:29 +00002262 if (SemaRef.RequireCompleteDeclContext(SS)) {
2263 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2264 << SS.getRange() << DC;
2265 return true;
2266 }
2267
John McCallaa81e162009-12-01 22:10:20 +00002268 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2269
2270 if (!isa<TypeDecl>(DC)) {
2271 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2272 << DC << SS.getRange();
2273 return true;
John McCall129e2df2009-11-30 22:42:35 +00002274 }
2275 }
2276
John McCallaa81e162009-12-01 22:10:20 +00002277 // The record definition is complete, now look up the member.
2278 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002279
2280 return false;
2281}
2282
2283Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002284Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002285 SourceLocation OpLoc, bool IsArrow,
2286 const CXXScopeSpec &SS,
2287 NamedDecl *FirstQualifierInScope,
2288 DeclarationName Name, SourceLocation NameLoc,
2289 const TemplateArgumentListInfo *TemplateArgs) {
2290 Expr *Base = BaseArg.takeAs<Expr>();
2291
John McCall2f841ba2009-12-02 03:53:29 +00002292 if (BaseType->isDependentType() ||
2293 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002294 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002295 IsArrow, OpLoc,
2296 SS, FirstQualifierInScope,
2297 Name, NameLoc,
2298 TemplateArgs);
2299
2300 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002301
John McCallaa81e162009-12-01 22:10:20 +00002302 // Implicit member accesses.
2303 if (!Base) {
2304 QualType RecordTy = BaseType;
2305 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2306 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2307 RecordTy->getAs<RecordType>(),
2308 OpLoc, SS))
2309 return ExprError();
2310
2311 // Explicit member accesses.
2312 } else {
2313 OwningExprResult Result =
2314 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2315 SS, FirstQualifierInScope,
2316 /*ObjCImpDecl*/ DeclPtrTy());
2317
2318 if (Result.isInvalid()) {
2319 Owned(Base);
2320 return ExprError();
2321 }
2322
2323 if (Result.get())
2324 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002325 }
2326
John McCallaa81e162009-12-01 22:10:20 +00002327 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2328 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002329}
2330
2331Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002332Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2333 SourceLocation OpLoc, bool IsArrow,
2334 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002335 LookupResult &R,
2336 const TemplateArgumentListInfo *TemplateArgs) {
2337 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002338 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002339 if (IsArrow) {
2340 assert(BaseType->isPointerType());
2341 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2342 }
2343
2344 NestedNameSpecifier *Qualifier =
2345 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2346 DeclarationName MemberName = R.getLookupName();
2347 SourceLocation MemberLoc = R.getNameLoc();
2348
2349 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002350 return ExprError();
2351
John McCall129e2df2009-11-30 22:42:35 +00002352 if (R.empty()) {
2353 // Rederive where we looked up.
2354 DeclContext *DC = (SS.isSet()
2355 ? computeDeclContext(SS, false)
2356 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002357
John McCall129e2df2009-11-30 22:42:35 +00002358 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002359 << MemberName << DC
2360 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002361 return ExprError();
2362 }
2363
John McCall2f841ba2009-12-02 03:53:29 +00002364 // Diagnose qualified lookups that find only declarations from a
2365 // non-base type. Note that it's okay for lookup to find
2366 // declarations from a non-base type as long as those aren't the
2367 // ones picked by overload resolution.
2368 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002369 return ExprError();
2370
2371 // Construct an unresolved result if we in fact got an unresolved
2372 // result.
2373 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002374 bool Dependent =
2375 R.isUnresolvableResult() ||
2376 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002377
2378 UnresolvedMemberExpr *MemExpr
2379 = UnresolvedMemberExpr::Create(Context, Dependent,
2380 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002381 BaseExpr, BaseExprType,
2382 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002383 Qualifier, SS.getRange(),
2384 MemberName, MemberLoc,
2385 TemplateArgs);
2386 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2387 MemExpr->addDecl(*I);
2388
2389 return Owned(MemExpr);
2390 }
2391
2392 assert(R.isSingleResult());
2393 NamedDecl *MemberDecl = R.getFoundDecl();
2394
2395 // FIXME: diagnose the presence of template arguments now.
2396
2397 // If the decl being referenced had an error, return an error for this
2398 // sub-expr without emitting another error, in order to avoid cascading
2399 // error cases.
2400 if (MemberDecl->isInvalidDecl())
2401 return ExprError();
2402
John McCallaa81e162009-12-01 22:10:20 +00002403 // Handle the implicit-member-access case.
2404 if (!BaseExpr) {
2405 // If this is not an instance member, convert to a non-member access.
2406 if (!IsInstanceMember(MemberDecl))
2407 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2408
2409 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2410 }
2411
John McCall129e2df2009-11-30 22:42:35 +00002412 bool ShouldCheckUse = true;
2413 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2414 // Don't diagnose the use of a virtual member function unless it's
2415 // explicitly qualified.
2416 if (MD->isVirtual() && !SS.isSet())
2417 ShouldCheckUse = false;
2418 }
2419
2420 // Check the use of this member.
2421 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2422 Owned(BaseExpr);
2423 return ExprError();
2424 }
2425
2426 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2427 // We may have found a field within an anonymous union or struct
2428 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002429 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2430 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002431 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2432 BaseExpr, OpLoc);
2433
2434 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2435 QualType MemberType = FD->getType();
2436 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2437 MemberType = Ref->getPointeeType();
2438 else {
2439 Qualifiers BaseQuals = BaseType.getQualifiers();
2440 BaseQuals.removeObjCGCAttr();
2441 if (FD->isMutable()) BaseQuals.removeConst();
2442
2443 Qualifiers MemberQuals
2444 = Context.getCanonicalType(MemberType).getQualifiers();
2445
2446 Qualifiers Combined = BaseQuals + MemberQuals;
2447 if (Combined != MemberQuals)
2448 MemberType = Context.getQualifiedType(MemberType, Combined);
2449 }
2450
2451 MarkDeclarationReferenced(MemberLoc, FD);
2452 if (PerformObjectMemberConversion(BaseExpr, FD))
2453 return ExprError();
2454 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2455 FD, MemberLoc, MemberType));
2456 }
2457
2458 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2459 MarkDeclarationReferenced(MemberLoc, Var);
2460 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2461 Var, MemberLoc,
2462 Var->getType().getNonReferenceType()));
2463 }
2464
2465 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2466 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2467 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2468 MemberFn, MemberLoc,
2469 MemberFn->getType()));
2470 }
2471
2472 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2473 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2474 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2475 Enum, MemberLoc, Enum->getType()));
2476 }
2477
2478 Owned(BaseExpr);
2479
2480 if (isa<TypeDecl>(MemberDecl))
2481 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2482 << MemberName << int(IsArrow));
2483
2484 // We found a declaration kind that we didn't expect. This is a
2485 // generic error message that tells the user that she can't refer
2486 // to this member with '.' or '->'.
2487 return ExprError(Diag(MemberLoc,
2488 diag::err_typecheck_member_reference_unknown)
2489 << MemberName << int(IsArrow));
2490}
2491
2492/// Look up the given member of the given non-type-dependent
2493/// expression. This can return in one of two ways:
2494/// * If it returns a sentinel null-but-valid result, the caller will
2495/// assume that lookup was performed and the results written into
2496/// the provided structure. It will take over from there.
2497/// * Otherwise, the returned expression will be produced in place of
2498/// an ordinary member expression.
2499///
2500/// The ObjCImpDecl bit is a gross hack that will need to be properly
2501/// fixed for ObjC++.
2502Sema::OwningExprResult
2503Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002504 bool &IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002505 const CXXScopeSpec &SS,
2506 NamedDecl *FirstQualifierInScope,
2507 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002508 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Steve Naroff3cc4af82007-12-16 21:42:28 +00002510 // Perform default conversions.
2511 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002512
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002513 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002514 assert(!BaseType->isDependentType());
2515
2516 DeclarationName MemberName = R.getLookupName();
2517 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002518
2519 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002520 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002521 // function. Suggest the addition of those parentheses, build the
2522 // call, and continue on.
2523 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2524 if (const FunctionProtoType *Fun
2525 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2526 QualType ResultTy = Fun->getResultType();
2527 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002528 ((!IsArrow && ResultTy->isRecordType()) ||
2529 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002530 ResultTy->getAs<PointerType>()->getPointeeType()
2531 ->isRecordType()))) {
2532 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2533 Diag(Loc, diag::err_member_reference_needs_call)
2534 << QualType(Fun, 0)
2535 << CodeModificationHint::CreateInsertion(Loc, "()");
2536
2537 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002538 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002539 MultiExprArg(*this, 0, 0), 0, Loc);
2540 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002541 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002542
2543 BaseExpr = NewBase.takeAs<Expr>();
2544 DefaultFunctionArrayConversion(BaseExpr);
2545 BaseType = BaseExpr->getType();
2546 }
2547 }
2548 }
2549
David Chisnall0f436562009-08-17 16:35:33 +00002550 // If this is an Objective-C pseudo-builtin and a definition is provided then
2551 // use that.
2552 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002553 if (IsArrow) {
2554 // Handle the following exceptional case PObj->isa.
2555 if (const ObjCObjectPointerType *OPT =
2556 BaseType->getAs<ObjCObjectPointerType>()) {
2557 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2558 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002559 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2560 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002561 }
2562 }
David Chisnall0f436562009-08-17 16:35:33 +00002563 // We have an 'id' type. Rather than fall through, we check if this
2564 // is a reference to 'isa'.
2565 if (BaseType != Context.ObjCIdRedefinitionType) {
2566 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002567 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002568 }
David Chisnall0f436562009-08-17 16:35:33 +00002569 }
John McCall129e2df2009-11-30 22:42:35 +00002570
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002571 // If this is an Objective-C pseudo-builtin and a definition is provided then
2572 // use that.
2573 if (Context.isObjCSelType(BaseType)) {
2574 // We have an 'SEL' type. Rather than fall through, we check if this
2575 // is a reference to 'sel_id'.
2576 if (BaseType != Context.ObjCSelRedefinitionType) {
2577 BaseType = Context.ObjCSelRedefinitionType;
2578 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2579 }
2580 }
John McCall129e2df2009-11-30 22:42:35 +00002581
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002582 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002583
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002584 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002585 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002586 // Also must look for a getter name which uses property syntax.
2587 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2588 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2589 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2590 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2591 ObjCMethodDecl *Getter;
2592 // FIXME: need to also look locally in the implementation.
2593 if ((Getter = IFace->lookupClassMethod(Sel))) {
2594 // Check the use of this method.
2595 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2596 return ExprError();
2597 }
2598 // If we found a getter then this may be a valid dot-reference, we
2599 // will look for the matching setter, in case it is needed.
2600 Selector SetterSel =
2601 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2602 PP.getSelectorTable(), Member);
2603 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2604 if (!Setter) {
2605 // If this reference is in an @implementation, also check for 'private'
2606 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002607 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002608 }
2609 // Look through local category implementations associated with the class.
2610 if (!Setter)
2611 Setter = IFace->getCategoryClassMethod(SetterSel);
2612
2613 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2614 return ExprError();
2615
2616 if (Getter || Setter) {
2617 QualType PType;
2618
2619 if (Getter)
2620 PType = Getter->getResultType();
2621 else
2622 // Get the expression type from Setter's incoming parameter.
2623 PType = (*(Setter->param_end() -1))->getType();
2624 // FIXME: we must check that the setter has property type.
2625 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2626 PType,
2627 Setter, MemberLoc, BaseExpr));
2628 }
2629 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2630 << MemberName << BaseType);
2631 }
2632 }
2633
2634 if (BaseType->isObjCClassType() &&
2635 BaseType != Context.ObjCClassRedefinitionType) {
2636 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002637 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002638 }
Mike Stump1eb44332009-09-09 15:08:12 +00002639
John McCall129e2df2009-11-30 22:42:35 +00002640 if (IsArrow) {
2641 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002642 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002643 else if (BaseType->isObjCObjectPointerType())
2644 ;
John McCall812c1542009-12-07 22:46:59 +00002645 else if (BaseType->isRecordType()) {
2646 // Recover from arrow accesses to records, e.g.:
2647 // struct MyRecord foo;
2648 // foo->bar
2649 // This is actually well-formed in C++ if MyRecord has an
2650 // overloaded operator->, but that should have been dealt with
2651 // by now.
2652 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2653 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2654 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2655 IsArrow = false;
2656 } else {
John McCall129e2df2009-11-30 22:42:35 +00002657 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2658 << BaseType << BaseExpr->getSourceRange();
2659 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002660 }
John McCall812c1542009-12-07 22:46:59 +00002661 } else {
2662 // Recover from dot accesses to pointers, e.g.:
2663 // type *foo;
2664 // foo.bar
2665 // This is actually well-formed in two cases:
2666 // - 'type' is an Objective C type
2667 // - 'bar' is a pseudo-destructor name which happens to refer to
2668 // the appropriate pointer type
2669 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2670 const PointerType *PT = BaseType->getAs<PointerType>();
2671 if (PT && PT->getPointeeType()->isRecordType()) {
2672 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2673 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2674 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2675 BaseType = PT->getPointeeType();
2676 IsArrow = true;
2677 }
2678 }
John McCall129e2df2009-11-30 22:42:35 +00002679 }
John McCall812c1542009-12-07 22:46:59 +00002680
John McCall129e2df2009-11-30 22:42:35 +00002681 // Handle field access to simple records. This also handles access
2682 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002683 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002684 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2685 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002686 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002687 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002688 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002689
Douglas Gregora71d8192009-09-04 17:36:40 +00002690 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2691 // into a record type was handled above, any destructor we see here is a
2692 // pseudo-destructor.
2693 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2694 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002695 // The left hand side of the dot operator shall be of scalar type. The
2696 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002697 // type.
2698 if (!BaseType->isScalarType())
2699 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2700 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002701
Douglas Gregora71d8192009-09-04 17:36:40 +00002702 // [...] The type designated by the pseudo-destructor-name shall be the
2703 // same as the object type.
2704 if (!MemberName.getCXXNameType()->isDependentType() &&
2705 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2706 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2707 << BaseType << MemberName.getCXXNameType()
2708 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002709
2710 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002711 // the form
2712 //
Mike Stump1eb44332009-09-09 15:08:12 +00002713 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2714 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002715 // shall designate the same scalar type.
2716 //
2717 // FIXME: DPG can't see any way to trigger this particular clause, so it
2718 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Douglas Gregora71d8192009-09-04 17:36:40 +00002720 // FIXME: We've lost the precise spelling of the type by going through
2721 // DeclarationName. Can we do better?
2722 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002723 IsArrow, OpLoc,
2724 (NestedNameSpecifier *) SS.getScopeRep(),
2725 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002726 MemberName.getCXXNameType(),
2727 MemberLoc));
2728 }
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Chris Lattnera38e6b12008-07-21 04:59:05 +00002730 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2731 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002732 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2733 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002734 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002735 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002736 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002737 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002738 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2739
Steve Naroffc70e8d92009-07-16 00:25:06 +00002740 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2741 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002742 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002743
Steve Naroffc70e8d92009-07-16 00:25:06 +00002744 if (IV) {
2745 // If the decl being referenced had an error, return an error for this
2746 // sub-expr without emitting another error, in order to avoid cascading
2747 // error cases.
2748 if (IV->isInvalidDecl())
2749 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002750
Steve Naroffc70e8d92009-07-16 00:25:06 +00002751 // Check whether we can reference this field.
2752 if (DiagnoseUseOfDecl(IV, MemberLoc))
2753 return ExprError();
2754 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2755 IV->getAccessControl() != ObjCIvarDecl::Package) {
2756 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2757 if (ObjCMethodDecl *MD = getCurMethodDecl())
2758 ClassOfMethodDecl = MD->getClassInterface();
2759 else if (ObjCImpDecl && getCurFunctionDecl()) {
2760 // Case of a c-function declared inside an objc implementation.
2761 // FIXME: For a c-style function nested inside an objc implementation
2762 // class, there is no implementation context available, so we pass
2763 // down the context as argument to this routine. Ideally, this context
2764 // need be passed down in the AST node and somehow calculated from the
2765 // AST for a function decl.
2766 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002767 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002768 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2769 ClassOfMethodDecl = IMPD->getClassInterface();
2770 else if (ObjCCategoryImplDecl* CatImplClass =
2771 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2772 ClassOfMethodDecl = CatImplClass->getClassInterface();
2773 }
Mike Stump1eb44332009-09-09 15:08:12 +00002774
2775 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2776 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002777 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002778 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002779 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002780 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2781 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002782 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002783 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002784 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002785
2786 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2787 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002788 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002789 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002790 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002791 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002792 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002793 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002794 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002795 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002796 if (!IsArrow && (BaseType->isObjCIdType() ||
2797 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002798 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002799 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Steve Naroff14108da2009-07-10 23:34:53 +00002801 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002802 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002803 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2804 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2805 // Check the use of this declaration
2806 if (DiagnoseUseOfDecl(PD, MemberLoc))
2807 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002808
Steve Naroff14108da2009-07-10 23:34:53 +00002809 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2810 MemberLoc, BaseExpr));
2811 }
2812 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2813 // Check the use of this method.
2814 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2815 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Steve Naroff14108da2009-07-10 23:34:53 +00002817 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002818 OMD->getResultType(),
2819 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002820 NULL, 0));
2821 }
2822 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002823
Steve Naroff14108da2009-07-10 23:34:53 +00002824 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002825 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002826 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002827 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2828 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002829 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00002830 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00002831 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2832 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002833 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002834
Daniel Dunbar2307d312008-09-03 01:05:41 +00002835 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002836 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002837 // Check whether we can reference this property.
2838 if (DiagnoseUseOfDecl(PD, MemberLoc))
2839 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002840 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002841 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002842 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002843 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2844 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002845 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002846 MemberLoc, BaseExpr));
2847 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002848 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002849 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2850 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002851 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002852 // Check whether we can reference this property.
2853 if (DiagnoseUseOfDecl(PD, MemberLoc))
2854 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002855
Steve Naroff6ece14c2009-01-21 00:14:39 +00002856 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002857 MemberLoc, BaseExpr));
2858 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002859 // If that failed, look for an "implicit" property by seeing if the nullary
2860 // selector is implemented.
2861
2862 // FIXME: The logic for looking up nullary and unary selectors should be
2863 // shared with the code in ActOnInstanceMessage.
2864
Anders Carlsson8f28f992009-08-26 18:25:21 +00002865 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002866 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002867
Daniel Dunbar2307d312008-09-03 01:05:41 +00002868 // If this reference is in an @implementation, check for 'private' methods.
2869 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002870 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002871
Steve Naroff7692ed62008-10-22 19:16:27 +00002872 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002873 if (!Getter)
2874 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002875 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002876 // Check if we can reference this property.
2877 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2878 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002879 }
2880 // If we found a getter then this may be a valid dot-reference, we
2881 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002882 Selector SetterSel =
2883 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002884 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002885 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002886 if (!Setter) {
2887 // If this reference is in an @implementation, also check for 'private'
2888 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002889 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002890 }
2891 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002892 if (!Setter)
2893 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002894
Steve Naroff1ca66942009-03-11 13:48:17 +00002895 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2896 return ExprError();
2897
2898 if (Getter || Setter) {
2899 QualType PType;
2900
2901 if (Getter)
2902 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002903 else
2904 // Get the expression type from Setter's incoming parameter.
2905 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002906 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002907 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002908 Setter, MemberLoc, BaseExpr));
2909 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002910 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002911 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002912 }
Mike Stump1eb44332009-09-09 15:08:12 +00002913
Steve Narofff242b1b2009-07-24 17:54:45 +00002914 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00002915 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002916 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002917 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002918 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002919 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00002920
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002921 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002922 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002923 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002924 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2925 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002926 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002927 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002928 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002929 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002930
Douglas Gregor214f31a2009-03-27 06:00:30 +00002931 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2932 << BaseType << BaseExpr->getSourceRange();
2933
Douglas Gregor214f31a2009-03-27 06:00:30 +00002934 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002935}
2936
John McCall129e2df2009-11-30 22:42:35 +00002937static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2938 SourceLocation NameLoc,
2939 Sema::ExprArg MemExpr) {
2940 Expr *E = (Expr *) MemExpr.get();
2941 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2942 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002943 << isa<CXXPseudoDestructorExpr>(E)
2944 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2945
John McCall129e2df2009-11-30 22:42:35 +00002946 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2947 move(MemExpr),
2948 /*LPLoc*/ ExpectedLParenLoc,
2949 Sema::MultiExprArg(SemaRef, 0, 0),
2950 /*CommaLocs*/ 0,
2951 /*RPLoc*/ ExpectedLParenLoc);
2952}
2953
2954/// The main callback when the parser finds something like
2955/// expression . [nested-name-specifier] identifier
2956/// expression -> [nested-name-specifier] identifier
2957/// where 'identifier' encompasses a fairly broad spectrum of
2958/// possibilities, including destructor and operator references.
2959///
2960/// \param OpKind either tok::arrow or tok::period
2961/// \param HasTrailingLParen whether the next token is '(', which
2962/// is used to diagnose mis-uses of special members that can
2963/// only be called
2964/// \param ObjCImpDecl the current ObjC @implementation decl;
2965/// this is an ugly hack around the fact that ObjC @implementations
2966/// aren't properly put in the context chain
2967Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
2968 SourceLocation OpLoc,
2969 tok::TokenKind OpKind,
2970 const CXXScopeSpec &SS,
2971 UnqualifiedId &Id,
2972 DeclPtrTy ObjCImpDecl,
2973 bool HasTrailingLParen) {
2974 if (SS.isSet() && SS.isInvalid())
2975 return ExprError();
2976
2977 TemplateArgumentListInfo TemplateArgsBuffer;
2978
2979 // Decompose the name into its component parts.
2980 DeclarationName Name;
2981 SourceLocation NameLoc;
2982 const TemplateArgumentListInfo *TemplateArgs;
2983 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
2984 Name, NameLoc, TemplateArgs);
2985
2986 bool IsArrow = (OpKind == tok::arrow);
2987
2988 NamedDecl *FirstQualifierInScope
2989 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
2990 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
2991
2992 // This is a postfix expression, so get rid of ParenListExprs.
2993 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
2994
2995 Expr *Base = BaseArg.takeAs<Expr>();
2996 OwningExprResult Result(*this);
2997 if (Base->getType()->isDependentType()) {
John McCallaa81e162009-12-01 22:10:20 +00002998 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00002999 IsArrow, OpLoc,
3000 SS, FirstQualifierInScope,
3001 Name, NameLoc,
3002 TemplateArgs);
3003 } else {
3004 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3005 if (TemplateArgs) {
3006 // Re-use the lookup done for the template name.
3007 DecomposeTemplateName(R, Id);
3008 } else {
3009 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3010 SS, FirstQualifierInScope,
3011 ObjCImpDecl);
3012
3013 if (Result.isInvalid()) {
3014 Owned(Base);
3015 return ExprError();
3016 }
3017
3018 if (Result.get()) {
3019 // The only way a reference to a destructor can be used is to
3020 // immediately call it, which falls into this case. If the
3021 // next token is not a '(', produce a diagnostic and build the
3022 // call now.
3023 if (!HasTrailingLParen &&
3024 Id.getKind() == UnqualifiedId::IK_DestructorName)
3025 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3026
3027 return move(Result);
3028 }
3029 }
3030
John McCallaa81e162009-12-01 22:10:20 +00003031 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3032 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003033 }
3034
3035 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003036}
3037
Anders Carlsson56c5e332009-08-25 03:49:14 +00003038Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3039 FunctionDecl *FD,
3040 ParmVarDecl *Param) {
3041 if (Param->hasUnparsedDefaultArg()) {
3042 Diag (CallLoc,
3043 diag::err_use_of_default_argument_to_function_declared_later) <<
3044 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003045 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003046 diag::note_default_argument_declared_here);
3047 } else {
3048 if (Param->hasUninstantiatedDefaultArg()) {
3049 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3050
3051 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00003052 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003053
Mike Stump1eb44332009-09-09 15:08:12 +00003054 InstantiatingTemplate Inst(*this, CallLoc, Param,
3055 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003056 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003057
John McCallce3ff2b2009-08-25 22:02:44 +00003058 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003059 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003060 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003061
3062 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00003063 /*FIXME:EqualLoc*/
3064 UninstExpr->getSourceRange().getBegin()))
3065 return ExprError();
3066 }
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Anders Carlsson56c5e332009-08-25 03:49:14 +00003068 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00003069
Anders Carlsson56c5e332009-08-25 03:49:14 +00003070 // If the default expression creates temporaries, we need to
3071 // push them to the current stack of expression temporaries so they'll
3072 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00003073 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00003074 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003075 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00003076 "Can't destroy temporaries in a default argument expr!");
3077 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
3078 ExprTemporaries.push_back(E->getTemporary(I));
3079 }
3080 }
3081
3082 // We already type-checked the argument, so we know it works.
3083 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3084}
3085
Douglas Gregor88a35142008-12-22 05:46:06 +00003086/// ConvertArgumentsForCall - Converts the arguments specified in
3087/// Args/NumArgs to the parameter types of the function FDecl with
3088/// function prototype Proto. Call is the call expression itself, and
3089/// Fn is the function expression. For a C++ member function, this
3090/// routine does not attempt to convert the object argument. Returns
3091/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003092bool
3093Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003094 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003095 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003096 Expr **Args, unsigned NumArgs,
3097 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003098 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003099 // assignment, to the types of the corresponding parameter, ...
3100 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003101 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003102
Douglas Gregor88a35142008-12-22 05:46:06 +00003103 // If too few arguments are available (and we don't have default
3104 // arguments for the remaining parameters), don't make the call.
3105 if (NumArgs < NumArgsInProto) {
3106 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3107 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3108 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003109 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003110 }
3111
3112 // If too many are passed and not variadic, error on the extras and drop
3113 // them.
3114 if (NumArgs > NumArgsInProto) {
3115 if (!Proto->isVariadic()) {
3116 Diag(Args[NumArgsInProto]->getLocStart(),
3117 diag::err_typecheck_call_too_many_args)
3118 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3119 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3120 Args[NumArgs-1]->getLocEnd());
3121 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003122 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003123 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003124 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003125 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003126 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003127 VariadicCallType CallType =
3128 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3129 if (Fn->getType()->isBlockPointerType())
3130 CallType = VariadicBlock; // Block
3131 else if (isa<MemberExpr>(Fn))
3132 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003133 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003134 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003135 if (Invalid)
3136 return true;
3137 unsigned TotalNumArgs = AllArgs.size();
3138 for (unsigned i = 0; i < TotalNumArgs; ++i)
3139 Call->setArg(i, AllArgs[i]);
3140
3141 return false;
3142}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003143
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003144bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3145 FunctionDecl *FDecl,
3146 const FunctionProtoType *Proto,
3147 unsigned FirstProtoArg,
3148 Expr **Args, unsigned NumArgs,
3149 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003150 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003151 unsigned NumArgsInProto = Proto->getNumArgs();
3152 unsigned NumArgsToCheck = NumArgs;
3153 bool Invalid = false;
3154 if (NumArgs != NumArgsInProto)
3155 // Use default arguments for missing arguments
3156 NumArgsToCheck = NumArgsInProto;
3157 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003158 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003159 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003160 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003161
Douglas Gregor88a35142008-12-22 05:46:06 +00003162 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003163 if (ArgIx < NumArgs) {
3164 Arg = Args[ArgIx++];
3165
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003166 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3167 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003168 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003169 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003170 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003171
Douglas Gregor61366e92008-12-24 00:01:03 +00003172 // Pass the argument.
3173 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3174 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00003175
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00003176 if (!ProtoArgType->isReferenceType())
3177 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003178 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003179 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003180
Mike Stump1eb44332009-09-09 15:08:12 +00003181 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003182 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003183 if (ArgExpr.isInvalid())
3184 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003185
Anders Carlsson56c5e332009-08-25 03:49:14 +00003186 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003187 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003188 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003189 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003190
Douglas Gregor88a35142008-12-22 05:46:06 +00003191 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003192 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003193 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003194 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003195 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003196 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003197 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003198 }
3199 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003200 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003201}
3202
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003203/// \brief "Deconstruct" the function argument of a call expression to find
3204/// the underlying declaration (if any), the name of the called function,
3205/// whether argument-dependent lookup is available, whether it has explicit
3206/// template arguments, etc.
3207void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCallba135432009-11-21 08:51:07 +00003208 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003209 DeclarationName &Name,
3210 NestedNameSpecifier *&Qualifier,
3211 SourceRange &QualifierRange,
3212 bool &ArgumentDependentLookup,
John McCall7453ed42009-11-22 00:44:51 +00003213 bool &Overloaded,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003214 bool &HasExplicitTemplateArguments,
John McCalld5532b62009-11-23 01:53:49 +00003215 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003216 // Set defaults for all of the output parameters.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003217 Name = DeclarationName();
3218 Qualifier = 0;
3219 QualifierRange = SourceRange();
John McCallf7a1a742009-11-24 19:00:30 +00003220 ArgumentDependentLookup = false;
John McCall7453ed42009-11-22 00:44:51 +00003221 Overloaded = false;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003222 HasExplicitTemplateArguments = false;
John McCall7453ed42009-11-22 00:44:51 +00003223
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003224 // If we're directly calling a function, get the appropriate declaration.
3225 // Also, in C++, keep track of whether we should perform argument-dependent
3226 // lookup and whether there were any explicitly-specified template arguments.
3227 while (true) {
3228 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
3229 FnExpr = IcExpr->getSubExpr();
3230 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003231 FnExpr = PExpr->getSubExpr();
3232 } else if (isa<UnaryOperator>(FnExpr) &&
3233 cast<UnaryOperator>(FnExpr)->getOpcode()
3234 == UnaryOperator::AddrOf) {
3235 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003236 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00003237 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
3238 ArgumentDependentLookup = false;
3239 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregora2813ce2009-10-23 18:54:35 +00003240 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003241 break;
John McCallba135432009-11-21 08:51:07 +00003242 } else if (UnresolvedLookupExpr *UnresLookup
3243 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
3244 Name = UnresLookup->getName();
3245 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
3246 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall7453ed42009-11-22 00:44:51 +00003247 Overloaded = UnresLookup->isOverloaded();
John McCallba135432009-11-21 08:51:07 +00003248 if ((Qualifier = UnresLookup->getQualifier()))
3249 QualifierRange = UnresLookup->getQualifierRange();
John McCallf7a1a742009-11-24 19:00:30 +00003250 if (UnresLookup->hasExplicitTemplateArgs()) {
3251 HasExplicitTemplateArguments = true;
3252 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003253 }
3254 break;
3255 } else {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003256 break;
3257 }
3258 }
3259}
3260
Steve Narofff69936d2007-09-16 03:34:24 +00003261/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003262/// This provides the location of the left/right parens and a list of comma
3263/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003264Action::OwningExprResult
3265Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3266 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003267 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003268 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003269
3270 // Since this might be a postfix expression, get rid of ParenListExprs.
3271 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003273 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003274 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003275 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003276
Douglas Gregor88a35142008-12-22 05:46:06 +00003277 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003278 // If this is a pseudo-destructor expression, build the call immediately.
3279 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3280 if (NumArgs > 0) {
3281 // Pseudo-destructor calls should not have any arguments.
3282 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3283 << CodeModificationHint::CreateRemoval(
3284 SourceRange(Args[0]->getLocStart(),
3285 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003286
Douglas Gregora71d8192009-09-04 17:36:40 +00003287 for (unsigned I = 0; I != NumArgs; ++I)
3288 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Douglas Gregora71d8192009-09-04 17:36:40 +00003290 NumArgs = 0;
3291 }
Mike Stump1eb44332009-09-09 15:08:12 +00003292
Douglas Gregora71d8192009-09-04 17:36:40 +00003293 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3294 RParenLoc));
3295 }
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Douglas Gregor17330012009-02-04 15:01:18 +00003297 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003298 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003299 // FIXME: Will need to cache the results of name lookup (including ADL) in
3300 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003301 bool Dependent = false;
3302 if (Fn->isTypeDependent())
3303 Dependent = true;
3304 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3305 Dependent = true;
3306
3307 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003308 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003309 Context.DependentTy, RParenLoc));
3310
3311 // Determine whether this is a call to an object (C++ [over.call.object]).
3312 if (Fn->getType()->isRecordType())
3313 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3314 CommaLocs, RParenLoc));
3315
John McCall129e2df2009-11-30 22:42:35 +00003316 Expr *NakedFn = Fn->IgnoreParens();
3317
3318 // Determine whether this is a call to an unresolved member function.
3319 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3320 // If lookup was unresolved but not dependent (i.e. didn't find
3321 // an unresolved using declaration), it has to be an overloaded
3322 // function set, which means it must contain either multiple
3323 // declarations (all methods or method templates) or a single
3324 // method template.
3325 assert((MemE->getNumDecls() > 1) ||
3326 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003327 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003328
John McCallaa81e162009-12-01 22:10:20 +00003329 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3330 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003331 }
3332
Douglas Gregorfa047642009-02-04 00:32:51 +00003333 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003334 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003335 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003336 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003337 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3338 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003339 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003340
3341 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003342 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003343 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3344 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003345 if (const FunctionProtoType *FPT =
3346 dyn_cast<FunctionProtoType>(BO->getType())) {
3347 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003348
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003349 ExprOwningPtr<CXXMemberCallExpr>
3350 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3351 NumArgs, ResultTy,
3352 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003353
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003354 if (CheckCallReturnType(FPT->getResultType(),
3355 BO->getRHS()->getSourceRange().getBegin(),
3356 TheCall.get(), 0))
3357 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003358
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003359 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3360 RParenLoc))
3361 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003362
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003363 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3364 }
3365 return ExprError(Diag(Fn->getLocStart(),
3366 diag::err_typecheck_call_not_function)
3367 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003368 }
3369 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003370 }
3371
Douglas Gregorfa047642009-02-04 00:32:51 +00003372 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003373 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003374 // lookup and whether there were any explicitly-specified template arguments.
John McCallba135432009-11-21 08:51:07 +00003375 llvm::SmallVector<NamedDecl*,8> Fns;
3376 DeclarationName UnqualifiedName;
John McCall7453ed42009-11-22 00:44:51 +00003377 bool Overloaded;
3378 bool ADL;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003379 bool HasExplicitTemplateArgs = 0;
John McCalld5532b62009-11-23 01:53:49 +00003380 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003381 NestedNameSpecifier *Qualifier = 0;
3382 SourceRange QualifierRange;
John McCallba135432009-11-21 08:51:07 +00003383 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00003384 ADL, Overloaded, HasExplicitTemplateArgs,
John McCalld5532b62009-11-23 01:53:49 +00003385 ExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003386
John McCall7453ed42009-11-22 00:44:51 +00003387 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
3388 FunctionDecl *FDecl; // same, if it's known to be a function
John McCallba135432009-11-21 08:51:07 +00003389
John McCall7453ed42009-11-22 00:44:51 +00003390 if (Overloaded || ADL) {
3391#ifndef NDEBUG
3392 if (ADL) {
3393 // To do ADL, we must have found an unqualified name.
3394 assert(UnqualifiedName && "found no unqualified name for ADL");
3395
3396 // We don't perform ADL for implicit declarations of builtins.
3397 // Verify that this was correctly set up.
3398 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
3399 FDecl->getBuiltinID() && FDecl->isImplicit())
3400 assert(0 && "performing ADL for builtin");
3401
3402 // We don't perform ADL in C.
3403 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
3404 }
3405
3406 if (Overloaded) {
3407 // To be overloaded, we must either have multiple functions or
3408 // at least one function template (which is effectively an
3409 // infinite set of functions).
3410 assert((Fns.size() > 1 ||
3411 (Fns.size() == 1 &&
3412 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
3413 && "unrecognized overload situation");
3414 }
3415#endif
3416
3417 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00003418 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall7453ed42009-11-22 00:44:51 +00003419 LParenLoc, Args, NumArgs, CommaLocs,
3420 RParenLoc, ADL);
3421 if (!FDecl)
3422 return ExprError();
3423
3424 Fn = FixOverloadedFunctionReference(Fn, FDecl);
3425
3426 NDecl = FDecl;
3427 } else {
3428 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
3429 if (Fns.empty())
John McCallaa81e162009-12-01 22:10:20 +00003430 NDecl = 0;
John McCall7453ed42009-11-22 00:44:51 +00003431 else {
3432 NDecl = Fns[0];
Douglas Gregorfa047642009-02-04 00:32:51 +00003433 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003434 }
Chris Lattner04421082008-04-08 04:40:51 +00003435
John McCallaa81e162009-12-01 22:10:20 +00003436 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3437}
3438
3439/// BuildCallExpr - Build a call to a resolved expression, i.e. an
3440/// expression not of \p OverloadTy. The expression should
3441/// unary-convert to an expression of function-pointer or
3442/// block-pointer type.
3443///
3444/// \param NDecl the declaration being called, if available
3445Sema::OwningExprResult
3446Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3447 SourceLocation LParenLoc,
3448 Expr **Args, unsigned NumArgs,
3449 SourceLocation RParenLoc) {
3450 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3451
Chris Lattner04421082008-04-08 04:40:51 +00003452 // Promote the function operand.
3453 UsualUnaryConversions(Fn);
3454
Chris Lattner925e60d2007-12-28 05:29:59 +00003455 // Make the call expr early, before semantic checks. This guarantees cleanup
3456 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003457 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3458 Args, NumArgs,
3459 Context.BoolTy,
3460 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003461
Steve Naroffdd972f22008-09-05 22:11:13 +00003462 const FunctionType *FuncT;
3463 if (!Fn->getType()->isBlockPointerType()) {
3464 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3465 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003466 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003467 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003468 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3469 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003470 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003471 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003472 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003473 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003474 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003475 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003476 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3477 << Fn->getType() << Fn->getSourceRange());
3478
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003479 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003480 if (CheckCallReturnType(FuncT->getResultType(),
3481 Fn->getSourceRange().getBegin(), TheCall.get(),
3482 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003483 return ExprError();
3484
Chris Lattner925e60d2007-12-28 05:29:59 +00003485 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003486 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003487
Douglas Gregor72564e72009-02-26 23:50:07 +00003488 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003489 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003490 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003491 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003492 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003493 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003494
Douglas Gregor74734d52009-04-02 15:37:10 +00003495 if (FDecl) {
3496 // Check if we have too few/too many template arguments, based
3497 // on our knowledge of the function definition.
3498 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003499 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003500 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003501 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003502 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3503 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3504 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3505 }
3506 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003507 }
3508
Steve Naroffb291ab62007-08-28 23:30:39 +00003509 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003510 for (unsigned i = 0; i != NumArgs; i++) {
3511 Expr *Arg = Args[i];
3512 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003513 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3514 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003515 PDiag(diag::err_call_incomplete_argument)
3516 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003517 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003518 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003519 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003520 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003521
Douglas Gregor88a35142008-12-22 05:46:06 +00003522 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3523 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003524 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3525 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003526
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003527 // Check for sentinels
3528 if (NDecl)
3529 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Chris Lattner59907c42007-08-10 20:18:51 +00003531 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003532 if (FDecl) {
3533 if (CheckFunctionCall(FDecl, TheCall.get()))
3534 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003535
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003536 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003537 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3538 } else if (NDecl) {
3539 if (CheckBlockCall(NDecl, TheCall.get()))
3540 return ExprError();
3541 }
Chris Lattner59907c42007-08-10 20:18:51 +00003542
Anders Carlssonec74c592009-08-16 03:06:32 +00003543 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003544}
3545
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003546Action::OwningExprResult
3547Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3548 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003549 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003550 //FIXME: Preserve type source info.
3551 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003552 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003553 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003554 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003555
Eli Friedman6223c222008-05-20 05:22:08 +00003556 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003557 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003558 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3559 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003560 } else if (!literalType->isDependentType() &&
3561 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003562 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003563 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003564 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003565 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003566
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003567 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003568 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003569 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003570
Chris Lattner371f2582008-12-04 23:50:19 +00003571 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003572 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003573 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003574 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003575 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003576 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003577 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003578 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003579}
3580
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003581Action::OwningExprResult
3582Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003583 SourceLocation RBraceLoc) {
3584 unsigned NumInit = initlist.size();
3585 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003586
Steve Naroff08d92e42007-09-15 18:49:24 +00003587 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003588 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003589
Mike Stumpeed9cac2009-02-19 03:04:26 +00003590 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003591 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003592 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003593 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003594}
3595
Anders Carlsson82debc72009-10-18 18:12:03 +00003596static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3597 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003598 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003599 return CastExpr::CK_NoOp;
3600
3601 if (SrcTy->hasPointerRepresentation()) {
3602 if (DestTy->hasPointerRepresentation())
3603 return CastExpr::CK_BitCast;
3604 if (DestTy->isIntegerType())
3605 return CastExpr::CK_PointerToIntegral;
3606 }
3607
3608 if (SrcTy->isIntegerType()) {
3609 if (DestTy->isIntegerType())
3610 return CastExpr::CK_IntegralCast;
3611 if (DestTy->hasPointerRepresentation())
3612 return CastExpr::CK_IntegralToPointer;
3613 if (DestTy->isRealFloatingType())
3614 return CastExpr::CK_IntegralToFloating;
3615 }
3616
3617 if (SrcTy->isRealFloatingType()) {
3618 if (DestTy->isRealFloatingType())
3619 return CastExpr::CK_FloatingCast;
3620 if (DestTy->isIntegerType())
3621 return CastExpr::CK_FloatingToIntegral;
3622 }
3623
3624 // FIXME: Assert here.
3625 // assert(false && "Unhandled cast combination!");
3626 return CastExpr::CK_Unknown;
3627}
3628
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003629/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003630bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003631 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003632 CXXMethodDecl *& ConversionDecl,
3633 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003634 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003635 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3636 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003637
Eli Friedman199ea952009-08-15 19:02:19 +00003638 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003639
3640 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3641 // type needs to be scalar.
3642 if (castType->isVoidType()) {
3643 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003644 Kind = CastExpr::CK_ToVoid;
3645 return false;
3646 }
3647
3648 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003649 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003650 (castType->isStructureType() || castType->isUnionType())) {
3651 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003652 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003653 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3654 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003655 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003656 return false;
3657 }
3658
3659 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003660 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003661 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003662 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003663 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003664 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003665 if (Context.hasSameUnqualifiedType(Field->getType(),
3666 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003667 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3668 << castExpr->getSourceRange();
3669 break;
3670 }
3671 }
3672 if (Field == FieldEnd)
3673 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3674 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003675 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003676 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003677 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003678
3679 // Reject any other conversions to non-scalar types.
3680 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3681 << castType << castExpr->getSourceRange();
3682 }
3683
3684 if (!castExpr->getType()->isScalarType() &&
3685 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003686 return Diag(castExpr->getLocStart(),
3687 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003688 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003689 }
3690
Anders Carlsson16a89042009-10-16 05:23:41 +00003691 if (castType->isExtVectorType())
3692 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3693
Anders Carlssonc3516322009-10-16 02:48:28 +00003694 if (castType->isVectorType())
3695 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3696 if (castExpr->getType()->isVectorType())
3697 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3698
3699 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003700 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003701
Anders Carlsson16a89042009-10-16 05:23:41 +00003702 if (isa<ObjCSelectorExpr>(castExpr))
3703 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3704
Anders Carlssonc3516322009-10-16 02:48:28 +00003705 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003706 QualType castExprType = castExpr->getType();
3707 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3708 return Diag(castExpr->getLocStart(),
3709 diag::err_cast_pointer_from_non_pointer_int)
3710 << castExprType << castExpr->getSourceRange();
3711 } else if (!castExpr->getType()->isArithmeticType()) {
3712 if (!castType->isIntegralType() && castType->isArithmeticType())
3713 return Diag(castExpr->getLocStart(),
3714 diag::err_cast_pointer_to_non_pointer_int)
3715 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003716 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003717
3718 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003719 return false;
3720}
3721
Anders Carlssonc3516322009-10-16 02:48:28 +00003722bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3723 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003724 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003725
Anders Carlssona64db8f2007-11-27 05:51:55 +00003726 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003727 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003728 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003729 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003730 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003731 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003732 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003733 } else
3734 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003735 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003736 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003737
Anders Carlssonc3516322009-10-16 02:48:28 +00003738 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003739 return false;
3740}
3741
Anders Carlsson16a89042009-10-16 05:23:41 +00003742bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3743 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003744 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003745
3746 QualType SrcTy = CastExpr->getType();
3747
Nate Begeman9b10da62009-06-27 22:05:55 +00003748 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3749 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003750 if (SrcTy->isVectorType()) {
3751 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3752 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3753 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003754 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003755 return false;
3756 }
3757
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003758 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003759 // conversion will take place first from scalar to elt type, and then
3760 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003761 if (SrcTy->isPointerType())
3762 return Diag(R.getBegin(),
3763 diag::err_invalid_conversion_between_vector_and_scalar)
3764 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003765
3766 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3767 ImpCastExprToType(CastExpr, DestElemTy,
3768 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003769
3770 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003771 return false;
3772}
3773
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003774Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003775Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003776 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003777 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003778
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003779 assert((Ty != 0) && (Op.get() != 0) &&
3780 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003781
Nate Begeman2ef13e52009-08-10 23:49:36 +00003782 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003783 //FIXME: Preserve type source info.
3784 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003785
Nate Begeman2ef13e52009-08-10 23:49:36 +00003786 // If the Expr being casted is a ParenListExpr, handle it specially.
3787 if (isa<ParenListExpr>(castExpr))
3788 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003789 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003790 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003791 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003792 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003793
3794 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003795 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003796 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003797
Anders Carlsson0aebc812009-09-09 21:33:21 +00003798 if (CastArg.isInvalid())
3799 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003800
Anders Carlsson0aebc812009-09-09 21:33:21 +00003801 castExpr = CastArg.takeAs<Expr>();
3802 } else {
3803 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003804 }
Mike Stump1eb44332009-09-09 15:08:12 +00003805
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003806 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003807 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003808 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003809}
3810
Nate Begeman2ef13e52009-08-10 23:49:36 +00003811/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3812/// of comma binary operators.
3813Action::OwningExprResult
3814Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3815 Expr *expr = EA.takeAs<Expr>();
3816 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3817 if (!E)
3818 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003819
Nate Begeman2ef13e52009-08-10 23:49:36 +00003820 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Nate Begeman2ef13e52009-08-10 23:49:36 +00003822 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3823 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3824 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003825
Nate Begeman2ef13e52009-08-10 23:49:36 +00003826 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3827}
3828
3829Action::OwningExprResult
3830Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3831 SourceLocation RParenLoc, ExprArg Op,
3832 QualType Ty) {
3833 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003834
3835 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003836 // then handle it as such.
3837 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3838 if (PE->getNumExprs() == 0) {
3839 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3840 return ExprError();
3841 }
3842
3843 llvm::SmallVector<Expr *, 8> initExprs;
3844 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3845 initExprs.push_back(PE->getExpr(i));
3846
3847 // FIXME: This means that pretty-printing the final AST will produce curly
3848 // braces instead of the original commas.
3849 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003850 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003851 initExprs.size(), RParenLoc);
3852 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003853 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003854 Owned(E));
3855 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003856 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003857 // sequence of BinOp comma operators.
3858 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3859 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3860 }
3861}
3862
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003863Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003864 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003865 MultiExprArg Val,
3866 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003867 unsigned nexprs = Val.size();
3868 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003869 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3870 Expr *expr;
3871 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3872 expr = new (Context) ParenExpr(L, R, exprs[0]);
3873 else
3874 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003875 return Owned(expr);
3876}
3877
Sebastian Redl28507842009-02-26 14:39:58 +00003878/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3879/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003880/// C99 6.5.15
3881QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3882 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003883 // C++ is sufficiently different to merit its own checker.
3884 if (getLangOptions().CPlusPlus)
3885 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3886
John McCallb13c87f2009-11-05 09:23:39 +00003887 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3888
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003889 UsualUnaryConversions(Cond);
3890 UsualUnaryConversions(LHS);
3891 UsualUnaryConversions(RHS);
3892 QualType CondTy = Cond->getType();
3893 QualType LHSTy = LHS->getType();
3894 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003895
Reid Spencer5f016e22007-07-11 17:01:13 +00003896 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003897 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3898 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3899 << CondTy;
3900 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003901 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003902
Chris Lattner70d67a92008-01-06 22:42:25 +00003903 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003904 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3905 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003906
Chris Lattner70d67a92008-01-06 22:42:25 +00003907 // If both operands have arithmetic type, do the usual arithmetic conversions
3908 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003909 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3910 UsualArithmeticConversions(LHS, RHS);
3911 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003912 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003913
Chris Lattner70d67a92008-01-06 22:42:25 +00003914 // If both operands are the same structure or union type, the result is that
3915 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003916 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3917 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003918 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003919 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003920 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003921 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003922 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003923 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003924
Chris Lattner70d67a92008-01-06 22:42:25 +00003925 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003926 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003927 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3928 if (!LHSTy->isVoidType())
3929 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3930 << RHS->getSourceRange();
3931 if (!RHSTy->isVoidType())
3932 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3933 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003934 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3935 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003936 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003937 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003938 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3939 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003940 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003941 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003942 // promote the null to a pointer.
3943 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003944 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003945 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003946 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003947 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003948 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003949 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003950 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003951
3952 // All objective-c pointer type analysis is done here.
3953 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
3954 QuestionLoc);
3955 if (!compositeType.isNull())
3956 return compositeType;
3957
3958
Steve Naroff7154a772009-07-01 14:36:47 +00003959 // Handle block pointer types.
3960 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3961 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3962 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3963 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003964 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3965 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003966 return destType;
3967 }
3968 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003969 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00003970 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003971 }
Steve Naroff7154a772009-07-01 14:36:47 +00003972 // We have 2 block pointer types.
3973 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3974 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003975 return LHSTy;
3976 }
Steve Naroff7154a772009-07-01 14:36:47 +00003977 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003978 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3979 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003980
Steve Naroff7154a772009-07-01 14:36:47 +00003981 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3982 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003983 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003984 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003985 // In this situation, we assume void* type. No especially good
3986 // reason, but this is what gcc does, and we do have to pick
3987 // to get a consistent AST.
3988 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003989 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3990 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003991 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003992 }
Steve Naroff7154a772009-07-01 14:36:47 +00003993 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003994 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3995 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003996 return LHSTy;
3997 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003998
Steve Naroff7154a772009-07-01 14:36:47 +00003999 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4000 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4001 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004002 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4003 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004004
4005 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4006 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4007 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004008 QualType destPointee
4009 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004010 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004011 // Add qualifiers if necessary.
4012 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4013 // Promote to void*.
4014 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004015 return destType;
4016 }
4017 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004018 QualType destPointee
4019 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004020 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004021 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004022 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004023 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004024 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004025 return destType;
4026 }
4027
4028 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4029 // Two identical pointer types are always compatible.
4030 return LHSTy;
4031 }
4032 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4033 rhptee.getUnqualifiedType())) {
4034 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4035 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4036 // In this situation, we assume void* type. No especially good
4037 // reason, but this is what gcc does, and we do have to pick
4038 // to get a consistent AST.
4039 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004040 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4041 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004042 return incompatTy;
4043 }
4044 // The pointer types are compatible.
4045 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4046 // differently qualified versions of compatible types, the result type is
4047 // a pointer to an appropriately qualified version of the *composite*
4048 // type.
4049 // FIXME: Need to calculate the composite type.
4050 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004051 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4052 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004053 return LHSTy;
4054 }
Mike Stump1eb44332009-09-09 15:08:12 +00004055
Steve Naroff7154a772009-07-01 14:36:47 +00004056 // GCC compatibility: soften pointer/integer mismatch.
4057 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4058 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4059 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004060 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004061 return RHSTy;
4062 }
4063 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4064 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4065 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004066 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004067 return LHSTy;
4068 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004069
Chris Lattner70d67a92008-01-06 22:42:25 +00004070 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004071 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4072 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004073 return QualType();
4074}
4075
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004076/// FindCompositeObjCPointerType - Helper method to find composite type of
4077/// two objective-c pointer types of the two input expressions.
4078QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4079 SourceLocation QuestionLoc) {
4080 QualType LHSTy = LHS->getType();
4081 QualType RHSTy = RHS->getType();
4082
4083 // Handle things like Class and struct objc_class*. Here we case the result
4084 // to the pseudo-builtin, because that will be implicitly cast back to the
4085 // redefinition type if an attempt is made to access its fields.
4086 if (LHSTy->isObjCClassType() &&
4087 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4088 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4089 return LHSTy;
4090 }
4091 if (RHSTy->isObjCClassType() &&
4092 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4093 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4094 return RHSTy;
4095 }
4096 // And the same for struct objc_object* / id
4097 if (LHSTy->isObjCIdType() &&
4098 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4099 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4100 return LHSTy;
4101 }
4102 if (RHSTy->isObjCIdType() &&
4103 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4104 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4105 return RHSTy;
4106 }
4107 // And the same for struct objc_selector* / SEL
4108 if (Context.isObjCSelType(LHSTy) &&
4109 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4110 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4111 return LHSTy;
4112 }
4113 if (Context.isObjCSelType(RHSTy) &&
4114 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4115 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4116 return RHSTy;
4117 }
4118 // Check constraints for Objective-C object pointers types.
4119 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4120
4121 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4122 // Two identical object pointer types are always compatible.
4123 return LHSTy;
4124 }
4125 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4126 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4127 QualType compositeType = LHSTy;
4128
4129 // If both operands are interfaces and either operand can be
4130 // assigned to the other, use that type as the composite
4131 // type. This allows
4132 // xxx ? (A*) a : (B*) b
4133 // where B is a subclass of A.
4134 //
4135 // Additionally, as for assignment, if either type is 'id'
4136 // allow silent coercion. Finally, if the types are
4137 // incompatible then make sure to use 'id' as the composite
4138 // type so the result is acceptable for sending messages to.
4139
4140 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4141 // It could return the composite type.
4142 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4143 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4144 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4145 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4146 } else if ((LHSTy->isObjCQualifiedIdType() ||
4147 RHSTy->isObjCQualifiedIdType()) &&
4148 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4149 // Need to handle "id<xx>" explicitly.
4150 // GCC allows qualified id and any Objective-C type to devolve to
4151 // id. Currently localizing to here until clear this should be
4152 // part of ObjCQualifiedIdTypesAreCompatible.
4153 compositeType = Context.getObjCIdType();
4154 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4155 compositeType = Context.getObjCIdType();
4156 } else if (!(compositeType =
4157 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4158 ;
4159 else {
4160 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4161 << LHSTy << RHSTy
4162 << LHS->getSourceRange() << RHS->getSourceRange();
4163 QualType incompatTy = Context.getObjCIdType();
4164 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4165 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4166 return incompatTy;
4167 }
4168 // The object pointer types are compatible.
4169 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4170 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4171 return compositeType;
4172 }
4173 // Check Objective-C object pointer types and 'void *'
4174 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4175 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4176 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4177 QualType destPointee
4178 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4179 QualType destType = Context.getPointerType(destPointee);
4180 // Add qualifiers if necessary.
4181 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4182 // Promote to void*.
4183 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4184 return destType;
4185 }
4186 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4187 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4188 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4189 QualType destPointee
4190 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4191 QualType destType = Context.getPointerType(destPointee);
4192 // Add qualifiers if necessary.
4193 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4194 // Promote to void*.
4195 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4196 return destType;
4197 }
4198 return QualType();
4199}
4200
Steve Narofff69936d2007-09-16 03:34:24 +00004201/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004202/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004203Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4204 SourceLocation ColonLoc,
4205 ExprArg Cond, ExprArg LHS,
4206 ExprArg RHS) {
4207 Expr *CondExpr = (Expr *) Cond.get();
4208 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004209
4210 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4211 // was the condition.
4212 bool isLHSNull = LHSExpr == 0;
4213 if (isLHSNull)
4214 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004215
4216 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004217 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004218 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004219 return ExprError();
4220
4221 Cond.release();
4222 LHS.release();
4223 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004224 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004225 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004226 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004227}
4228
Reid Spencer5f016e22007-07-11 17:01:13 +00004229// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004230// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004231// routine is it effectively iqnores the qualifiers on the top level pointee.
4232// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4233// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004234Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004235Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4236 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004237
David Chisnall0f436562009-08-17 16:35:33 +00004238 if ((lhsType->isObjCClassType() &&
4239 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4240 (rhsType->isObjCClassType() &&
4241 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4242 return Compatible;
4243 }
4244
Reid Spencer5f016e22007-07-11 17:01:13 +00004245 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004246 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4247 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004248
Reid Spencer5f016e22007-07-11 17:01:13 +00004249 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004250 lhptee = Context.getCanonicalType(lhptee);
4251 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004252
Chris Lattner5cf216b2008-01-04 18:04:52 +00004253 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004254
4255 // C99 6.5.16.1p1: This following citation is common to constraints
4256 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4257 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004258 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004259 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004260 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004261
Mike Stumpeed9cac2009-02-19 03:04:26 +00004262 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4263 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004264 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004265 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004266 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004267 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004268
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004269 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004270 assert(rhptee->isFunctionType());
4271 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004272 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004273
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004274 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004275 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004276 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004277
4278 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004279 assert(lhptee->isFunctionType());
4280 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004281 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004282 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004283 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004284 lhptee = lhptee.getUnqualifiedType();
4285 rhptee = rhptee.getUnqualifiedType();
4286 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4287 // Check if the pointee types are compatible ignoring the sign.
4288 // We explicitly check for char so that we catch "char" vs
4289 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004290 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004291 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004292 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004293 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004294
4295 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004296 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004297 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004298 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004299
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004300 if (lhptee == rhptee) {
4301 // Types are compatible ignoring the sign. Qualifier incompatibility
4302 // takes priority over sign incompatibility because the sign
4303 // warning can be disabled.
4304 if (ConvTy != Compatible)
4305 return ConvTy;
4306 return IncompatiblePointerSign;
4307 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004308
4309 // If we are a multi-level pointer, it's possible that our issue is simply
4310 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4311 // the eventual target type is the same and the pointers have the same
4312 // level of indirection, this must be the issue.
4313 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4314 do {
4315 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4316 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4317
4318 lhptee = Context.getCanonicalType(lhptee);
4319 rhptee = Context.getCanonicalType(rhptee);
4320 } while (lhptee->isPointerType() && rhptee->isPointerType());
4321
Douglas Gregora4923eb2009-11-16 21:35:15 +00004322 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004323 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004324 }
4325
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004326 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004327 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004328 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004329 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004330}
4331
Steve Naroff1c7d0672008-09-04 15:10:53 +00004332/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4333/// block pointer types are compatible or whether a block and normal pointer
4334/// are compatible. It is more restrict than comparing two function pointer
4335// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004336Sema::AssignConvertType
4337Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004338 QualType rhsType) {
4339 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004340
Steve Naroff1c7d0672008-09-04 15:10:53 +00004341 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004342 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4343 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004344
Steve Naroff1c7d0672008-09-04 15:10:53 +00004345 // make sure we operate on the canonical type
4346 lhptee = Context.getCanonicalType(lhptee);
4347 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004348
Steve Naroff1c7d0672008-09-04 15:10:53 +00004349 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004350
Steve Naroff1c7d0672008-09-04 15:10:53 +00004351 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004352 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004353 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004354
Eli Friedman26784c12009-06-08 05:08:54 +00004355 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004356 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004357 return ConvTy;
4358}
4359
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004360/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4361/// for assignment compatibility.
4362Sema::AssignConvertType
4363Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4364 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4365 return Compatible;
4366 QualType lhptee =
4367 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4368 QualType rhptee =
4369 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4370 // make sure we operate on the canonical type
4371 lhptee = Context.getCanonicalType(lhptee);
4372 rhptee = Context.getCanonicalType(rhptee);
4373 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4374 return CompatiblePointerDiscardsQualifiers;
4375
4376 if (Context.typesAreCompatible(lhsType, rhsType))
4377 return Compatible;
4378 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4379 return IncompatibleObjCQualifiedId;
4380 return IncompatiblePointer;
4381}
4382
Mike Stumpeed9cac2009-02-19 03:04:26 +00004383/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4384/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004385/// pointers. Here are some objectionable examples that GCC considers warnings:
4386///
4387/// int a, *pint;
4388/// short *pshort;
4389/// struct foo *pfoo;
4390///
4391/// pint = pshort; // warning: assignment from incompatible pointer type
4392/// a = pint; // warning: assignment makes integer from pointer without a cast
4393/// pint = a; // warning: assignment makes pointer from integer without a cast
4394/// pint = pfoo; // warning: assignment from incompatible pointer type
4395///
4396/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004397/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004398///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004399Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004400Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004401 // Get canonical types. We're not formatting these types, just comparing
4402 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004403 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4404 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004405
4406 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004407 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004408
David Chisnall0f436562009-08-17 16:35:33 +00004409 if ((lhsType->isObjCClassType() &&
4410 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4411 (rhsType->isObjCClassType() &&
4412 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4413 return Compatible;
4414 }
4415
Douglas Gregor9d293df2008-10-28 00:22:11 +00004416 // If the left-hand side is a reference type, then we are in a
4417 // (rare!) case where we've allowed the use of references in C,
4418 // e.g., as a parameter type in a built-in function. In this case,
4419 // just make sure that the type referenced is compatible with the
4420 // right-hand side type. The caller is responsible for adjusting
4421 // lhsType so that the resulting expression does not have reference
4422 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004423 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004424 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004425 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004426 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004427 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004428 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4429 // to the same ExtVector type.
4430 if (lhsType->isExtVectorType()) {
4431 if (rhsType->isExtVectorType())
4432 return lhsType == rhsType ? Compatible : Incompatible;
4433 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4434 return Compatible;
4435 }
Mike Stump1eb44332009-09-09 15:08:12 +00004436
Nate Begemanbe2341d2008-07-14 18:02:46 +00004437 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004438 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004439 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004440 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004441 if (getLangOptions().LaxVectorConversions &&
4442 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004443 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004444 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004445 }
4446 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004447 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004448
Chris Lattnere8b3e962008-01-04 23:32:24 +00004449 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004450 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004451
Chris Lattner78eca282008-04-07 06:49:41 +00004452 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004453 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004454 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004455
Chris Lattner78eca282008-04-07 06:49:41 +00004456 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004457 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004458
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004459 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004460 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004461 if (lhsType->isVoidPointerType()) // an exception to the rule.
4462 return Compatible;
4463 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004464 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004465 if (rhsType->getAs<BlockPointerType>()) {
4466 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004467 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004468
4469 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004470 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004471 return Compatible;
4472 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004473 return Incompatible;
4474 }
4475
4476 if (isa<BlockPointerType>(lhsType)) {
4477 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004478 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004479
Steve Naroffb4406862008-09-29 18:10:17 +00004480 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004481 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004482 return Compatible;
4483
Steve Naroff1c7d0672008-09-04 15:10:53 +00004484 if (rhsType->isBlockPointerType())
4485 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004486
Ted Kremenek6217b802009-07-29 21:53:49 +00004487 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004488 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004489 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004490 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004491 return Incompatible;
4492 }
4493
Steve Naroff14108da2009-07-10 23:34:53 +00004494 if (isa<ObjCObjectPointerType>(lhsType)) {
4495 if (rhsType->isIntegerType())
4496 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004497
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004498 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004499 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004500 if (rhsType->isVoidPointerType()) // an exception to the rule.
4501 return Compatible;
4502 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004503 }
4504 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004505 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004506 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004507 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004508 if (RHSPT->getPointeeType()->isVoidType())
4509 return Compatible;
4510 }
4511 // Treat block pointers as objects.
4512 if (rhsType->isBlockPointerType())
4513 return Compatible;
4514 return Incompatible;
4515 }
Chris Lattner78eca282008-04-07 06:49:41 +00004516 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004517 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004518 if (lhsType == Context.BoolTy)
4519 return Compatible;
4520
4521 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004522 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004523
Mike Stumpeed9cac2009-02-19 03:04:26 +00004524 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004525 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004526
4527 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004528 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004529 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004530 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004531 }
Steve Naroff14108da2009-07-10 23:34:53 +00004532 if (isa<ObjCObjectPointerType>(rhsType)) {
4533 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4534 if (lhsType == Context.BoolTy)
4535 return Compatible;
4536
4537 if (lhsType->isIntegerType())
4538 return PointerToInt;
4539
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004540 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004541 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004542 if (lhsType->isVoidPointerType()) // an exception to the rule.
4543 return Compatible;
4544 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004545 }
4546 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004547 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004548 return Compatible;
4549 return Incompatible;
4550 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004551
Chris Lattnerfc144e22008-01-04 23:18:45 +00004552 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004553 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004554 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004555 }
4556 return Incompatible;
4557}
4558
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004559/// \brief Constructs a transparent union from an expression that is
4560/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004561static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004562 QualType UnionType, FieldDecl *Field) {
4563 // Build an initializer list that designates the appropriate member
4564 // of the transparent union.
4565 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4566 &E, 1,
4567 SourceLocation());
4568 Initializer->setType(UnionType);
4569 Initializer->setInitializedFieldInUnion(Field);
4570
4571 // Build a compound literal constructing a value of the transparent
4572 // union type from this initializer list.
4573 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4574 false);
4575}
4576
4577Sema::AssignConvertType
4578Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4579 QualType FromType = rExpr->getType();
4580
Mike Stump1eb44332009-09-09 15:08:12 +00004581 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004582 // transparent_union GCC extension.
4583 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004584 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004585 return Incompatible;
4586
4587 // The field to initialize within the transparent union.
4588 RecordDecl *UD = UT->getDecl();
4589 FieldDecl *InitField = 0;
4590 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004591 for (RecordDecl::field_iterator it = UD->field_begin(),
4592 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004593 it != itend; ++it) {
4594 if (it->getType()->isPointerType()) {
4595 // If the transparent union contains a pointer type, we allow:
4596 // 1) void pointer
4597 // 2) null pointer constant
4598 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004599 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004600 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004601 InitField = *it;
4602 break;
4603 }
Mike Stump1eb44332009-09-09 15:08:12 +00004604
Douglas Gregorce940492009-09-25 04:25:58 +00004605 if (rExpr->isNullPointerConstant(Context,
4606 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004607 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004608 InitField = *it;
4609 break;
4610 }
4611 }
4612
4613 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4614 == Compatible) {
4615 InitField = *it;
4616 break;
4617 }
4618 }
4619
4620 if (!InitField)
4621 return Incompatible;
4622
4623 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4624 return Compatible;
4625}
4626
Chris Lattner5cf216b2008-01-04 18:04:52 +00004627Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004628Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004629 if (getLangOptions().CPlusPlus) {
4630 if (!lhsType->isRecordType()) {
4631 // C++ 5.17p3: If the left operand is not of class type, the
4632 // expression is implicitly converted (C++ 4) to the
4633 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004634 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4635 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004636 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004637 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004638 }
4639
4640 // FIXME: Currently, we fall through and treat C++ classes like C
4641 // structures.
4642 }
4643
Steve Naroff529a4ad2007-11-27 17:58:44 +00004644 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4645 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004646 if ((lhsType->isPointerType() ||
4647 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004648 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004649 && rExpr->isNullPointerConstant(Context,
4650 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004651 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004652 return Compatible;
4653 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004654
Chris Lattner943140e2007-10-16 02:55:40 +00004655 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004656 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004657 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004658 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004659 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004660 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004661 if (!lhsType->isReferenceType())
4662 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004663
Chris Lattner5cf216b2008-01-04 18:04:52 +00004664 Sema::AssignConvertType result =
4665 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004666
Steve Narofff1120de2007-08-24 22:33:52 +00004667 // C99 6.5.16.1p2: The value of the right operand is converted to the
4668 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004669 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4670 // so that we can use references in built-in functions even in C.
4671 // The getNonReferenceType() call makes sure that the resulting expression
4672 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004673 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004674 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4675 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004676 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004677}
4678
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004679QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004680 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004681 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004682 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004683 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004684}
4685
Mike Stumpeed9cac2009-02-19 03:04:26 +00004686inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004687 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004688 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004689 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004690 QualType lhsType =
4691 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4692 QualType rhsType =
4693 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004694
Nate Begemanbe2341d2008-07-14 18:02:46 +00004695 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004696 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004697 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004698
Nate Begemanbe2341d2008-07-14 18:02:46 +00004699 // Handle the case of a vector & extvector type of the same size and element
4700 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004701 if (getLangOptions().LaxVectorConversions) {
4702 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004703 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4704 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004705 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004706 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004707 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004708 }
4709 }
4710 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004711
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004712 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4713 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4714 bool swapped = false;
4715 if (rhsType->isExtVectorType()) {
4716 swapped = true;
4717 std::swap(rex, lex);
4718 std::swap(rhsType, lhsType);
4719 }
Mike Stump1eb44332009-09-09 15:08:12 +00004720
Nate Begemandde25982009-06-28 19:12:57 +00004721 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004722 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004723 QualType EltTy = LV->getElementType();
4724 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4725 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004726 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004727 if (swapped) std::swap(rex, lex);
4728 return lhsType;
4729 }
4730 }
4731 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4732 rhsType->isRealFloatingType()) {
4733 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004734 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004735 if (swapped) std::swap(rex, lex);
4736 return lhsType;
4737 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004738 }
4739 }
Mike Stump1eb44332009-09-09 15:08:12 +00004740
Nate Begemandde25982009-06-28 19:12:57 +00004741 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004742 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004743 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004744 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004745 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004746}
4747
Reid Spencer5f016e22007-07-11 17:01:13 +00004748inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004749 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004750 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004751 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004752
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004753 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004754
Steve Naroffa4332e22007-07-17 00:58:39 +00004755 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004756 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004757 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004758}
4759
4760inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004761 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004762 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4763 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4764 return CheckVectorOperands(Loc, lex, rex);
4765 return InvalidOperands(Loc, lex, rex);
4766 }
Steve Naroff90045e82007-07-13 23:32:42 +00004767
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004768 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004769
Steve Naroffa4332e22007-07-17 00:58:39 +00004770 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004771 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004772 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004773}
4774
4775inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004776 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004777 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4778 QualType compType = CheckVectorOperands(Loc, lex, rex);
4779 if (CompLHSTy) *CompLHSTy = compType;
4780 return compType;
4781 }
Steve Naroff49b45262007-07-13 16:58:59 +00004782
Eli Friedmanab3a8522009-03-28 01:22:36 +00004783 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004784
Reid Spencer5f016e22007-07-11 17:01:13 +00004785 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004786 if (lex->getType()->isArithmeticType() &&
4787 rex->getType()->isArithmeticType()) {
4788 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004789 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004790 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004791
Eli Friedmand72d16e2008-05-18 18:08:51 +00004792 // Put any potential pointer into PExp
4793 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004794 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004795 std::swap(PExp, IExp);
4796
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004797 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Eli Friedmand72d16e2008-05-18 18:08:51 +00004799 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004800 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004801
Chris Lattnerb5f15622009-04-24 23:50:08 +00004802 // Check for arithmetic on pointers to incomplete types.
4803 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004804 if (getLangOptions().CPlusPlus) {
4805 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004806 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004807 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004808 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004809
4810 // GNU extension: arithmetic on pointer to void
4811 Diag(Loc, diag::ext_gnu_void_ptr)
4812 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004813 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004814 if (getLangOptions().CPlusPlus) {
4815 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4816 << lex->getType() << lex->getSourceRange();
4817 return QualType();
4818 }
4819
4820 // GNU extension: arithmetic on pointer to function
4821 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4822 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004823 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004824 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004825 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004826 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004827 PExp->getType()->isObjCObjectPointerType()) &&
4828 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004829 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4830 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004831 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004832 return QualType();
4833 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004834 // Diagnose bad cases where we step over interface counts.
4835 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4836 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4837 << PointeeTy << PExp->getSourceRange();
4838 return QualType();
4839 }
Mike Stump1eb44332009-09-09 15:08:12 +00004840
Eli Friedmanab3a8522009-03-28 01:22:36 +00004841 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004842 QualType LHSTy = Context.isPromotableBitField(lex);
4843 if (LHSTy.isNull()) {
4844 LHSTy = lex->getType();
4845 if (LHSTy->isPromotableIntegerType())
4846 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004847 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004848 *CompLHSTy = LHSTy;
4849 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004850 return PExp->getType();
4851 }
4852 }
4853
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004854 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004855}
4856
Chris Lattnereca7be62008-04-07 05:30:13 +00004857// C99 6.5.6
4858QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004859 SourceLocation Loc, QualType* CompLHSTy) {
4860 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4861 QualType compType = CheckVectorOperands(Loc, lex, rex);
4862 if (CompLHSTy) *CompLHSTy = compType;
4863 return compType;
4864 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004865
Eli Friedmanab3a8522009-03-28 01:22:36 +00004866 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004867
Chris Lattner6e4ab612007-12-09 21:53:25 +00004868 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004869
Chris Lattner6e4ab612007-12-09 21:53:25 +00004870 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004871 if (lex->getType()->isArithmeticType()
4872 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004873 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004874 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004875 }
Mike Stump1eb44332009-09-09 15:08:12 +00004876
Chris Lattner6e4ab612007-12-09 21:53:25 +00004877 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004878 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004879 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004880
Douglas Gregore7450f52009-03-24 19:52:54 +00004881 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004882
Douglas Gregore7450f52009-03-24 19:52:54 +00004883 bool ComplainAboutVoid = false;
4884 Expr *ComplainAboutFunc = 0;
4885 if (lpointee->isVoidType()) {
4886 if (getLangOptions().CPlusPlus) {
4887 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4888 << lex->getSourceRange() << rex->getSourceRange();
4889 return QualType();
4890 }
4891
4892 // GNU C extension: arithmetic on pointer to void
4893 ComplainAboutVoid = true;
4894 } else if (lpointee->isFunctionType()) {
4895 if (getLangOptions().CPlusPlus) {
4896 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004897 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004898 return QualType();
4899 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004900
4901 // GNU C extension: arithmetic on pointer to function
4902 ComplainAboutFunc = lex;
4903 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004904 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004905 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004906 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004907 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004908 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004909
Chris Lattnerb5f15622009-04-24 23:50:08 +00004910 // Diagnose bad cases where we step over interface counts.
4911 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4912 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4913 << lpointee << lex->getSourceRange();
4914 return QualType();
4915 }
Mike Stump1eb44332009-09-09 15:08:12 +00004916
Chris Lattner6e4ab612007-12-09 21:53:25 +00004917 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004918 if (rex->getType()->isIntegerType()) {
4919 if (ComplainAboutVoid)
4920 Diag(Loc, diag::ext_gnu_void_ptr)
4921 << lex->getSourceRange() << rex->getSourceRange();
4922 if (ComplainAboutFunc)
4923 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004924 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004925 << ComplainAboutFunc->getSourceRange();
4926
Eli Friedmanab3a8522009-03-28 01:22:36 +00004927 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004928 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004929 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004930
Chris Lattner6e4ab612007-12-09 21:53:25 +00004931 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004932 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004933 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004934
Douglas Gregore7450f52009-03-24 19:52:54 +00004935 // RHS must be a completely-type object type.
4936 // Handle the GNU void* extension.
4937 if (rpointee->isVoidType()) {
4938 if (getLangOptions().CPlusPlus) {
4939 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4940 << lex->getSourceRange() << rex->getSourceRange();
4941 return QualType();
4942 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004943
Douglas Gregore7450f52009-03-24 19:52:54 +00004944 ComplainAboutVoid = true;
4945 } else if (rpointee->isFunctionType()) {
4946 if (getLangOptions().CPlusPlus) {
4947 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004948 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004949 return QualType();
4950 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004951
4952 // GNU extension: arithmetic on pointer to function
4953 if (!ComplainAboutFunc)
4954 ComplainAboutFunc = rex;
4955 } else if (!rpointee->isDependentType() &&
4956 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004957 PDiag(diag::err_typecheck_sub_ptr_object)
4958 << rex->getSourceRange()
4959 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004960 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004961
Eli Friedman88d936b2009-05-16 13:54:38 +00004962 if (getLangOptions().CPlusPlus) {
4963 // Pointee types must be the same: C++ [expr.add]
4964 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4965 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4966 << lex->getType() << rex->getType()
4967 << lex->getSourceRange() << rex->getSourceRange();
4968 return QualType();
4969 }
4970 } else {
4971 // Pointee types must be compatible C99 6.5.6p3
4972 if (!Context.typesAreCompatible(
4973 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4974 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4975 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4976 << lex->getType() << rex->getType()
4977 << lex->getSourceRange() << rex->getSourceRange();
4978 return QualType();
4979 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004980 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004981
Douglas Gregore7450f52009-03-24 19:52:54 +00004982 if (ComplainAboutVoid)
4983 Diag(Loc, diag::ext_gnu_void_ptr)
4984 << lex->getSourceRange() << rex->getSourceRange();
4985 if (ComplainAboutFunc)
4986 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004987 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004988 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004989
4990 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004991 return Context.getPointerDiffType();
4992 }
4993 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004994
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004995 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004996}
4997
Chris Lattnereca7be62008-04-07 05:30:13 +00004998// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004999QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005000 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005001 // C99 6.5.7p2: Each of the operands shall have integer type.
5002 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005003 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005004
Nate Begeman2207d792009-10-25 02:26:48 +00005005 // Vector shifts promote their scalar inputs to vector type.
5006 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5007 return CheckVectorOperands(Loc, lex, rex);
5008
Chris Lattnerca5eede2007-12-12 05:47:28 +00005009 // Shifts don't perform usual arithmetic conversions, they just do integer
5010 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005011 QualType LHSTy = Context.isPromotableBitField(lex);
5012 if (LHSTy.isNull()) {
5013 LHSTy = lex->getType();
5014 if (LHSTy->isPromotableIntegerType())
5015 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005016 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005017 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005018 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005019
Chris Lattnerca5eede2007-12-12 05:47:28 +00005020 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005021
Ryan Flynnd0439682009-08-07 16:20:20 +00005022 // Sanity-check shift operands
5023 llvm::APSInt Right;
5024 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005025 if (!rex->isValueDependent() &&
5026 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005027 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005028 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5029 else {
5030 llvm::APInt LeftBits(Right.getBitWidth(),
5031 Context.getTypeSize(lex->getType()));
5032 if (Right.uge(LeftBits))
5033 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5034 }
5035 }
5036
Chris Lattnerca5eede2007-12-12 05:47:28 +00005037 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005038 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005039}
5040
John McCall5dbad3d2009-11-06 08:49:08 +00005041/// \brief Implements -Wsign-compare.
5042///
5043/// \param lex the left-hand expression
5044/// \param rex the right-hand expression
5045/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00005046/// \param Equality whether this is an "equality-like" join, which
5047/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00005048void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00005049 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00005050 // Don't warn if we're in an unevaluated context.
Douglas Gregor2afce722009-11-26 00:44:06 +00005051 if (ExprEvalContexts.back().Context == Unevaluated)
John McCall7d62a8f2009-11-06 18:16:06 +00005052 return;
5053
John McCall45aa4552009-11-05 00:40:04 +00005054 QualType lt = lex->getType(), rt = rex->getType();
5055
5056 // Only warn if both operands are integral.
5057 if (!lt->isIntegerType() || !rt->isIntegerType())
5058 return;
5059
Sebastian Redl732429c2009-11-05 21:09:23 +00005060 // If either expression is value-dependent, don't warn. We'll get another
5061 // chance at instantiation time.
5062 if (lex->isValueDependent() || rex->isValueDependent())
5063 return;
5064
John McCall45aa4552009-11-05 00:40:04 +00005065 // The rule is that the signed operand becomes unsigned, so isolate the
5066 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00005067 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00005068 if (lt->isSignedIntegerType()) {
5069 if (rt->isSignedIntegerType()) return;
5070 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00005071 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00005072 } else {
5073 if (!rt->isSignedIntegerType()) return;
5074 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00005075 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00005076 }
5077
John McCall5dbad3d2009-11-06 08:49:08 +00005078 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00005079 // then (1) the result type will be signed and (2) the unsigned
5080 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00005081 // of the comparison will be exact.
5082 if (Context.getIntWidth(signedOperand->getType()) >
5083 Context.getIntWidth(unsignedOperand->getType()))
5084 return;
5085
John McCall45aa4552009-11-05 00:40:04 +00005086 // If the value is a non-negative integer constant, then the
5087 // signed->unsigned conversion won't change it.
5088 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00005089 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00005090 assert(value.isSigned() && "result of signed expression not signed");
5091
5092 if (value.isNonNegative())
5093 return;
5094 }
5095
John McCall5dbad3d2009-11-06 08:49:08 +00005096 if (Equality) {
5097 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00005098 // constant which cannot collide with a overflowed signed operand,
5099 // then reinterpreting the signed operand as unsigned will not
5100 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00005101 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5102 assert(!value.isSigned() && "result of unsigned expression is signed");
5103
5104 // 2's complement: test the top bit.
5105 if (value.isNonNegative())
5106 return;
5107 }
5108 }
5109
John McCallb13c87f2009-11-05 09:23:39 +00005110 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00005111 << lex->getType() << rex->getType()
5112 << lex->getSourceRange() << rex->getSourceRange();
5113}
5114
Douglas Gregor0c6db942009-05-04 06:07:12 +00005115// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005116QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005117 unsigned OpaqueOpc, bool isRelational) {
5118 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5119
Chris Lattner02dd4b12009-12-05 05:40:13 +00005120 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005121 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005122 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005123
John McCall5dbad3d2009-11-06 08:49:08 +00005124 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5125 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005126
Chris Lattnera5937dd2007-08-26 01:18:55 +00005127 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005128 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5129 UsualArithmeticConversions(lex, rex);
5130 else {
5131 UsualUnaryConversions(lex);
5132 UsualUnaryConversions(rex);
5133 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005134 QualType lType = lex->getType();
5135 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005136
Mike Stumpaf199f32009-05-07 18:43:07 +00005137 if (!lType->isFloatingType()
5138 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005139 // For non-floating point types, check for self-comparisons of the form
5140 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5141 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005142 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005143 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005144 Expr *LHSStripped = lex->IgnoreParens();
5145 Expr *RHSStripped = rex->IgnoreParens();
5146 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5147 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005148 if (DRL->getDecl() == DRR->getDecl() &&
5149 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00005150 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00005151
Chris Lattner55660a72009-03-08 19:39:53 +00005152 if (isa<CastExpr>(LHSStripped))
5153 LHSStripped = LHSStripped->IgnoreParenCasts();
5154 if (isa<CastExpr>(RHSStripped))
5155 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005156
Chris Lattner55660a72009-03-08 19:39:53 +00005157 // Warn about comparisons against a string constant (unless the other
5158 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005159 Expr *literalString = 0;
5160 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005161 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005162 !RHSStripped->isNullPointerConstant(Context,
5163 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005164 literalString = lex;
5165 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005166 } else if ((isa<StringLiteral>(RHSStripped) ||
5167 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005168 !LHSStripped->isNullPointerConstant(Context,
5169 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005170 literalString = rex;
5171 literalStringStripped = RHSStripped;
5172 }
5173
5174 if (literalString) {
5175 std::string resultComparison;
5176 switch (Opc) {
5177 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5178 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5179 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5180 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5181 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5182 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5183 default: assert(false && "Invalid comparison operator");
5184 }
5185 Diag(Loc, diag::warn_stringcompare)
5186 << isa<ObjCEncodeExpr>(literalStringStripped)
5187 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00005188 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5189 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5190 "strcmp(")
5191 << CodeModificationHint::CreateInsertion(
5192 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00005193 resultComparison);
5194 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005195 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005196
Douglas Gregor447b69e2008-11-19 03:25:36 +00005197 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005198 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005199
Chris Lattnera5937dd2007-08-26 01:18:55 +00005200 if (isRelational) {
5201 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005202 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005203 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005204 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005205 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005206 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005207
Chris Lattnera5937dd2007-08-26 01:18:55 +00005208 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005209 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005210 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005211
Douglas Gregorce940492009-09-25 04:25:58 +00005212 bool LHSIsNull = lex->isNullPointerConstant(Context,
5213 Expr::NPC_ValueDependentIsNull);
5214 bool RHSIsNull = rex->isNullPointerConstant(Context,
5215 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005216
Chris Lattnera5937dd2007-08-26 01:18:55 +00005217 // All of the following pointer related warnings are GCC extensions, except
5218 // when handling null pointer constants. One day, we can consider making them
5219 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005220 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005221 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005222 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005223 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005224 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005225
Douglas Gregor0c6db942009-05-04 06:07:12 +00005226 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005227 if (LCanPointeeTy == RCanPointeeTy)
5228 return ResultTy;
5229
Douglas Gregor0c6db942009-05-04 06:07:12 +00005230 // C++ [expr.rel]p2:
5231 // [...] Pointer conversions (4.10) and qualification
5232 // conversions (4.4) are performed on pointer operands (or on
5233 // a pointer operand and a null pointer constant) to bring
5234 // them to their composite pointer type. [...]
5235 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005236 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005237 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005238 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005239 if (T.isNull()) {
5240 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5241 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5242 return QualType();
5243 }
5244
Eli Friedman73c39ab2009-10-20 08:27:19 +00005245 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5246 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005247 return ResultTy;
5248 }
Eli Friedman3075e762009-08-23 00:27:47 +00005249 // C99 6.5.9p2 and C99 6.5.8p2
5250 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5251 RCanPointeeTy.getUnqualifiedType())) {
5252 // Valid unless a relational comparison of function pointers
5253 if (isRelational && LCanPointeeTy->isFunctionType()) {
5254 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5255 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5256 }
5257 } else if (!isRelational &&
5258 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5259 // Valid unless comparison between non-null pointer and function pointer
5260 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5261 && !LHSIsNull && !RHSIsNull) {
5262 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5263 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5264 }
5265 } else {
5266 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005267 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005268 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005269 }
Eli Friedman3075e762009-08-23 00:27:47 +00005270 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005271 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005272 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005273 }
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005275 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005276 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005277 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005278 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005279 (lType->isPointerType() ||
5280 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005281 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005282 return ResultTy;
5283 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005284 if (LHSIsNull &&
5285 (rType->isPointerType() ||
5286 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005287 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005288 return ResultTy;
5289 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005290
5291 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005292 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005293 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5294 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005295 // In addition, pointers to members can be compared, or a pointer to
5296 // member and a null pointer constant. Pointer to member conversions
5297 // (4.11) and qualification conversions (4.4) are performed to bring
5298 // them to a common type. If one operand is a null pointer constant,
5299 // the common type is the type of the other operand. Otherwise, the
5300 // common type is a pointer to member type similar (4.4) to the type
5301 // of one of the operands, with a cv-qualification signature (4.4)
5302 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005303 // types.
5304 QualType T = FindCompositePointerType(lex, rex);
5305 if (T.isNull()) {
5306 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5307 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5308 return QualType();
5309 }
Mike Stump1eb44332009-09-09 15:08:12 +00005310
Eli Friedman73c39ab2009-10-20 08:27:19 +00005311 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5312 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005313 return ResultTy;
5314 }
Mike Stump1eb44332009-09-09 15:08:12 +00005315
Douglas Gregor20b3e992009-08-24 17:42:35 +00005316 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005317 if (lType->isNullPtrType() && rType->isNullPtrType())
5318 return ResultTy;
5319 }
Mike Stump1eb44332009-09-09 15:08:12 +00005320
Steve Naroff1c7d0672008-09-04 15:10:53 +00005321 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005322 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005323 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5324 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005325
Steve Naroff1c7d0672008-09-04 15:10:53 +00005326 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005327 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005328 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005329 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005330 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005331 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005332 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005333 }
Steve Naroff59f53942008-09-28 01:11:11 +00005334 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005335 if (!isRelational
5336 && ((lType->isBlockPointerType() && rType->isPointerType())
5337 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005338 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005339 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005340 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005341 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005342 ->getPointeeType()->isVoidType())))
5343 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5344 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005345 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005346 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005347 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005348 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005349
Steve Naroff14108da2009-07-10 23:34:53 +00005350 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005351 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005352 const PointerType *LPT = lType->getAs<PointerType>();
5353 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005354 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005355 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005356 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005357 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005358
Steve Naroffa8069f12008-11-17 19:49:16 +00005359 if (!LPtrToVoid && !RPtrToVoid &&
5360 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005361 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005362 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005363 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005364 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005365 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005366 }
Steve Naroff14108da2009-07-10 23:34:53 +00005367 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005368 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005369 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5370 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005371 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005372 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005373 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005374 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005375 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005376 unsigned DiagID = 0;
5377 if (RHSIsNull) {
5378 if (isRelational)
5379 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5380 } else if (isRelational)
5381 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5382 else
5383 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005384
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005385 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005386 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005387 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005388 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005389 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005390 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005391 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005392 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005393 unsigned DiagID = 0;
5394 if (LHSIsNull) {
5395 if (isRelational)
5396 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5397 } else if (isRelational)
5398 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5399 else
5400 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005401
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005402 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005403 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005404 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005405 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005406 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005407 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005408 }
Steve Naroff39218df2008-09-04 16:56:14 +00005409 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005410 if (!isRelational && RHSIsNull
5411 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005412 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005413 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005414 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005415 if (!isRelational && LHSIsNull
5416 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005417 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005418 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005419 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005420 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005421}
5422
Nate Begemanbe2341d2008-07-14 18:02:46 +00005423/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005424/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005425/// like a scalar comparison, a vector comparison produces a vector of integer
5426/// types.
5427QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005428 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005429 bool isRelational) {
5430 // Check to make sure we're operating on vectors of the same type and width,
5431 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005432 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005433 if (vType.isNull())
5434 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005435
Nate Begemanbe2341d2008-07-14 18:02:46 +00005436 QualType lType = lex->getType();
5437 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005438
Nate Begemanbe2341d2008-07-14 18:02:46 +00005439 // For non-floating point types, check for self-comparisons of the form
5440 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5441 // often indicate logic errors in the program.
5442 if (!lType->isFloatingType()) {
5443 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5444 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5445 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005446 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005447 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005448
Nate Begemanbe2341d2008-07-14 18:02:46 +00005449 // Check for comparisons of floating point operands using != and ==.
5450 if (!isRelational && lType->isFloatingType()) {
5451 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005452 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005453 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005454
Nate Begemanbe2341d2008-07-14 18:02:46 +00005455 // Return the type for the comparison, which is the same as vector type for
5456 // integer vectors, or an integer type of identical size and number of
5457 // elements for floating point vectors.
5458 if (lType->isIntegerType())
5459 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005460
John McCall183700f2009-09-21 23:43:11 +00005461 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005462 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005463 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005464 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005465 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005466 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5467
Mike Stumpeed9cac2009-02-19 03:04:26 +00005468 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005469 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005470 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5471}
5472
Reid Spencer5f016e22007-07-11 17:01:13 +00005473inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005474 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005475 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005476 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005477
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005478 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005479
Steve Naroffa4332e22007-07-17 00:58:39 +00005480 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005481 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005482 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005483}
5484
5485inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005486 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005487 if (!Context.getLangOptions().CPlusPlus) {
5488 UsualUnaryConversions(lex);
5489 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005490
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005491 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5492 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005493
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005494 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005495 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005496
5497 // C++ [expr.log.and]p1
5498 // C++ [expr.log.or]p1
5499 // The operands are both implicitly converted to type bool (clause 4).
5500 StandardConversionSequence LHS;
5501 if (!IsStandardConversion(lex, Context.BoolTy,
5502 /*InOverloadResolution=*/false, LHS))
5503 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005504
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005505 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5506 "passing", /*IgnoreBaseAccess=*/false))
5507 return InvalidOperands(Loc, lex, rex);
5508
5509 StandardConversionSequence RHS;
5510 if (!IsStandardConversion(rex, Context.BoolTy,
5511 /*InOverloadResolution=*/false, RHS))
5512 return InvalidOperands(Loc, lex, rex);
5513
5514 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5515 "passing", /*IgnoreBaseAccess=*/false))
5516 return InvalidOperands(Loc, lex, rex);
5517
5518 // C++ [expr.log.and]p2
5519 // C++ [expr.log.or]p2
5520 // The result is a bool.
5521 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005522}
5523
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005524/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5525/// is a read-only property; return true if so. A readonly property expression
5526/// depends on various declarations and thus must be treated specially.
5527///
Mike Stump1eb44332009-09-09 15:08:12 +00005528static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005529 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5530 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5531 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5532 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005533 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005534 BaseType->getAsObjCInterfacePointerType())
5535 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5536 if (S.isPropertyReadonly(PDecl, IFace))
5537 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005538 }
5539 }
5540 return false;
5541}
5542
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005543/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5544/// emit an error and return true. If so, return false.
5545static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005546 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005547 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005548 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005549 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5550 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005551 if (IsLV == Expr::MLV_Valid)
5552 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005553
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005554 unsigned Diag = 0;
5555 bool NeedType = false;
5556 switch (IsLV) { // C99 6.5.16p2
5557 default: assert(0 && "Unknown result from isModifiableLvalue!");
5558 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005559 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005560 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5561 NeedType = true;
5562 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005563 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005564 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5565 NeedType = true;
5566 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005567 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005568 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5569 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005570 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005571 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5572 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005573 case Expr::MLV_IncompleteType:
5574 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005575 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005576 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5577 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005578 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005579 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5580 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005581 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005582 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5583 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005584 case Expr::MLV_ReadonlyProperty:
5585 Diag = diag::error_readonly_property_assignment;
5586 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005587 case Expr::MLV_NoSetterProperty:
5588 Diag = diag::error_nosetter_property_assignment;
5589 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005590 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005591
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005592 SourceRange Assign;
5593 if (Loc != OrigLoc)
5594 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005595 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005596 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005597 else
Mike Stump1eb44332009-09-09 15:08:12 +00005598 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005599 return true;
5600}
5601
5602
5603
5604// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005605QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5606 SourceLocation Loc,
5607 QualType CompoundType) {
5608 // Verify that LHS is a modifiable lvalue, and emit error if not.
5609 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005610 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005611
5612 QualType LHSType = LHS->getType();
5613 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005614
Chris Lattner5cf216b2008-01-04 18:04:52 +00005615 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005616 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005617 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005618 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005619 // Special case of NSObject attributes on c-style pointer types.
5620 if (ConvTy == IncompatiblePointer &&
5621 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005622 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005623 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005624 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005625 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005626
Chris Lattner2c156472008-08-21 18:04:13 +00005627 // If the RHS is a unary plus or minus, check to see if they = and + are
5628 // right next to each other. If so, the user may have typo'd "x =+ 4"
5629 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005630 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005631 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5632 RHSCheck = ICE->getSubExpr();
5633 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5634 if ((UO->getOpcode() == UnaryOperator::Plus ||
5635 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005636 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005637 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005638 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5639 // And there is a space or other character before the subexpr of the
5640 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005641 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5642 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005643 Diag(Loc, diag::warn_not_compound_assign)
5644 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5645 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005646 }
Chris Lattner2c156472008-08-21 18:04:13 +00005647 }
5648 } else {
5649 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005650 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005651 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005652
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005653 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5654 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005655 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005656
Reid Spencer5f016e22007-07-11 17:01:13 +00005657 // C99 6.5.16p3: The type of an assignment expression is the type of the
5658 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005659 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005660 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5661 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005662 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005663 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005664 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005665}
5666
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005667// C99 6.5.17
5668QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005669 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005670 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005671
5672 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5673 // incomplete in C++).
5674
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005675 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005676}
5677
Steve Naroff49b45262007-07-13 16:58:59 +00005678/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5679/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005680QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5681 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005682 if (Op->isTypeDependent())
5683 return Context.DependentTy;
5684
Chris Lattner3528d352008-11-21 07:05:48 +00005685 QualType ResType = Op->getType();
5686 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005687
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005688 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5689 // Decrement of bool is not allowed.
5690 if (!isInc) {
5691 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5692 return QualType();
5693 }
5694 // Increment of bool sets it to true, but is deprecated.
5695 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5696 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005697 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005698 } else if (ResType->isAnyPointerType()) {
5699 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005700
Chris Lattner3528d352008-11-21 07:05:48 +00005701 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005702 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005703 if (getLangOptions().CPlusPlus) {
5704 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5705 << Op->getSourceRange();
5706 return QualType();
5707 }
5708
5709 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005710 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005711 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005712 if (getLangOptions().CPlusPlus) {
5713 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5714 << Op->getType() << Op->getSourceRange();
5715 return QualType();
5716 }
5717
5718 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005719 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005720 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005721 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005722 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005723 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005724 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005725 // Diagnose bad cases where we step over interface counts.
5726 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5727 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5728 << PointeeTy << Op->getSourceRange();
5729 return QualType();
5730 }
Chris Lattner3528d352008-11-21 07:05:48 +00005731 } else if (ResType->isComplexType()) {
5732 // C99 does not support ++/-- on complex types, we allow as an extension.
5733 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005734 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005735 } else {
5736 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005737 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005738 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005739 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005740 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005741 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005742 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005743 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005744 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005745}
5746
Anders Carlsson369dee42008-02-01 07:15:58 +00005747/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005748/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005749/// where the declaration is needed for type checking. We only need to
5750/// handle cases when the expression references a function designator
5751/// or is an lvalue. Here are some examples:
5752/// - &(x) => x
5753/// - &*****f => f for f a function designator.
5754/// - &s.xx => s
5755/// - &s.zz[1].yy -> s, if zz is an array
5756/// - *(x + 1) -> x, if x is an array
5757/// - &"123"[2] -> 0
5758/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005759static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005760 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005761 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005762 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005763 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005764 // If this is an arrow operator, the address is an offset from
5765 // the base's value, so the object the base refers to is
5766 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005767 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005768 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005769 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005770 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005771 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005772 // FIXME: This code shouldn't be necessary! We should catch the implicit
5773 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005774 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5775 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5776 if (ICE->getSubExpr()->getType()->isArrayType())
5777 return getPrimaryDecl(ICE->getSubExpr());
5778 }
5779 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005780 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005781 case Stmt::UnaryOperatorClass: {
5782 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005783
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005784 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005785 case UnaryOperator::Real:
5786 case UnaryOperator::Imag:
5787 case UnaryOperator::Extension:
5788 return getPrimaryDecl(UO->getSubExpr());
5789 default:
5790 return 0;
5791 }
5792 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005793 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005794 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005795 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005796 // If the result of an implicit cast is an l-value, we care about
5797 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005798 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005799 default:
5800 return 0;
5801 }
5802}
5803
5804/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005805/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005806/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005807/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005808/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005809/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005810/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005811QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005812 // Make sure to ignore parentheses in subsequent checks
5813 op = op->IgnoreParens();
5814
Douglas Gregor9103bb22008-12-17 22:52:20 +00005815 if (op->isTypeDependent())
5816 return Context.DependentTy;
5817
Steve Naroff08f19672008-01-13 17:10:08 +00005818 if (getLangOptions().C99) {
5819 // Implement C99-only parts of addressof rules.
5820 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5821 if (uOp->getOpcode() == UnaryOperator::Deref)
5822 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5823 // (assuming the deref expression is valid).
5824 return uOp->getSubExpr()->getType();
5825 }
5826 // Technically, there should be a check for array subscript
5827 // expressions here, but the result of one is always an lvalue anyway.
5828 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005829 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005830 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005831
Eli Friedman441cf102009-05-16 23:27:50 +00005832 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5833 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005834 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005835 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005836 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005837 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5838 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005839 return QualType();
5840 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005841 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005842 // The operand cannot be a bit-field
5843 Diag(OpLoc, diag::err_typecheck_address_of)
5844 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005845 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005846 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5847 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005848 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005849 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005850 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005851 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005852 } else if (isa<ObjCPropertyRefExpr>(op)) {
5853 // cannot take address of a property expression.
5854 Diag(OpLoc, diag::err_typecheck_address_of)
5855 << "property expression" << op->getSourceRange();
5856 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005857 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5858 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005859 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5860 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005861 } else if (isa<UnresolvedLookupExpr>(op)) {
5862 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005863 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005864 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005865 // with the register storage-class specifier.
5866 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5867 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005868 Diag(OpLoc, diag::err_typecheck_address_of)
5869 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005870 return QualType();
5871 }
John McCallba135432009-11-21 08:51:07 +00005872 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005873 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005874 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005875 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005876 // Could be a pointer to member, though, if there is an explicit
5877 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005878 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005879 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005880 if (Ctx && Ctx->isRecord()) {
5881 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005882 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005883 diag::err_cannot_form_pointer_to_member_of_reference_type)
5884 << FD->getDeclName() << FD->getType();
5885 return QualType();
5886 }
Mike Stump1eb44332009-09-09 15:08:12 +00005887
Sebastian Redlebc07d52009-02-03 20:19:35 +00005888 return Context.getMemberPointerType(op->getType(),
5889 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005890 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005891 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005892 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005893 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005894 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005895 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5896 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005897 return Context.getMemberPointerType(op->getType(),
5898 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5899 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005900 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005901 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005902
Eli Friedman441cf102009-05-16 23:27:50 +00005903 if (lval == Expr::LV_IncompleteVoidType) {
5904 // Taking the address of a void variable is technically illegal, but we
5905 // allow it in cases which are otherwise valid.
5906 // Example: "extern void x; void* y = &x;".
5907 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5908 }
5909
Reid Spencer5f016e22007-07-11 17:01:13 +00005910 // If the operand has type "type", the result has type "pointer to type".
5911 return Context.getPointerType(op->getType());
5912}
5913
Chris Lattner22caddc2008-11-23 09:13:29 +00005914QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005915 if (Op->isTypeDependent())
5916 return Context.DependentTy;
5917
Chris Lattner22caddc2008-11-23 09:13:29 +00005918 UsualUnaryConversions(Op);
5919 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005920
Chris Lattner22caddc2008-11-23 09:13:29 +00005921 // Note that per both C89 and C99, this is always legal, even if ptype is an
5922 // incomplete type or void. It would be possible to warn about dereferencing
5923 // a void pointer, but it's completely well-defined, and such a warning is
5924 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005925 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005926 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005927
John McCall183700f2009-09-21 23:43:11 +00005928 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005929 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005930
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005931 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005932 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005933 return QualType();
5934}
5935
5936static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5937 tok::TokenKind Kind) {
5938 BinaryOperator::Opcode Opc;
5939 switch (Kind) {
5940 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005941 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5942 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005943 case tok::star: Opc = BinaryOperator::Mul; break;
5944 case tok::slash: Opc = BinaryOperator::Div; break;
5945 case tok::percent: Opc = BinaryOperator::Rem; break;
5946 case tok::plus: Opc = BinaryOperator::Add; break;
5947 case tok::minus: Opc = BinaryOperator::Sub; break;
5948 case tok::lessless: Opc = BinaryOperator::Shl; break;
5949 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5950 case tok::lessequal: Opc = BinaryOperator::LE; break;
5951 case tok::less: Opc = BinaryOperator::LT; break;
5952 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5953 case tok::greater: Opc = BinaryOperator::GT; break;
5954 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5955 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5956 case tok::amp: Opc = BinaryOperator::And; break;
5957 case tok::caret: Opc = BinaryOperator::Xor; break;
5958 case tok::pipe: Opc = BinaryOperator::Or; break;
5959 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5960 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5961 case tok::equal: Opc = BinaryOperator::Assign; break;
5962 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5963 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5964 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5965 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5966 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5967 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5968 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5969 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5970 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5971 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5972 case tok::comma: Opc = BinaryOperator::Comma; break;
5973 }
5974 return Opc;
5975}
5976
5977static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5978 tok::TokenKind Kind) {
5979 UnaryOperator::Opcode Opc;
5980 switch (Kind) {
5981 default: assert(0 && "Unknown unary op!");
5982 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5983 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5984 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5985 case tok::star: Opc = UnaryOperator::Deref; break;
5986 case tok::plus: Opc = UnaryOperator::Plus; break;
5987 case tok::minus: Opc = UnaryOperator::Minus; break;
5988 case tok::tilde: Opc = UnaryOperator::Not; break;
5989 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005990 case tok::kw___real: Opc = UnaryOperator::Real; break;
5991 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5992 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5993 }
5994 return Opc;
5995}
5996
Douglas Gregoreaebc752008-11-06 23:29:22 +00005997/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5998/// operator @p Opc at location @c TokLoc. This routine only supports
5999/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006000Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6001 unsigned Op,
6002 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006003 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006004 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006005 // The following two variables are used for compound assignment operators
6006 QualType CompLHSTy; // Type of LHS after promotions for computation
6007 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006008
6009 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006010 case BinaryOperator::Assign:
6011 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6012 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006013 case BinaryOperator::PtrMemD:
6014 case BinaryOperator::PtrMemI:
6015 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6016 Opc == BinaryOperator::PtrMemI);
6017 break;
6018 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006019 case BinaryOperator::Div:
6020 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
6021 break;
6022 case BinaryOperator::Rem:
6023 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6024 break;
6025 case BinaryOperator::Add:
6026 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6027 break;
6028 case BinaryOperator::Sub:
6029 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6030 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006031 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006032 case BinaryOperator::Shr:
6033 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6034 break;
6035 case BinaryOperator::LE:
6036 case BinaryOperator::LT:
6037 case BinaryOperator::GE:
6038 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006039 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006040 break;
6041 case BinaryOperator::EQ:
6042 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006043 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006044 break;
6045 case BinaryOperator::And:
6046 case BinaryOperator::Xor:
6047 case BinaryOperator::Or:
6048 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6049 break;
6050 case BinaryOperator::LAnd:
6051 case BinaryOperator::LOr:
6052 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6053 break;
6054 case BinaryOperator::MulAssign:
6055 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006056 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6057 CompLHSTy = CompResultTy;
6058 if (!CompResultTy.isNull())
6059 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006060 break;
6061 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006062 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6063 CompLHSTy = CompResultTy;
6064 if (!CompResultTy.isNull())
6065 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006066 break;
6067 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006068 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6069 if (!CompResultTy.isNull())
6070 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006071 break;
6072 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006073 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6074 if (!CompResultTy.isNull())
6075 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006076 break;
6077 case BinaryOperator::ShlAssign:
6078 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006079 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6080 CompLHSTy = CompResultTy;
6081 if (!CompResultTy.isNull())
6082 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006083 break;
6084 case BinaryOperator::AndAssign:
6085 case BinaryOperator::XorAssign:
6086 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006087 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6088 CompLHSTy = CompResultTy;
6089 if (!CompResultTy.isNull())
6090 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006091 break;
6092 case BinaryOperator::Comma:
6093 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6094 break;
6095 }
6096 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006097 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006098 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006099 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6100 else
6101 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006102 CompLHSTy, CompResultTy,
6103 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006104}
6105
Sebastian Redlaee3c932009-10-27 12:10:02 +00006106/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6107/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006108static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6109 const PartialDiagnostic &PD,
6110 SourceRange ParenRange)
6111{
6112 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6113 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6114 // We can't display the parentheses, so just dig the
6115 // warning/error and return.
6116 Self.Diag(Loc, PD);
6117 return;
6118 }
6119
6120 Self.Diag(Loc, PD)
6121 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6122 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6123}
6124
Sebastian Redlaee3c932009-10-27 12:10:02 +00006125/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6126/// operators are mixed in a way that suggests that the programmer forgot that
6127/// comparison operators have higher precedence. The most typical example of
6128/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006129static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6130 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006131 typedef BinaryOperator BinOp;
6132 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6133 rhsopc = static_cast<BinOp::Opcode>(-1);
6134 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006135 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006136 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006137 rhsopc = BO->getOpcode();
6138
6139 // Subs are not binary operators.
6140 if (lhsopc == -1 && rhsopc == -1)
6141 return;
6142
6143 // Bitwise operations are sometimes used as eager logical ops.
6144 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006145 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6146 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006147 return;
6148
Sebastian Redlaee3c932009-10-27 12:10:02 +00006149 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006150 SuggestParentheses(Self, OpLoc,
6151 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006152 << SourceRange(lhs->getLocStart(), OpLoc)
6153 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6154 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6155 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006156 SuggestParentheses(Self, OpLoc,
6157 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006158 << SourceRange(OpLoc, rhs->getLocEnd())
6159 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6160 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006161}
6162
6163/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6164/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6165/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6166static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6167 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006168 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006169 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6170}
6171
Reid Spencer5f016e22007-07-11 17:01:13 +00006172// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006173Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6174 tok::TokenKind Kind,
6175 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006176 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006177 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006178
Steve Narofff69936d2007-09-16 03:34:24 +00006179 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6180 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006181
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006182 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6183 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6184
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006185 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6186}
6187
6188Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6189 BinaryOperator::Opcode Opc,
6190 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006191 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006192 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006193 rhs->getType()->isOverloadableType())) {
6194 // Find all of the overloaded operators visible from this
6195 // point. We perform both an operator-name lookup from the local
6196 // scope and an argument-dependent lookup based on the types of
6197 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006198 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006199 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6200 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006201 if (S)
6202 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6203 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006204 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006205 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006206 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006207 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006208 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006209
Douglas Gregor063daf62009-03-13 18:40:31 +00006210 // Build the (potentially-overloaded, potentially-dependent)
6211 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006212 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006213 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006214
Douglas Gregoreaebc752008-11-06 23:29:22 +00006215 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006216 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006217}
6218
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006219Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006220 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006221 ExprArg InputArg) {
6222 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006223
Mike Stump390b4cc2009-05-16 07:39:55 +00006224 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006225 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006226 QualType resultType;
6227 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006228 case UnaryOperator::OffsetOf:
6229 assert(false && "Invalid unary operator");
6230 break;
6231
Reid Spencer5f016e22007-07-11 17:01:13 +00006232 case UnaryOperator::PreInc:
6233 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006234 case UnaryOperator::PostInc:
6235 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006236 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006237 Opc == UnaryOperator::PreInc ||
6238 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006239 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006240 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006241 resultType = CheckAddressOfOperand(Input, OpLoc);
6242 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006243 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006244 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006245 resultType = CheckIndirectionOperand(Input, OpLoc);
6246 break;
6247 case UnaryOperator::Plus:
6248 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006249 UsualUnaryConversions(Input);
6250 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006251 if (resultType->isDependentType())
6252 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006253 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6254 break;
6255 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6256 resultType->isEnumeralType())
6257 break;
6258 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6259 Opc == UnaryOperator::Plus &&
6260 resultType->isPointerType())
6261 break;
6262
Sebastian Redl0eb23302009-01-19 00:08:26 +00006263 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6264 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006265 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006266 UsualUnaryConversions(Input);
6267 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006268 if (resultType->isDependentType())
6269 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006270 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6271 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6272 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006273 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006274 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006275 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006276 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6277 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006278 break;
6279 case UnaryOperator::LNot: // logical negation
6280 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006281 DefaultFunctionArrayConversion(Input);
6282 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006283 if (resultType->isDependentType())
6284 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006285 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006286 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6287 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006288 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006289 // In C++, it's bool. C++ 5.3.1p8
6290 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006291 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006292 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006293 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006294 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006295 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006296 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006297 resultType = Input->getType();
6298 break;
6299 }
6300 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006301 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006302
6303 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006304 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006305}
6306
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006307Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6308 UnaryOperator::Opcode Opc,
6309 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006310 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006311 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6312 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006313 // Find all of the overloaded operators visible from this
6314 // point. We perform both an operator-name lookup from the local
6315 // scope and an argument-dependent lookup based on the types of
6316 // the arguments.
6317 FunctionSet Functions;
6318 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6319 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006320 if (S)
6321 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6322 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006323 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006324 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006325 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006326 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006327
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006328 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6329 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006330
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006331 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6332}
6333
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006334// Unary Operators. 'Tok' is the token for the operator.
6335Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6336 tok::TokenKind Op, ExprArg input) {
6337 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6338}
6339
Steve Naroff1b273c42007-09-16 14:56:35 +00006340/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006341Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6342 SourceLocation LabLoc,
6343 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006344 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006345 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006346
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006347 // If we haven't seen this label yet, create a forward reference. It
6348 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006349 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006350 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006351
Reid Spencer5f016e22007-07-11 17:01:13 +00006352 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006353 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6354 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006355}
6356
Sebastian Redlf53597f2009-03-15 17:47:39 +00006357Sema::OwningExprResult
6358Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6359 SourceLocation RPLoc) { // "({..})"
6360 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006361 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6362 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6363
Eli Friedmandca2b732009-01-24 23:09:00 +00006364 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006365 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006366 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006367
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006368 // FIXME: there are a variety of strange constraints to enforce here, for
6369 // example, it is not possible to goto into a stmt expression apparently.
6370 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006371
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006372 // If there are sub stmts in the compound stmt, take the type of the last one
6373 // as the type of the stmtexpr.
6374 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006375
Chris Lattner611b2ec2008-07-26 19:51:01 +00006376 if (!Compound->body_empty()) {
6377 Stmt *LastStmt = Compound->body_back();
6378 // If LastStmt is a label, skip down through into the body.
6379 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6380 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006381
Chris Lattner611b2ec2008-07-26 19:51:01 +00006382 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006383 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006384 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006385
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006386 // FIXME: Check that expression type is complete/non-abstract; statement
6387 // expressions are not lvalues.
6388
Sebastian Redlf53597f2009-03-15 17:47:39 +00006389 substmt.release();
6390 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006391}
Steve Naroffd34e9152007-08-01 22:05:33 +00006392
Sebastian Redlf53597f2009-03-15 17:47:39 +00006393Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6394 SourceLocation BuiltinLoc,
6395 SourceLocation TypeLoc,
6396 TypeTy *argty,
6397 OffsetOfComponent *CompPtr,
6398 unsigned NumComponents,
6399 SourceLocation RPLoc) {
6400 // FIXME: This function leaks all expressions in the offset components on
6401 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006402 // FIXME: Preserve type source info.
6403 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006404 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006405
Sebastian Redl28507842009-02-26 14:39:58 +00006406 bool Dependent = ArgTy->isDependentType();
6407
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006408 // We must have at least one component that refers to the type, and the first
6409 // one is known to be a field designator. Verify that the ArgTy represents
6410 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006411 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006412 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006413
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006414 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6415 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006416
Eli Friedman35183ac2009-02-27 06:44:11 +00006417 // Otherwise, create a null pointer as the base, and iteratively process
6418 // the offsetof designators.
6419 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6420 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006421 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006422 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006423
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006424 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6425 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006426 // FIXME: This diagnostic isn't actually visible because the location is in
6427 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006428 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006429 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6430 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006431
Sebastian Redl28507842009-02-26 14:39:58 +00006432 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006433 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006434
John McCalld00f2002009-11-04 03:03:43 +00006435 if (RequireCompleteType(TypeLoc, Res->getType(),
6436 diag::err_offsetof_incomplete_type))
6437 return ExprError();
6438
Sebastian Redl28507842009-02-26 14:39:58 +00006439 // FIXME: Dependent case loses a lot of information here. And probably
6440 // leaks like a sieve.
6441 for (unsigned i = 0; i != NumComponents; ++i) {
6442 const OffsetOfComponent &OC = CompPtr[i];
6443 if (OC.isBrackets) {
6444 // Offset of an array sub-field. TODO: Should we allow vector elements?
6445 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6446 if (!AT) {
6447 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006448 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6449 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006450 }
6451
6452 // FIXME: C++: Verify that operator[] isn't overloaded.
6453
Eli Friedman35183ac2009-02-27 06:44:11 +00006454 // Promote the array so it looks more like a normal array subscript
6455 // expression.
6456 DefaultFunctionArrayConversion(Res);
6457
Sebastian Redl28507842009-02-26 14:39:58 +00006458 // C99 6.5.2.1p1
6459 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006460 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006461 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006462 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006463 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006464 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006465
6466 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6467 OC.LocEnd);
6468 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006469 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006470
Ted Kremenek6217b802009-07-29 21:53:49 +00006471 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006472 if (!RC) {
6473 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006474 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6475 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006476 }
Chris Lattner704fe352007-08-30 17:59:59 +00006477
Sebastian Redl28507842009-02-26 14:39:58 +00006478 // Get the decl corresponding to this.
6479 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006480 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006481 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Douglas Gregor75b699a2009-12-12 07:25:49 +00006482 switch (ExprEvalContexts.back().Context ) {
6483 case Unevaluated:
6484 // The argument will never be evaluated, so don't complain.
6485 break;
6486
6487 case PotentiallyEvaluated:
6488 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6489 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6490 << Res->getType());
6491 DidWarnAboutNonPOD = true;
6492 break;
6493
6494 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +00006495 ExprEvalContexts.back().addDiagnostic(BuiltinLoc,
6496 PDiag(diag::warn_offsetof_non_pod_type)
6497 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6498 << Res->getType());
Douglas Gregor75b699a2009-12-12 07:25:49 +00006499 DidWarnAboutNonPOD = true;
6500 break;
6501 }
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006502 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006503 }
Mike Stump1eb44332009-09-09 15:08:12 +00006504
John McCalla24dc2e2009-11-17 02:14:36 +00006505 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6506 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006507
John McCall1bcee0a2009-12-02 08:25:40 +00006508 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006509 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006510 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006511 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6512 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006513
Sebastian Redl28507842009-02-26 14:39:58 +00006514 // FIXME: C++: Verify that MemberDecl isn't a static field.
6515 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006516 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006517 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006518 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006519 } else {
Eli Friedman16c53782009-12-04 07:18:51 +00006520 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006521 // MemberDecl->getType() doesn't get the right qualifiers, but it
6522 // doesn't matter here.
6523 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6524 MemberDecl->getType().getNonReferenceType());
6525 }
Sebastian Redl28507842009-02-26 14:39:58 +00006526 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006527 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006528
Sebastian Redlf53597f2009-03-15 17:47:39 +00006529 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6530 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006531}
6532
6533
Sebastian Redlf53597f2009-03-15 17:47:39 +00006534Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6535 TypeTy *arg1,TypeTy *arg2,
6536 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006537 // FIXME: Preserve type source info.
6538 QualType argT1 = GetTypeFromParser(arg1);
6539 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006540
Steve Naroffd34e9152007-08-01 22:05:33 +00006541 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006542
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006543 if (getLangOptions().CPlusPlus) {
6544 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6545 << SourceRange(BuiltinLoc, RPLoc);
6546 return ExprError();
6547 }
6548
Sebastian Redlf53597f2009-03-15 17:47:39 +00006549 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6550 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006551}
6552
Sebastian Redlf53597f2009-03-15 17:47:39 +00006553Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6554 ExprArg cond,
6555 ExprArg expr1, ExprArg expr2,
6556 SourceLocation RPLoc) {
6557 Expr *CondExpr = static_cast<Expr*>(cond.get());
6558 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6559 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006560
Steve Naroffd04fdd52007-08-03 21:21:27 +00006561 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6562
Sebastian Redl28507842009-02-26 14:39:58 +00006563 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006564 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006565 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006566 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006567 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006568 } else {
6569 // The conditional expression is required to be a constant expression.
6570 llvm::APSInt condEval(32);
6571 SourceLocation ExpLoc;
6572 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006573 return ExprError(Diag(ExpLoc,
6574 diag::err_typecheck_choose_expr_requires_constant)
6575 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006576
Sebastian Redl28507842009-02-26 14:39:58 +00006577 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6578 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006579 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6580 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006581 }
6582
Sebastian Redlf53597f2009-03-15 17:47:39 +00006583 cond.release(); expr1.release(); expr2.release();
6584 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006585 resType, RPLoc,
6586 resType->isDependentType(),
6587 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006588}
6589
Steve Naroff4eb206b2008-09-03 18:15:37 +00006590//===----------------------------------------------------------------------===//
6591// Clang Extensions.
6592//===----------------------------------------------------------------------===//
6593
6594/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006595void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006596 // Analyze block parameters.
6597 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006598
Steve Naroff4eb206b2008-09-03 18:15:37 +00006599 // Add BSI to CurBlock.
6600 BSI->PrevBlockInfo = CurBlock;
6601 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006602
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006603 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006604 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006605 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006606 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006607 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6608 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006609
Steve Naroff090276f2008-10-10 01:28:17 +00006610 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek3cdff232009-12-07 22:01:30 +00006611 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor44b43212008-12-11 16:49:14 +00006612 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006613}
6614
Mike Stump98eb8a72009-02-04 22:31:32 +00006615void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006616 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006617
6618 if (ParamInfo.getNumTypeObjects() == 0
6619 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006620 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006621 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6622
Mike Stump4eeab842009-04-28 01:10:27 +00006623 if (T->isArrayType()) {
6624 Diag(ParamInfo.getSourceRange().getBegin(),
6625 diag::err_block_returns_array);
6626 return;
6627 }
6628
Mike Stump98eb8a72009-02-04 22:31:32 +00006629 // The parameter list is optional, if there was none, assume ().
6630 if (!T->isFunctionType())
6631 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6632
6633 CurBlock->hasPrototype = true;
6634 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006635 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006636 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006637 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006638 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006639 // FIXME: remove the attribute.
6640 }
John McCall183700f2009-09-21 23:43:11 +00006641 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006642
Chris Lattner9097af12009-04-11 19:27:54 +00006643 // Do not allow returning a objc interface by-value.
6644 if (RetTy->isObjCInterfaceType()) {
6645 Diag(ParamInfo.getSourceRange().getBegin(),
6646 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6647 return;
6648 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006649 return;
6650 }
6651
Steve Naroff4eb206b2008-09-03 18:15:37 +00006652 // Analyze arguments to block.
6653 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6654 "Not a function declarator!");
6655 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006656
Steve Naroff090276f2008-10-10 01:28:17 +00006657 CurBlock->hasPrototype = FTI.hasPrototype;
6658 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006659
Steve Naroff4eb206b2008-09-03 18:15:37 +00006660 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6661 // no arguments, not a function that takes a single void argument.
6662 if (FTI.hasPrototype &&
6663 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006664 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6665 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006666 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006667 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006668 } else if (FTI.hasPrototype) {
6669 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006670 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006671 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006672 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006673 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006674 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006675 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006676 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006677 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6678 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6679 // If this has an identifier, add it to the scope stack.
6680 if ((*AI)->getIdentifier())
6681 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006682
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006683 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006684 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006685 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006686 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006687 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006688 // FIXME: remove the attribute.
6689 }
Mike Stump1eb44332009-09-09 15:08:12 +00006690
Chris Lattner9097af12009-04-11 19:27:54 +00006691 // Analyze the return type.
6692 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006693 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006694
Chris Lattner9097af12009-04-11 19:27:54 +00006695 // Do not allow returning a objc interface by-value.
6696 if (RetTy->isObjCInterfaceType()) {
6697 Diag(ParamInfo.getSourceRange().getBegin(),
6698 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6699 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006700 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006701}
6702
6703/// ActOnBlockError - If there is an error parsing a block, this callback
6704/// is invoked to pop the information about the block from the action impl.
6705void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6706 // Ensure that CurBlock is deleted.
6707 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006708
Chris Lattner17a78302009-04-19 05:28:12 +00006709 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6710
Steve Naroff4eb206b2008-09-03 18:15:37 +00006711 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006712 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006713 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006714 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006715}
6716
6717/// ActOnBlockStmtExpr - This is called when the body of a block statement
6718/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006719Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6720 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006721 // If blocks are disabled, emit an error.
6722 if (!LangOpts.Blocks)
6723 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006724
Steve Naroff4eb206b2008-09-03 18:15:37 +00006725 // Ensure that CurBlock is deleted.
6726 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006727
Steve Naroff090276f2008-10-10 01:28:17 +00006728 PopDeclContext();
6729
Steve Naroff4eb206b2008-09-03 18:15:37 +00006730 // Pop off CurBlock, handle nested blocks.
6731 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006732
Steve Naroff4eb206b2008-09-03 18:15:37 +00006733 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006734 if (!BSI->ReturnType.isNull())
6735 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006736
Steve Naroff4eb206b2008-09-03 18:15:37 +00006737 llvm::SmallVector<QualType, 8> ArgTypes;
6738 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6739 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006740
Mike Stump56925862009-07-28 22:04:01 +00006741 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006742 QualType BlockTy;
6743 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006744 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6745 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006746 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006747 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006748 BSI->isVariadic, 0, false, false, 0, 0,
6749 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006750
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006751 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006752 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006753 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006754
Chris Lattner17a78302009-04-19 05:28:12 +00006755 // If needed, diagnose invalid gotos and switches in the block.
6756 if (CurFunctionNeedsScopeChecking)
6757 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6758 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006759
Anders Carlssone9146f22009-05-01 19:49:17 +00006760 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006761 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006762 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6763 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006764}
6765
Sebastian Redlf53597f2009-03-15 17:47:39 +00006766Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6767 ExprArg expr, TypeTy *type,
6768 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006769 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006770 Expr *E = static_cast<Expr*>(expr.get());
6771 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006772
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006773 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006774
6775 // Get the va_list type
6776 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006777 if (VaListType->isArrayType()) {
6778 // Deal with implicit array decay; for example, on x86-64,
6779 // va_list is an array, but it's supposed to decay to
6780 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006781 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006782 // Make sure the input expression also decays appropriately.
6783 UsualUnaryConversions(E);
6784 } else {
6785 // Otherwise, the va_list argument must be an l-value because
6786 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006787 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006788 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006789 return ExprError();
6790 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006791
Douglas Gregordd027302009-05-19 23:10:31 +00006792 if (!E->isTypeDependent() &&
6793 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006794 return ExprError(Diag(E->getLocStart(),
6795 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006796 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006797 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006798
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006799 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006800 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006801
Sebastian Redlf53597f2009-03-15 17:47:39 +00006802 expr.release();
6803 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6804 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006805}
6806
Sebastian Redlf53597f2009-03-15 17:47:39 +00006807Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006808 // The type of __null will be int or long, depending on the size of
6809 // pointers on the target.
6810 QualType Ty;
6811 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6812 Ty = Context.IntTy;
6813 else
6814 Ty = Context.LongTy;
6815
Sebastian Redlf53597f2009-03-15 17:47:39 +00006816 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006817}
6818
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006819static void
6820MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6821 QualType DstType,
6822 Expr *SrcExpr,
6823 CodeModificationHint &Hint) {
6824 if (!SemaRef.getLangOptions().ObjC1)
6825 return;
6826
6827 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6828 if (!PT)
6829 return;
6830
6831 // Check if the destination is of type 'id'.
6832 if (!PT->isObjCIdType()) {
6833 // Check if the destination is the 'NSString' interface.
6834 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6835 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6836 return;
6837 }
6838
6839 // Strip off any parens and casts.
6840 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6841 if (!SL || SL->isWide())
6842 return;
6843
6844 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6845}
6846
Chris Lattner5cf216b2008-01-04 18:04:52 +00006847bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6848 SourceLocation Loc,
6849 QualType DstType, QualType SrcType,
6850 Expr *SrcExpr, const char *Flavor) {
6851 // Decode the result (notice that AST's are still created for extensions).
6852 bool isInvalid = false;
6853 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006854 CodeModificationHint Hint;
6855
Chris Lattner5cf216b2008-01-04 18:04:52 +00006856 switch (ConvTy) {
6857 default: assert(0 && "Unknown conversion type");
6858 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006859 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006860 DiagKind = diag::ext_typecheck_convert_pointer_int;
6861 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006862 case IntToPointer:
6863 DiagKind = diag::ext_typecheck_convert_int_pointer;
6864 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006865 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006866 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006867 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6868 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006869 case IncompatiblePointerSign:
6870 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6871 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006872 case FunctionVoidPointer:
6873 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6874 break;
6875 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006876 // If the qualifiers lost were because we were applying the
6877 // (deprecated) C++ conversion from a string literal to a char*
6878 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6879 // Ideally, this check would be performed in
6880 // CheckPointerTypesForAssignment. However, that would require a
6881 // bit of refactoring (so that the second argument is an
6882 // expression, rather than a type), which should be done as part
6883 // of a larger effort to fix CheckPointerTypesForAssignment for
6884 // C++ semantics.
6885 if (getLangOptions().CPlusPlus &&
6886 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6887 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006888 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6889 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006890 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006891 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006892 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006893 case IntToBlockPointer:
6894 DiagKind = diag::err_int_to_block_pointer;
6895 break;
6896 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006897 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006898 break;
Steve Naroff39579072008-10-14 22:18:38 +00006899 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006900 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006901 // it can give a more specific diagnostic.
6902 DiagKind = diag::warn_incompatible_qualified_id;
6903 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006904 case IncompatibleVectors:
6905 DiagKind = diag::warn_incompatible_vectors;
6906 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006907 case Incompatible:
6908 DiagKind = diag::err_typecheck_convert_incompatible;
6909 isInvalid = true;
6910 break;
6911 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006912
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006913 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006914 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006915 return isInvalid;
6916}
Anders Carlssone21555e2008-11-30 19:50:32 +00006917
Chris Lattner3bf68932009-04-25 21:59:05 +00006918bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006919 llvm::APSInt ICEResult;
6920 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6921 if (Result)
6922 *Result = ICEResult;
6923 return false;
6924 }
6925
Anders Carlssone21555e2008-11-30 19:50:32 +00006926 Expr::EvalResult EvalResult;
6927
Mike Stumpeed9cac2009-02-19 03:04:26 +00006928 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006929 EvalResult.HasSideEffects) {
6930 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6931
6932 if (EvalResult.Diag) {
6933 // We only show the note if it's not the usual "invalid subexpression"
6934 // or if it's actually in a subexpression.
6935 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6936 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6937 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6938 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006939
Anders Carlssone21555e2008-11-30 19:50:32 +00006940 return true;
6941 }
6942
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006943 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6944 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006945
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006946 if (EvalResult.Diag &&
6947 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6948 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006949
Anders Carlssone21555e2008-11-30 19:50:32 +00006950 if (Result)
6951 *Result = EvalResult.Val.getInt();
6952 return false;
6953}
Douglas Gregore0762c92009-06-19 23:52:42 +00006954
Douglas Gregor2afce722009-11-26 00:44:06 +00006955void
Mike Stump1eb44332009-09-09 15:08:12 +00006956Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00006957 ExprEvalContexts.push_back(
6958 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00006959}
6960
Mike Stump1eb44332009-09-09 15:08:12 +00006961void
Douglas Gregor2afce722009-11-26 00:44:06 +00006962Sema::PopExpressionEvaluationContext() {
6963 // Pop the current expression evaluation context off the stack.
6964 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6965 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006966
Douglas Gregor06d33692009-12-12 07:57:52 +00006967 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
6968 if (Rec.PotentiallyReferenced) {
6969 // Mark any remaining declarations in the current position of the stack
6970 // as "referenced". If they were not meant to be referenced, semantic
6971 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6972 for (PotentiallyReferencedDecls::iterator
6973 I = Rec.PotentiallyReferenced->begin(),
6974 IEnd = Rec.PotentiallyReferenced->end();
6975 I != IEnd; ++I)
6976 MarkDeclarationReferenced(I->first, I->second);
6977 }
6978
6979 if (Rec.PotentiallyDiagnosed) {
6980 // Emit any pending diagnostics.
6981 for (PotentiallyEmittedDiagnostics::iterator
6982 I = Rec.PotentiallyDiagnosed->begin(),
6983 IEnd = Rec.PotentiallyDiagnosed->end();
6984 I != IEnd; ++I)
6985 Diag(I->first, I->second);
6986 }
Douglas Gregor2afce722009-11-26 00:44:06 +00006987 }
6988
6989 // When are coming out of an unevaluated context, clear out any
6990 // temporaries that we may have created as part of the evaluation of
6991 // the expression in that context: they aren't relevant because they
6992 // will never be constructed.
6993 if (Rec.Context == Unevaluated &&
6994 ExprTemporaries.size() > Rec.NumTemporaries)
6995 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6996 ExprTemporaries.end());
6997
6998 // Destroy the popped expression evaluation record.
6999 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007000}
Douglas Gregore0762c92009-06-19 23:52:42 +00007001
7002/// \brief Note that the given declaration was referenced in the source code.
7003///
7004/// This routine should be invoke whenever a given declaration is referenced
7005/// in the source code, and where that reference occurred. If this declaration
7006/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7007/// C99 6.9p3), then the declaration will be marked as used.
7008///
7009/// \param Loc the location where the declaration was referenced.
7010///
7011/// \param D the declaration that has been referenced by the source code.
7012void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7013 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007014
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007015 if (D->isUsed())
7016 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007017
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007018 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7019 // template or not. The reason for this is that unevaluated expressions
7020 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7021 // -Wunused-parameters)
7022 if (isa<ParmVarDecl>(D) ||
7023 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00007024 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00007025
Douglas Gregore0762c92009-06-19 23:52:42 +00007026 // Do not mark anything as "used" within a dependent context; wait for
7027 // an instantiation.
7028 if (CurContext->isDependentContext())
7029 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007030
Douglas Gregor2afce722009-11-26 00:44:06 +00007031 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007032 case Unevaluated:
7033 // We are in an expression that is not potentially evaluated; do nothing.
7034 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007035
Douglas Gregorac7610d2009-06-22 20:57:11 +00007036 case PotentiallyEvaluated:
7037 // We are in a potentially-evaluated expression, so this declaration is
7038 // "used"; handle this below.
7039 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007040
Douglas Gregorac7610d2009-06-22 20:57:11 +00007041 case PotentiallyPotentiallyEvaluated:
7042 // We are in an expression that may be potentially evaluated; queue this
7043 // declaration reference until we know whether the expression is
7044 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007045 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007046 return;
7047 }
Mike Stump1eb44332009-09-09 15:08:12 +00007048
Douglas Gregore0762c92009-06-19 23:52:42 +00007049 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007050 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007051 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007052 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7053 if (!Constructor->isUsed())
7054 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007055 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007056 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007057 if (!Constructor->isUsed())
7058 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7059 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007060
7061 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007062 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7063 if (Destructor->isImplicit() && !Destructor->isUsed())
7064 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007065
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007066 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7067 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7068 MethodDecl->getOverloadedOperator() == OO_Equal) {
7069 if (!MethodDecl->isUsed())
7070 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7071 }
7072 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007073 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007074 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007075 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007076 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007077 bool AlreadyInstantiated = false;
7078 if (FunctionTemplateSpecializationInfo *SpecInfo
7079 = Function->getTemplateSpecializationInfo()) {
7080 if (SpecInfo->getPointOfInstantiation().isInvalid())
7081 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007082 else if (SpecInfo->getTemplateSpecializationKind()
7083 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007084 AlreadyInstantiated = true;
7085 } else if (MemberSpecializationInfo *MSInfo
7086 = Function->getMemberSpecializationInfo()) {
7087 if (MSInfo->getPointOfInstantiation().isInvalid())
7088 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007089 else if (MSInfo->getTemplateSpecializationKind()
7090 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007091 AlreadyInstantiated = true;
7092 }
7093
7094 if (!AlreadyInstantiated)
7095 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7096 }
7097
Douglas Gregore0762c92009-06-19 23:52:42 +00007098 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007099 Function->setUsed(true);
7100 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007101 }
Mike Stump1eb44332009-09-09 15:08:12 +00007102
Douglas Gregore0762c92009-06-19 23:52:42 +00007103 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007104 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007105 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007106 Var->getInstantiatedFromStaticDataMember()) {
7107 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7108 assert(MSInfo && "Missing member specialization information?");
7109 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7110 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7111 MSInfo->setPointOfInstantiation(Loc);
7112 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7113 }
7114 }
Mike Stump1eb44332009-09-09 15:08:12 +00007115
Douglas Gregore0762c92009-06-19 23:52:42 +00007116 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007117
Douglas Gregore0762c92009-06-19 23:52:42 +00007118 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007119 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007120 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007121}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007122
7123bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7124 CallExpr *CE, FunctionDecl *FD) {
7125 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7126 return false;
7127
7128 PartialDiagnostic Note =
7129 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7130 << FD->getDeclName() : PDiag();
7131 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7132
7133 if (RequireCompleteType(Loc, ReturnType,
7134 FD ?
7135 PDiag(diag::err_call_function_incomplete_return)
7136 << CE->getSourceRange() << FD->getDeclName() :
7137 PDiag(diag::err_call_incomplete_return)
7138 << CE->getSourceRange(),
7139 std::make_pair(NoteLoc, Note)))
7140 return true;
7141
7142 return false;
7143}
7144
John McCall5a881bb2009-10-12 21:59:07 +00007145// Diagnose the common s/=/==/ typo. Note that adding parentheses
7146// will prevent this condition from triggering, which is what we want.
7147void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7148 SourceLocation Loc;
7149
John McCalla52ef082009-11-11 02:41:58 +00007150 unsigned diagnostic = diag::warn_condition_is_assignment;
7151
John McCall5a881bb2009-10-12 21:59:07 +00007152 if (isa<BinaryOperator>(E)) {
7153 BinaryOperator *Op = cast<BinaryOperator>(E);
7154 if (Op->getOpcode() != BinaryOperator::Assign)
7155 return;
7156
John McCallc8d8ac52009-11-12 00:06:05 +00007157 // Greylist some idioms by putting them into a warning subcategory.
7158 if (ObjCMessageExpr *ME
7159 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7160 Selector Sel = ME->getSelector();
7161
John McCallc8d8ac52009-11-12 00:06:05 +00007162 // self = [<foo> init...]
7163 if (isSelfExpr(Op->getLHS())
7164 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7165 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7166
7167 // <foo> = [<bar> nextObject]
7168 else if (Sel.isUnarySelector() &&
7169 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7170 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7171 }
John McCalla52ef082009-11-11 02:41:58 +00007172
John McCall5a881bb2009-10-12 21:59:07 +00007173 Loc = Op->getOperatorLoc();
7174 } else if (isa<CXXOperatorCallExpr>(E)) {
7175 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7176 if (Op->getOperator() != OO_Equal)
7177 return;
7178
7179 Loc = Op->getOperatorLoc();
7180 } else {
7181 // Not an assignment.
7182 return;
7183 }
7184
John McCall5a881bb2009-10-12 21:59:07 +00007185 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007186 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007187
John McCalla52ef082009-11-11 02:41:58 +00007188 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007189 << E->getSourceRange()
7190 << CodeModificationHint::CreateInsertion(Open, "(")
7191 << CodeModificationHint::CreateInsertion(Close, ")");
7192}
7193
7194bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7195 DiagnoseAssignmentAsCondition(E);
7196
7197 if (!E->isTypeDependent()) {
7198 DefaultFunctionArrayConversion(E);
7199
7200 QualType T = E->getType();
7201
7202 if (getLangOptions().CPlusPlus) {
7203 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7204 return true;
7205 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7206 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7207 << T << E->getSourceRange();
7208 return true;
7209 }
7210 }
7211
7212 return false;
7213}