blob: 43f150fbeff7710b8f4365151b5e569a6d0432ff [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"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000028#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
David Chisnall0f436562009-08-17 16:35:33 +000031
Douglas Gregor48f3bb92009-02-18 21:56:37 +000032/// \brief Determine whether the use of this declaration is valid, and
33/// emit any corresponding diagnostics.
34///
35/// This routine diagnoses various problems with referencing
36/// declarations that can occur when using a declaration. For example,
37/// it might warn if a deprecated or unavailable declaration is being
38/// used, or produce an error (and return true) if a C++0x deleted
39/// function is being used.
40///
Chris Lattner52338262009-10-25 22:31:57 +000041/// If IgnoreDeprecated is set to true, this should not want about deprecated
42/// decls.
43///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000044/// \returns true if there was an error (this declaration cannot be
45/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000046///
John McCall54abf7d2009-11-04 02:18:39 +000047bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000048 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000049 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000050 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000051 }
52
Chris Lattnerffb93682009-10-25 17:21:40 +000053 // See if the decl is unavailable
54 if (D->getAttr<UnavailableAttr>()) {
55 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
56 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
57 }
58
Douglas Gregor48f3bb92009-02-18 21:56:37 +000059 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000060 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000061 if (FD->isDeleted()) {
62 Diag(Loc, diag::err_deleted_function_use);
63 Diag(D->getLocation(), diag::note_unavailable_here) << true;
64 return true;
65 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000066 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000067
Douglas Gregor48f3bb92009-02-18 21:56:37 +000068 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000069}
70
Fariborz Jahanian5b530052009-05-13 18:09:35 +000071/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000072/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000073/// attribute. It warns if call does not have the sentinel argument.
74///
75void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000076 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000077 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000078 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000079 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000080 int sentinelPos = attr->getSentinel();
81 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000082
Mike Stump390b4cc2009-05-16 07:39:55 +000083 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
84 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000085 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000086 bool warnNotEnoughArgs = false;
87 int isMethod = 0;
88 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
89 // skip over named parameters.
90 ObjCMethodDecl::param_iterator P, E = MD->param_end();
91 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
92 if (nullPos)
93 --nullPos;
94 else
95 ++i;
96 }
97 warnNotEnoughArgs = (P != E || i >= NumArgs);
98 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +000099 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000100 // skip over named parameters.
101 ObjCMethodDecl::param_iterator P, E = FD->param_end();
102 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
103 if (nullPos)
104 --nullPos;
105 else
106 ++i;
107 }
108 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000109 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000110 // block or function pointer call.
111 QualType Ty = V->getType();
112 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000113 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000114 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
115 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000116 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
117 unsigned NumArgsInProto = Proto->getNumArgs();
118 unsigned k;
119 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
120 if (nullPos)
121 --nullPos;
122 else
123 ++i;
124 }
125 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
126 }
127 if (Ty->isBlockPointerType())
128 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000129 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000130 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000131 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000132 return;
133
134 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000135 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000136 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000137 return;
138 }
139 int sentinel = i;
140 while (sentinelPos > 0 && i < NumArgs-1) {
141 --sentinelPos;
142 ++i;
143 }
144 if (sentinelPos > 0) {
145 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000146 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000147 return;
148 }
149 while (i < NumArgs-1) {
150 ++i;
151 ++sentinel;
152 }
153 Expr *sentinelExpr = Args[sentinel];
154 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
Douglas Gregorce940492009-09-25 04:25:58 +0000155 !sentinelExpr->isNullPointerConstant(Context,
156 Expr::NPC_ValueDependentIsNull))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000157 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000158 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000159 }
160 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000161}
162
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000163SourceRange Sema::getExprRange(ExprTy *E) const {
164 Expr *Ex = (Expr *)E;
165 return Ex? Ex->getSourceRange() : SourceRange();
166}
167
Chris Lattnere7a2e912008-07-25 21:10:04 +0000168//===----------------------------------------------------------------------===//
169// Standard Promotions and Conversions
170//===----------------------------------------------------------------------===//
171
Chris Lattnere7a2e912008-07-25 21:10:04 +0000172/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
173void Sema::DefaultFunctionArrayConversion(Expr *&E) {
174 QualType Ty = E->getType();
175 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
176
Chris Lattnere7a2e912008-07-25 21:10:04 +0000177 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000178 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000179 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000180 else if (Ty->isArrayType()) {
181 // In C90 mode, arrays only promote to pointers if the array expression is
182 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
183 // type 'array of type' is converted to an expression that has type 'pointer
184 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
185 // that has type 'array of type' ...". The relevant change is "an lvalue"
186 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000187 //
188 // C++ 4.2p1:
189 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
190 // T" can be converted to an rvalue of type "pointer to T".
191 //
192 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
193 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000194 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
195 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000196 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000197}
198
199/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000200/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000201/// sometimes surpressed. For example, the array->pointer conversion doesn't
202/// apply if the array is an argument to the sizeof or address (&) operators.
203/// In these instances, this routine should *not* be called.
204Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
205 QualType Ty = Expr->getType();
206 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Douglas Gregorfc24e442009-05-01 20:41:21 +0000208 // C99 6.3.1.1p2:
209 //
210 // The following may be used in an expression wherever an int or
211 // unsigned int may be used:
212 // - an object or expression with an integer type whose integer
213 // conversion rank is less than or equal to the rank of int
214 // and unsigned int.
215 // - A bit-field of type _Bool, int, signed int, or unsigned int.
216 //
217 // If an int can represent all values of the original type, the
218 // value is converted to an int; otherwise, it is converted to an
219 // unsigned int. These are called the integer promotions. All
220 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000221 QualType PTy = Context.isPromotableBitField(Expr);
222 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000223 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000224 return Expr;
225 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000226 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000227 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000228 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000229 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000230 }
231
Douglas Gregorfc24e442009-05-01 20:41:21 +0000232 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000233 return Expr;
234}
235
Chris Lattner05faf172008-07-25 22:25:12 +0000236/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000237/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000238/// double. All other argument types are converted by UsualUnaryConversions().
239void Sema::DefaultArgumentPromotion(Expr *&Expr) {
240 QualType Ty = Expr->getType();
241 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chris Lattner05faf172008-07-25 22:25:12 +0000243 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000244 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000245 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000246 return ImpCastExprToType(Expr, Context.DoubleTy,
247 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Chris Lattner05faf172008-07-25 22:25:12 +0000249 UsualUnaryConversions(Expr);
250}
251
Chris Lattner312531a2009-04-12 08:11:20 +0000252/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
253/// will warn if the resulting type is not a POD type, and rejects ObjC
254/// interfaces passed by value. This returns true if the argument type is
255/// completely illegal.
256bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000257 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Chris Lattner312531a2009-04-12 08:11:20 +0000259 if (Expr->getType()->isObjCInterfaceType()) {
260 Diag(Expr->getLocStart(),
261 diag::err_cannot_pass_objc_interface_to_vararg)
262 << Expr->getType() << CT;
263 return true;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000264 }
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Chris Lattner312531a2009-04-12 08:11:20 +0000266 if (!Expr->getType()->isPODType())
267 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
268 << Expr->getType() << CT;
269
270 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000271}
272
273
Chris Lattnere7a2e912008-07-25 21:10:04 +0000274/// UsualArithmeticConversions - Performs various conversions that are common to
275/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000276/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000277/// responsible for emitting appropriate error diagnostics.
278/// FIXME: verify the conversion rules for "complex int" are consistent with
279/// GCC.
280QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
281 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000282 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000283 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000284
285 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000286
Mike Stump1eb44332009-09-09 15:08:12 +0000287 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000288 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000289 QualType lhs =
290 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000291 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000292 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000293
294 // If both types are identical, no conversion is needed.
295 if (lhs == rhs)
296 return lhs;
297
298 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
299 // The caller can deal with this (e.g. pointer + int).
300 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
301 return lhs;
302
Douglas Gregor2d833e32009-05-02 00:36:19 +0000303 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000304 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000305 if (!LHSBitfieldPromoteTy.isNull())
306 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000307 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000308 if (!RHSBitfieldPromoteTy.isNull())
309 rhs = RHSBitfieldPromoteTy;
310
Eli Friedmana95d7572009-08-19 07:44:53 +0000311 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000312 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000313 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
314 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000315 return destType;
316}
317
Chris Lattnere7a2e912008-07-25 21:10:04 +0000318//===----------------------------------------------------------------------===//
319// Semantic Analysis for various Expression Types
320//===----------------------------------------------------------------------===//
321
322
Steve Narofff69936d2007-09-16 03:34:24 +0000323/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000324/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
325/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
326/// multiple tokens. However, the common case is that StringToks points to one
327/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000328///
329Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000330Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 assert(NumStringToks && "Must have at least one string!");
332
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000333 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000335 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000336
337 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
338 for (unsigned i = 0; i != NumStringToks; ++i)
339 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000340
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000341 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000342 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000343 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000344
345 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
346 if (getLangOptions().CPlusPlus)
347 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000348
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000349 // Get an array type for the string, according to C99 6.4.5. This includes
350 // the nul terminator character as well as the string length for pascal
351 // strings.
352 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000353 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000354 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000357 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000358 Literal.GetStringLength(),
359 Literal.AnyWide, StrTy,
360 &StringTokLocs[0],
361 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000362}
363
Chris Lattner639e2d32008-10-20 05:16:36 +0000364/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
365/// CurBlock to VD should cause it to be snapshotted (as we do for auto
366/// variables defined outside the block) or false if this is not needed (e.g.
367/// for values inside the block or for globals).
368///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000369/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
370/// up-to-date.
371///
Chris Lattner639e2d32008-10-20 05:16:36 +0000372static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
373 ValueDecl *VD) {
374 // If the value is defined inside the block, we couldn't snapshot it even if
375 // we wanted to.
376 if (CurBlock->TheDecl == VD->getDeclContext())
377 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattner639e2d32008-10-20 05:16:36 +0000379 // If this is an enum constant or function, it is constant, don't snapshot.
380 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
381 return false;
382
383 // If this is a reference to an extern, static, or global variable, no need to
384 // snapshot it.
385 // FIXME: What about 'const' variables in C++?
386 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000387 if (!Var->hasLocalStorage())
388 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000390 // Blocks that have these can't be constant.
391 CurBlock->hasBlockDeclRefExprs = true;
392
393 // If we have nested blocks, the decl may be declared in an outer block (in
394 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
395 // be defined outside all of the current blocks (in which case the blocks do
396 // all get the bit). Walk the nesting chain.
397 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
398 NextBlock = NextBlock->PrevBlockInfo) {
399 // If we found the defining block for the variable, don't mark the block as
400 // having a reference outside it.
401 if (NextBlock->TheDecl == VD->getDeclContext())
402 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000404 // Otherwise, the DeclRef from the inner block causes the outer one to need
405 // a snapshot as well.
406 NextBlock->hasBlockDeclRefExprs = true;
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner639e2d32008-10-20 05:16:36 +0000409 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000410}
411
Chris Lattner639e2d32008-10-20 05:16:36 +0000412
413
Douglas Gregora2813ce2009-10-23 18:54:35 +0000414/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000415Sema::OwningExprResult
Sebastian Redlebc07d52009-02-03 20:19:35 +0000416Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
417 bool TypeDependent, bool ValueDependent,
418 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000419 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
420 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000421 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000422 << D->getDeclName();
423 return ExprError();
424 }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Anders Carlssone41590d2009-06-24 00:10:43 +0000426 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
427 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
428 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
429 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000430 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000431 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000432 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000433 << D->getIdentifier();
434 return ExprError();
435 }
436 }
437 }
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Douglas Gregore0762c92009-06-19 23:52:42 +0000440 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Douglas Gregora2813ce2009-10-23 18:54:35 +0000442 return Owned(DeclRefExpr::Create(Context,
443 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
444 SS? SS->getRange() : SourceRange(),
445 D, Loc,
446 Ty, TypeDependent, ValueDependent));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000447}
448
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000449/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
450/// variable corresponding to the anonymous union or struct whose type
451/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000452static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
453 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000454 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000455 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Mike Stump390b4cc2009-05-16 07:39:55 +0000457 // FIXME: Once Decls are directly linked together, this will be an O(1)
458 // operation rather than a slow walk through DeclContext's vector (which
459 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000460 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000461 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000462 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000463 D != DEnd; ++D) {
464 if (*D == Record) {
465 // The object for the anonymous struct/union directly
466 // follows its type in the list of declarations.
467 ++D;
468 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000469 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000470 return *D;
471 }
472 }
473
474 assert(false && "Missing object for anonymous record");
475 return 0;
476}
477
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000478/// \brief Given a field that represents a member of an anonymous
479/// struct/union, build the path from that field's context to the
480/// actual member.
481///
482/// Construct the sequence of field member references we'll have to
483/// perform to get to the field in the anonymous union/struct. The
484/// list of members is built from the field outward, so traverse it
485/// backwards to go from an object in the current context to the field
486/// we found.
487///
488/// \returns The variable from which the field access should begin,
489/// for an anonymous struct/union that is not a member of another
490/// class. Otherwise, returns NULL.
491VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
492 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000493 assert(Field->getDeclContext()->isRecord() &&
494 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
495 && "Field must be stored inside an anonymous struct or union");
496
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000497 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000498 VarDecl *BaseObject = 0;
499 DeclContext *Ctx = Field->getDeclContext();
500 do {
501 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000502 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000503 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000504 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000505 else {
506 BaseObject = cast<VarDecl>(AnonObject);
507 break;
508 }
509 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000510 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000511 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000512
513 return BaseObject;
514}
515
516Sema::OwningExprResult
517Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
518 FieldDecl *Field,
519 Expr *BaseObjectExpr,
520 SourceLocation OpLoc) {
521 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000522 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000523 AnonFields);
524
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000525 // Build the expression that refers to the base object, from
526 // which we will build a sequence of member references to each
527 // of the anonymous union objects and, eventually, the field we
528 // found via name lookup.
529 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000530 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000531 if (BaseObject) {
532 // BaseObject is an anonymous struct/union variable (and is,
533 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000534 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000535 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000536 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000537 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000538 BaseQuals
539 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000540 } else if (BaseObjectExpr) {
541 // The caller provided the base object expression. Determine
542 // whether its a pointer and whether it adds any qualifiers to the
543 // anonymous struct/union fields we're looking into.
544 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000545 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000546 BaseObjectIsPointer = true;
547 ObjectType = ObjectPtr->getPointeeType();
548 }
John McCall0953e762009-09-24 19:53:00 +0000549 BaseQuals
550 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000551 } else {
552 // We've found a member of an anonymous struct/union that is
553 // inside a non-anonymous struct/union, so in a well-formed
554 // program our base object expression is "this".
555 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
556 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000557 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000558 = Context.getTagDeclType(
559 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
560 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000561 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000562 == Context.getCanonicalType(ThisType)) ||
563 IsDerivedFrom(ThisType, AnonFieldType)) {
564 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000566 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000567 BaseObjectIsPointer = true;
568 }
569 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000570 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
571 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000572 }
John McCall0953e762009-09-24 19:53:00 +0000573 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000574 }
575
Mike Stump1eb44332009-09-09 15:08:12 +0000576 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000577 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
578 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000579 }
580
581 // Build the implicit member references to the field of the
582 // anonymous struct/union.
583 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000584 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000585 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
586 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
587 FI != FIEnd; ++FI) {
588 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000589 Qualifiers MemberTypeQuals =
590 Context.getCanonicalType(MemberType).getQualifiers();
591
592 // CVR attributes from the base are picked up by members,
593 // except that 'mutable' members don't pick up 'const'.
594 if ((*FI)->isMutable())
595 ResultQuals.removeConst();
596
597 // GC attributes are never picked up by members.
598 ResultQuals.removeObjCGCAttr();
599
600 // TR 18037 does not allow fields to be declared with address spaces.
601 assert(!MemberTypeQuals.hasAddressSpace());
602
603 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
604 if (NewQuals != MemberTypeQuals)
605 MemberType = Context.getQualifiedType(MemberType, NewQuals);
606
Douglas Gregore0762c92009-06-19 23:52:42 +0000607 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000608 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000609 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
610 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000611 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000612 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000613 }
614
Sebastian Redlcd965b92009-01-18 18:53:16 +0000615 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000616}
617
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000618Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
619 const CXXScopeSpec &SS,
620 UnqualifiedId &Name,
621 bool HasTrailingLParen,
622 bool IsAddressOfOperand) {
623 if (Name.getKind() == UnqualifiedId::IK_TemplateId) {
624 ASTTemplateArgsPtr TemplateArgsPtr(*this,
625 Name.TemplateId->getTemplateArgs(),
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000626 Name.TemplateId->NumArgs);
627 return ActOnTemplateIdExpr(SS,
628 TemplateTy::make(Name.TemplateId->Template),
629 Name.TemplateId->TemplateNameLoc,
630 Name.TemplateId->LAngleLoc,
631 TemplateArgsPtr,
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000632 Name.TemplateId->RAngleLoc);
633 }
634
635 // FIXME: We lose a bunch of source information by doing this. Later,
636 // we'll want to merge ActOnDeclarationNameExpr's logic into
637 // ActOnIdExpression.
638 return ActOnDeclarationNameExpr(S,
639 Name.StartLocation,
640 GetNameFromUnqualifiedId(Name),
641 HasTrailingLParen,
642 &SS,
643 IsAddressOfOperand);
644}
645
Douglas Gregor10c42622008-11-18 15:03:34 +0000646/// ActOnDeclarationNameExpr - The parser has read some kind of name
647/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
648/// performs lookup on that name and returns an expression that refers
649/// to that name. This routine isn't directly called from the parser,
650/// because the parser doesn't know about DeclarationName. Rather,
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000651/// this routine is called by ActOnIdExpression, which contains a
652/// parsed UnqualifiedId.
Douglas Gregor10c42622008-11-18 15:03:34 +0000653///
654/// HasTrailingLParen indicates whether this identifier is used in a
655/// function call context. LookupCtx is only used for a C++
656/// qualified-id (foo::bar) to indicate the class or namespace that
657/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000658///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000659/// isAddressOfOperand means that this expression is the direct operand
660/// of an address-of operator. This matters because this is the only
661/// situation where a qualified name referencing a non-static member may
662/// appear outside a member function of this class.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000663Sema::OwningExprResult
664Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
665 DeclarationName Name, bool HasTrailingLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000666 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000667 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000668 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000669 if (SS && SS->isInvalid())
670 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000671
672 // C++ [temp.dep.expr]p3:
673 // An id-expression is type-dependent if it contains:
674 // -- a nested-name-specifier that contains a class-name that
675 // names a dependent type.
Douglas Gregor00c44862009-05-29 14:49:33 +0000676 // FIXME: Member of the current instantiation.
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000677 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000678 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
Mike Stump1eb44332009-09-09 15:08:12 +0000679 Loc, SS->getRange(),
Anders Carlsson9b31df42009-07-09 00:05:08 +0000680 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
681 isAddressOfOperand));
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000682 }
683
John McCalla24dc2e2009-11-17 02:14:36 +0000684 LookupResult Lookup(*this, Name, Loc, LookupOrdinaryName);
685 LookupParsedName(Lookup, S, SS, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000686
John McCalla24dc2e2009-11-17 02:14:36 +0000687 if (Lookup.isAmbiguous())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000688 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000689
John McCallf36e02d2009-10-09 21:13:30 +0000690 NamedDecl *D = Lookup.getAsSingleDecl(Context);
Douglas Gregor5c37de72008-12-06 00:22:45 +0000691
Chris Lattner8a934232008-03-31 00:36:02 +0000692 // If this reference is in an Objective-C method, then ivar lookup happens as
693 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000694 IdentifierInfo *II = Name.getAsIdentifierInfo();
695 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000696 // There are two cases to handle here. 1) scoped lookup could have failed,
697 // in which case we should look for an ivar. 2) scoped lookup could have
Mike Stump1eb44332009-09-09 15:08:12 +0000698 // found a decl, but that decl is outside the current instance method (i.e.
699 // a global variable). In these two cases, we do a lookup for an ivar with
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000700 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000701 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000702 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000703 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000704 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000705 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000706 if (DiagnoseUseOfDecl(IV, Loc))
707 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattner5cb10d32009-04-24 22:30:50 +0000709 // If we're referencing an invalid decl, just return this as a silent
710 // error node. The error diagnostic was already emitted on the decl.
711 if (IV->isInvalidDecl())
712 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000714 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
715 // If a class method attemps to use a free standing ivar, this is
716 // an error.
717 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
718 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
719 << IV->getDeclName());
720 // If a class method uses a global variable, even if an ivar with
721 // same name exists, use the global.
722 if (!IsClsMethod) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000723 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
724 ClassDeclared != IFace)
725 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stump390b4cc2009-05-16 07:39:55 +0000726 // FIXME: This should use a new expr for a direct reference, don't
727 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000728 IdentifierInfo &II = Context.Idents.get("self");
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000729 UnqualifiedId SelfName;
730 SelfName.setIdentifier(&II, SourceLocation());
731 CXXScopeSpec SelfScopeSpec;
732 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
733 SelfName, false, false);
Douglas Gregore0762c92009-06-19 23:52:42 +0000734 MarkDeclarationReferenced(Loc, IV);
Mike Stump1eb44332009-09-09 15:08:12 +0000735 return Owned(new (Context)
736 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlssone9146f22009-05-01 19:49:17 +0000737 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000738 }
Chris Lattner8a934232008-03-31 00:36:02 +0000739 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000740 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000741 // We should warn if a local variable hides an ivar.
742 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000743 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000744 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000745 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
746 IFace == ClassDeclared)
Chris Lattner5cb10d32009-04-24 22:30:50 +0000747 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000748 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000749 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000750 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000751 if (D == 0 && II->isStr("super")) {
Steve Naroffdd53eb52009-03-05 20:12:00 +0000752 QualType T;
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Steve Naroffdd53eb52009-03-05 20:12:00 +0000754 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff14108da2009-07-10 23:34:53 +0000755 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
756 getCurMethodDecl()->getClassInterface()));
Steve Naroffdd53eb52009-03-05 20:12:00 +0000757 else
758 T = Context.getObjCClassType();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000759 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000760 }
Chris Lattner8a934232008-03-31 00:36:02 +0000761 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000762
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000763 // Determine whether this name might be a candidate for
764 // argument-dependent lookup.
Mike Stump1eb44332009-09-09 15:08:12 +0000765 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000766 HasTrailingLParen;
767
768 if (ADL && D == 0) {
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000769 // We've seen something of the form
770 //
771 // identifier(
772 //
773 // and we did not find any entity by the name
774 // "identifier". However, this identifier is still subject to
775 // argument-dependent lookup, so keep track of the name.
776 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
777 Context.OverloadTy,
778 Loc));
779 }
780
Reid Spencer5f016e22007-07-11 17:01:13 +0000781 if (D == 0) {
782 // Otherwise, this could be an implicitly declared function reference (legal
783 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000784 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000785 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000786 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 else {
788 // If this name wasn't predeclared and if this is not a function call,
789 // diagnose the problem.
Douglas Gregor3f093272009-10-13 21:16:44 +0000790 if (SS && !SS->isEmpty())
791 return ExprError(Diag(Loc, diag::err_no_member)
792 << Name << computeDeclContext(*SS, false)
793 << SS->getRange());
794 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000795 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000796 return ExprError(Diag(Loc, diag::err_undeclared_use)
797 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000798 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000799 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 }
801 }
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Douglas Gregor751f9a42009-06-30 15:47:41 +0000803 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
804 // Warn about constructs like:
805 // if (void *X = foo()) { ... } else { X }.
806 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Douglas Gregor751f9a42009-06-30 15:47:41 +0000808 // FIXME: In a template instantiation, we don't have scope
809 // information to check this property.
810 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
811 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000812 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000813 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000814 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000815 ExprError(Diag(Loc, diag::warn_value_always_zero)
816 << Var->getDeclName()
817 << (Var->getType()->isPointerType()? 2 :
818 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +0000819 break;
820 }
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000822 // Move to the parent of this scope.
823 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +0000824 }
825 }
826 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
827 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
828 // C99 DR 316 says that, if a function type comes from a
829 // function definition (without a prototype), that type is only
830 // used for checking compatibility. Therefore, when referencing
831 // the function, we pretend that we don't have the full function
832 // type.
833 if (DiagnoseUseOfDecl(Func, Loc))
834 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000835
Douglas Gregor751f9a42009-06-30 15:47:41 +0000836 QualType T = Func->getType();
837 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +0000838 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +0000839 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
840 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
841 }
842 }
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Douglas Gregor751f9a42009-06-30 15:47:41 +0000844 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
845}
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000846/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000847bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000848Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
849 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +0000850 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000851 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000852 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000853 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000854 if (DestType->isDependentType() || From->getType()->isDependentType())
855 return false;
856 QualType FromRecordType = From->getType();
857 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +0000858 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000859 DestType = Context.getPointerType(DestType);
860 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000861 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000862 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
863 CheckDerivedToBaseConversion(FromRecordType,
864 DestRecordType,
865 From->getSourceRange().getBegin(),
866 From->getSourceRange()))
867 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +0000868 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
869 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000870 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000871 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000872}
Douglas Gregor751f9a42009-06-30 15:47:41 +0000873
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000874/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +0000875static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
876 const CXXScopeSpec *SS, NamedDecl *Member,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000877 SourceLocation Loc, QualType Ty) {
878 if (SS && SS->isSet())
Mike Stump1eb44332009-09-09 15:08:12 +0000879 return MemberExpr::Create(C, Base, isArrow,
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000880 (NestedNameSpecifier *)SS->getScopeRep(),
Mike Stump1eb44332009-09-09 15:08:12 +0000881 SS->getRange(), Member, Loc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +0000882 // FIXME: Explicit template argument lists
883 false, SourceLocation(), 0, 0, SourceLocation(),
884 Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000886 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
887}
888
Douglas Gregor751f9a42009-06-30 15:47:41 +0000889/// \brief Complete semantic analysis for a reference to the given declaration.
890Sema::OwningExprResult
891Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
892 bool HasTrailingLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000893 const CXXScopeSpec *SS,
Douglas Gregor751f9a42009-06-30 15:47:41 +0000894 bool isAddressOfOperand) {
895 assert(D && "Cannot refer to a NULL declaration");
896 DeclarationName Name = D->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Sebastian Redlebc07d52009-02-03 20:19:35 +0000898 // If this is an expression of the form &Class::member, don't build an
899 // implicit member ref, because we want a pointer to the member in general,
900 // not any specific instance's member.
901 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000902 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000903 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000904 QualType DType;
905 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
906 DType = FD->getType().getNonReferenceType();
907 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
908 DType = Method->getType();
909 } else if (isa<OverloadedFunctionDecl>(D)) {
910 DType = Context.OverloadTy;
911 }
912 // Could be an inner type. That's diagnosed below, so ignore it here.
913 if (!DType.isNull()) {
914 // The pointer is type- and value-dependent if it points into something
915 // dependent.
Douglas Gregor00c44862009-05-29 14:49:33 +0000916 bool Dependent = DC->isDependentContext();
Anders Carlssone41590d2009-06-24 00:10:43 +0000917 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redlebc07d52009-02-03 20:19:35 +0000918 }
919 }
920 }
921
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000922 // We may have found a field within an anonymous union or struct
923 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +0000924 // FIXME: This needs to happen post-isImplicitMemberReference?
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000925 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
926 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
927 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000928
Douglas Gregore961afb2009-10-22 07:08:30 +0000929 // Cope with an implicit member access in a C++ non-static member function.
930 QualType ThisType, MemberType;
931 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
932 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
933 MarkDeclarationReferenced(Loc, D);
934 if (PerformObjectMemberConversion(This, D))
935 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +0000936
Douglas Gregore961afb2009-10-22 07:08:30 +0000937 bool ShouldCheckUse = true;
938 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
939 // Don't diagnose the use of a virtual member function unless it's
940 // explicitly qualified.
941 if (MD->isVirtual() && (!SS || !SS->isSet()))
942 ShouldCheckUse = false;
Douglas Gregor88a35142008-12-22 05:46:06 +0000943 }
Douglas Gregore961afb2009-10-22 07:08:30 +0000944
945 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
946 return ExprError();
947 return Owned(BuildMemberExpr(Context, This, true, SS, D,
948 Loc, MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000949 }
950
Douglas Gregor44b43212008-12-11 16:49:14 +0000951 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
953 if (MD->isStatic())
954 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000955 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
956 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000957 }
958
Douglas Gregor88a35142008-12-22 05:46:06 +0000959 // Any other ways we could have found the field in a well-formed
960 // program would have been turned into implicit member expressions
961 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000962 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
963 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000964 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000965
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000967 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000968 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000969 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000970 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000971 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000972
Steve Naroffdd972f22008-09-05 22:11:13 +0000973 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000974 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +0000975 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
976 false, false, SS);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000977 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +0000978 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
979 false, false, SS);
John McCall7ba107a2009-11-18 02:36:19 +0000980 else if (UnresolvedUsingValueDecl *UD = dyn_cast<UnresolvedUsingValueDecl>(D))
Mike Stump1eb44332009-09-09 15:08:12 +0000981 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
982 /*TypeDependent=*/true,
Anders Carlsson598da5b2009-08-29 01:06:32 +0000983 /*ValueDependent=*/true, SS);
984
Steve Naroffdd972f22008-09-05 22:11:13 +0000985 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000986
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000987 // Check whether this declaration can be used. Note that we suppress
988 // this check when we're going to perform argument-dependent lookup
989 // on this function name, because this might not be the function
990 // that overload resolution actually selects.
Mike Stump1eb44332009-09-09 15:08:12 +0000991 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000992 HasTrailingLParen;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000993 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
994 return ExprError();
995
Steve Naroffdd972f22008-09-05 22:11:13 +0000996 // Only create DeclRefExpr's for valid Decl's.
997 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000998 return ExprError();
999
Chris Lattner639e2d32008-10-20 05:16:36 +00001000 // If the identifier reference is inside a block, and it refers to a value
1001 // that is outside the block, create a BlockDeclRefExpr instead of a
1002 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1003 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001004 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001005 // We do not do this for things like enum constants, global variables, etc,
1006 // as they do not get snapshotted.
1007 //
1008 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001009 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001010 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001011 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001012 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001013 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001014 // This is to record that a 'const' was actually synthesize and added.
1015 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001016 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Eli Friedman5fdeae12009-03-22 23:00:19 +00001018 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001019 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001020 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001021 }
1022 // If this reference is not in a block or if the referenced variable is
1023 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001024
Douglas Gregor898574e2008-12-05 23:32:09 +00001025 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +00001026 bool ValueDependent = false;
1027 if (getLangOptions().CPlusPlus) {
1028 // C++ [temp.dep.expr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001029 // An id-expression is type-dependent if it contains:
Douglas Gregor83f96f62008-12-10 20:57:37 +00001030 // - an identifier that was declared with a dependent type,
1031 if (VD->getType()->isDependentType())
1032 TypeDependent = true;
1033 // - FIXME: a template-id that is dependent,
1034 // - a conversion-function-id that specifies a dependent type,
1035 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1036 Name.getCXXNameType()->isDependentType())
1037 TypeDependent = true;
1038 // - a nested-name-specifier that contains a class-name that
1039 // names a dependent type.
1040 else if (SS && !SS->isEmpty()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001041 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor83f96f62008-12-10 20:57:37 +00001042 DC; DC = DC->getParent()) {
1043 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001044 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001045 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1046 if (Context.getTypeDeclType(Record)->isDependentType()) {
1047 TypeDependent = true;
1048 break;
1049 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001050 }
1051 }
1052 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001053
Douglas Gregor83f96f62008-12-10 20:57:37 +00001054 // C++ [temp.dep.constexpr]p2:
1055 //
1056 // An identifier is value-dependent if it is:
1057 // - a name declared with a dependent type,
1058 if (TypeDependent)
1059 ValueDependent = true;
1060 // - the name of a non-type template parameter,
1061 else if (isa<NonTypeTemplateParmDecl>(VD))
1062 ValueDependent = true;
1063 // - a constant with integral or enumeration type and is
1064 // initialized with an expression that is value-dependent
Eli Friedmanc1494122009-06-11 01:11:20 +00001065 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
Mike Stumpfbf68702009-11-03 22:20:01 +00001066 if (Context.getCanonicalType(Dcl->getType()).getCVRQualifiers()
1067 == Qualifiers::Const &&
Eli Friedmanc1494122009-06-11 01:11:20 +00001068 Dcl->getInit()) {
1069 ValueDependent = Dcl->getInit()->isValueDependent();
1070 }
1071 }
Douglas Gregor83f96f62008-12-10 20:57:37 +00001072 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001073
Anders Carlssone41590d2009-06-24 00:10:43 +00001074 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1075 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001076}
1077
Sebastian Redlcd965b92009-01-18 18:53:16 +00001078Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1079 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001080 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001081
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001083 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001084 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1085 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1086 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001088
Chris Lattnerfa28b302008-01-12 08:14:25 +00001089 // Pre-defined identifiers are of type char[x], where x is the length of the
1090 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Anders Carlsson3a082d82009-09-08 18:24:21 +00001092 Decl *currentDecl = getCurFunctionOrMethodDecl();
1093 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001094 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001095 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001096 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001097
Anders Carlsson773f3972009-09-11 01:22:35 +00001098 QualType ResTy;
1099 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1100 ResTy = Context.DependentTy;
1101 } else {
1102 unsigned Length =
1103 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001104
Anders Carlsson773f3972009-09-11 01:22:35 +00001105 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001106 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001107 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1108 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001109 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001110}
1111
Sebastian Redlcd965b92009-01-18 18:53:16 +00001112Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 llvm::SmallString<16> CharBuffer;
1114 CharBuffer.resize(Tok.getLength());
1115 const char *ThisTokBegin = &CharBuffer[0];
1116 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001117
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1119 Tok.getLocation(), PP);
1120 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001121 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001122
1123 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1124
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001125 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1126 Literal.isWide(),
1127 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001128}
1129
Sebastian Redlcd965b92009-01-18 18:53:16 +00001130Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1131 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1133 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001134 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001135 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001136 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001137 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 }
Ted Kremenek28396602009-01-13 23:19:12 +00001139
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001141 // Add padding so that NumericLiteralParser can overread by one character.
1142 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001144
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 // Get the spelling of the token, which eliminates trigraphs, etc.
1146 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001147
Mike Stump1eb44332009-09-09 15:08:12 +00001148 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001149 Tok.getLocation(), PP);
1150 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001151 return ExprError();
1152
Chris Lattner5d661452007-08-26 03:42:43 +00001153 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001154
Chris Lattner5d661452007-08-26 03:42:43 +00001155 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001156 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001157 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001158 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001159 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001160 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001161 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001162 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001163
1164 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1165
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001166 // isExact will be set by GetFloatValue().
1167 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001168 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1169 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001170
Chris Lattner5d661452007-08-26 03:42:43 +00001171 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001172 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001173 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001174 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001175
Neil Boothb9449512007-08-29 22:00:19 +00001176 // long long is a C99 feature.
1177 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001178 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001179 Diag(Tok.getLocation(), diag::ext_longlong);
1180
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001182 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001183
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 if (Literal.GetIntegerValue(ResultVal)) {
1185 // If this value didn't fit into uintmax_t, warn and force to ull.
1186 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001187 Ty = Context.UnsignedLongLongTy;
1188 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001189 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 } else {
1191 // If this value fits into a ULL, try to figure out what else it fits into
1192 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001193
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1195 // be an unsigned int.
1196 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1197
1198 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001199 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001200 if (!Literal.isLong && !Literal.isLongLong) {
1201 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001202 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 // Does it fit in a unsigned int?
1205 if (ResultVal.isIntN(IntSize)) {
1206 // Does it fit in a signed int?
1207 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001208 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001210 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001211 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001216 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001217 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 // Does it fit in a unsigned long?
1220 if (ResultVal.isIntN(LongSize)) {
1221 // Does it fit in a signed long?
1222 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001223 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001225 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001226 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001228 }
1229
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001231 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001232 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001233
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 // Does it fit in a unsigned long long?
1235 if (ResultVal.isIntN(LongLongSize)) {
1236 // Does it fit in a signed long long?
1237 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001238 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001240 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001241 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 }
1243 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001244
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 // If we still couldn't decide a type, we probably have something that
1246 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001247 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001249 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001250 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001252
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001253 if (ResultVal.getBitWidth() != Width)
1254 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001256 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001258
Chris Lattner5d661452007-08-26 03:42:43 +00001259 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1260 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001261 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001262 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001263
1264 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001265}
1266
Sebastian Redlcd965b92009-01-18 18:53:16 +00001267Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1268 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001269 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001270 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001271 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001272}
1273
1274/// The UsualUnaryConversions() function is *not* called by this routine.
1275/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001276bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001277 SourceLocation OpLoc,
1278 const SourceRange &ExprRange,
1279 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001280 if (exprType->isDependentType())
1281 return false;
1282
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001284 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001285 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001286 if (isSizeof)
1287 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1288 return false;
1289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Chris Lattner1efaa952009-04-24 00:30:45 +00001291 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001292 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001293 Diag(OpLoc, diag::ext_sizeof_void_type)
1294 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001295 return false;
1296 }
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Chris Lattner1efaa952009-04-24 00:30:45 +00001298 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001299 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001300 PDiag(diag::err_alignof_incomplete_type)
1301 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001302 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Chris Lattner1efaa952009-04-24 00:30:45 +00001304 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001305 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001306 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001307 << exprType << isSizeof << ExprRange;
1308 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001309 }
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Chris Lattner1efaa952009-04-24 00:30:45 +00001311 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001312}
1313
Chris Lattner31e21e02009-01-24 20:17:12 +00001314bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1315 const SourceRange &ExprRange) {
1316 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001317
Mike Stump1eb44332009-09-09 15:08:12 +00001318 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001319 if (isa<DeclRefExpr>(E))
1320 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001321
1322 // Cannot know anything else if the expression is dependent.
1323 if (E->isTypeDependent())
1324 return false;
1325
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001326 if (E->getBitField()) {
1327 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1328 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001329 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001330
1331 // Alignment of a field access is always okay, so long as it isn't a
1332 // bit-field.
1333 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001334 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001335 return false;
1336
Chris Lattner31e21e02009-01-24 20:17:12 +00001337 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1338}
1339
Douglas Gregorba498172009-03-13 21:01:28 +00001340/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001341Action::OwningExprResult
John McCall5ab75172009-11-04 07:28:41 +00001342Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1343 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001344 bool isSizeOf, SourceRange R) {
John McCall5ab75172009-11-04 07:28:41 +00001345 if (!DInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001346 return ExprError();
1347
John McCall5ab75172009-11-04 07:28:41 +00001348 QualType T = DInfo->getType();
1349
Douglas Gregorba498172009-03-13 21:01:28 +00001350 if (!T->isDependentType() &&
1351 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1352 return ExprError();
1353
1354 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCall5ab75172009-11-04 07:28:41 +00001355 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001356 Context.getSizeType(), OpLoc,
1357 R.getEnd()));
1358}
1359
1360/// \brief Build a sizeof or alignof expression given an expression
1361/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001362Action::OwningExprResult
1363Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001364 bool isSizeOf, SourceRange R) {
1365 // Verify that the operand is valid.
1366 bool isInvalid = false;
1367 if (E->isTypeDependent()) {
1368 // Delay type-checking for type-dependent expressions.
1369 } else if (!isSizeOf) {
1370 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001371 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001372 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1373 isInvalid = true;
1374 } else {
1375 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1376 }
1377
1378 if (isInvalid)
1379 return ExprError();
1380
1381 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1382 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1383 Context.getSizeType(), OpLoc,
1384 R.getEnd()));
1385}
1386
Sebastian Redl05189992008-11-11 17:56:53 +00001387/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1388/// the same for @c alignof and @c __alignof
1389/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001390Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001391Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1392 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001394 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001395
Sebastian Redl05189992008-11-11 17:56:53 +00001396 if (isType) {
John McCall5ab75172009-11-04 07:28:41 +00001397 DeclaratorInfo *DInfo;
1398 (void) GetTypeFromParser(TyOrEx, &DInfo);
1399 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001400 }
Sebastian Redl05189992008-11-11 17:56:53 +00001401
Douglas Gregorba498172009-03-13 21:01:28 +00001402 Expr *ArgEx = (Expr *)TyOrEx;
1403 Action::OwningExprResult Result
1404 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1405
1406 if (Result.isInvalid())
1407 DeleteExpr(ArgEx);
1408
1409 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001410}
1411
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001412QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001413 if (V->isTypeDependent())
1414 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Chris Lattnercc26ed72007-08-26 05:39:26 +00001416 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001417 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001418 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Chris Lattnercc26ed72007-08-26 05:39:26 +00001420 // Otherwise they pass through real integer and floating point types here.
1421 if (V->getType()->isArithmeticType())
1422 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Chris Lattnercc26ed72007-08-26 05:39:26 +00001424 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001425 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1426 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001427 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001428}
1429
1430
Reid Spencer5f016e22007-07-11 17:01:13 +00001431
Sebastian Redl0eb23302009-01-19 00:08:26 +00001432Action::OwningExprResult
1433Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1434 tok::TokenKind Kind, ExprArg Input) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001435 // Since this might be a postfix expression, get rid of ParenListExprs.
1436 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001437 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001438
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 UnaryOperator::Opcode Opc;
1440 switch (Kind) {
1441 default: assert(0 && "Unknown unary op!");
1442 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1443 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1444 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001445
Douglas Gregor74253732008-11-19 15:42:04 +00001446 if (getLangOptions().CPlusPlus &&
1447 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1448 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001449 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001450 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1451
1452 // C++ [over.inc]p1:
1453 //
1454 // [...] If the function is a member function with one
1455 // parameter (which shall be of type int) or a non-member
1456 // function with two parameters (the second of which shall be
1457 // of type int), it defines the postfix increment operator ++
1458 // for objects of that type. When the postfix increment is
1459 // called as a result of using the ++ operator, the int
1460 // argument will have value zero.
Mike Stump1eb44332009-09-09 15:08:12 +00001461 Expr *Args[2] = {
1462 Arg,
1463 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001464 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001465 };
1466
1467 // Build the candidate set for overloading
1468 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00001469 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor74253732008-11-19 15:42:04 +00001470
1471 // Perform overload resolution.
1472 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001473 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor74253732008-11-19 15:42:04 +00001474 case OR_Success: {
1475 // We found a built-in operator or an overloaded operator.
1476 FunctionDecl *FnDecl = Best->Function;
1477
1478 if (FnDecl) {
1479 // We matched an overloaded operator. Build a call to that
1480 // operator.
1481
1482 // Convert the arguments.
1483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1484 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001485 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001486 } else {
1487 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001488 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001489 FnDecl->getParamDecl(0)->getType(),
1490 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001491 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001492 }
1493
1494 // Determine the result type
Anders Carlsson07d68f12009-10-13 21:49:31 +00001495 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001496
Douglas Gregor74253732008-11-19 15:42:04 +00001497 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001498 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump488e25b2009-02-19 02:54:59 +00001499 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00001500 UsualUnaryConversions(FnExpr);
1501
Sebastian Redl0eb23302009-01-19 00:08:26 +00001502 Input.release();
Douglas Gregor7ff69262009-05-27 05:00:47 +00001503 Args[0] = Arg;
Anders Carlsson07d68f12009-10-13 21:49:31 +00001504
1505 ExprOwningPtr<CXXOperatorCallExpr>
1506 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OverOp,
1507 FnExpr, Args, 2,
1508 ResultTy, OpLoc));
1509
1510 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
1511 FnDecl))
1512 return ExprError();
Anders Carlsson3a9439f2009-10-13 22:22:09 +00001513 return Owned(TheCall.release());
1514
Douglas Gregor74253732008-11-19 15:42:04 +00001515 } else {
1516 // We matched a built-in operator. Convert the arguments, then
1517 // break out so that we will build the appropriate built-in
1518 // operator node.
1519 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1520 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001521 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001522
1523 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001524 }
Douglas Gregor74253732008-11-19 15:42:04 +00001525 }
1526
Douglas Gregor33074752009-09-30 21:46:01 +00001527 case OR_No_Viable_Function: {
1528 // No viable function; try checking this as a built-in operator, which
1529 // will fail and provide a diagnostic. Then, print the overload
1530 // candidates.
1531 OwningExprResult Result = CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1532 assert(Result.isInvalid() &&
1533 "C++ postfix-unary operator overloading is missing candidates!");
1534 if (Result.isInvalid())
1535 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1536
1537 return move(Result);
1538 }
1539
Douglas Gregor74253732008-11-19 15:42:04 +00001540 case OR_Ambiguous:
1541 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1542 << UnaryOperator::getOpcodeStr(Opc)
1543 << Arg->getSourceRange();
1544 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001545 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001546
1547 case OR_Deleted:
1548 Diag(OpLoc, diag::err_ovl_deleted_oper)
1549 << Best->Function->isDeleted()
1550 << UnaryOperator::getOpcodeStr(Opc)
1551 << Arg->getSourceRange();
1552 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1553 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001554 }
1555
1556 // Either we found no viable overloaded operator or we matched a
1557 // built-in operator. In either case, fall through to trying to
1558 // build a built-in operation.
1559 }
1560
Eli Friedman6016cb22009-07-22 23:24:42 +00001561 Input.release();
1562 Input = Arg;
Eli Friedmande99a452009-07-22 22:25:00 +00001563 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001564}
1565
Sebastian Redl0eb23302009-01-19 00:08:26 +00001566Action::OwningExprResult
1567Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1568 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001569 // Since this might be a postfix expression, get rid of ParenListExprs.
1570 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1571
Sebastian Redl0eb23302009-01-19 00:08:26 +00001572 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1573 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Douglas Gregor337c6b92008-11-19 17:17:41 +00001575 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001576 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1577 Base.release();
1578 Idx.release();
1579 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1580 Context.DependentTy, RLoc));
1581 }
1582
Mike Stump1eb44332009-09-09 15:08:12 +00001583 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001584 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001585 LHSExp->getType()->isEnumeralType() ||
1586 RHSExp->getType()->isRecordType() ||
1587 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001588 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001589 }
1590
Sebastian Redlf322ed62009-10-29 20:17:01 +00001591 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1592}
1593
1594
1595Action::OwningExprResult
1596Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1597 ExprArg Idx, SourceLocation RLoc) {
1598 Expr *LHSExp = static_cast<Expr*>(Base.get());
1599 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1600
Chris Lattner12d9ff62007-07-16 00:14:47 +00001601 // Perform default conversions.
1602 DefaultFunctionArrayConversion(LHSExp);
1603 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001604
Chris Lattner12d9ff62007-07-16 00:14:47 +00001605 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001608 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001609 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001611 Expr *BaseExpr, *IndexExpr;
1612 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001613 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1614 BaseExpr = LHSExp;
1615 IndexExpr = RHSExp;
1616 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001617 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001618 BaseExpr = LHSExp;
1619 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001620 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001621 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001622 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001623 BaseExpr = RHSExp;
1624 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001625 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001626 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001627 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001628 BaseExpr = LHSExp;
1629 IndexExpr = RHSExp;
1630 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001631 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001632 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001633 // Handle the uncommon case of "123[Ptr]".
1634 BaseExpr = RHSExp;
1635 IndexExpr = LHSExp;
1636 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001637 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001638 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001639 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001640
Chris Lattner12d9ff62007-07-16 00:14:47 +00001641 // FIXME: need to deal with const...
1642 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001643 } else if (LHSTy->isArrayType()) {
1644 // If we see an array that wasn't promoted by
1645 // DefaultFunctionArrayConversion, it must be an array that
1646 // wasn't promoted because of the C90 rule that doesn't
1647 // allow promoting non-lvalue arrays. Warn, then
1648 // force the promotion here.
1649 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1650 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001651 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1652 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001653 LHSTy = LHSExp->getType();
1654
1655 BaseExpr = LHSExp;
1656 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001657 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001658 } else if (RHSTy->isArrayType()) {
1659 // Same as previous, except for 123[f().a] case
1660 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1661 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001662 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1663 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001664 RHSTy = RHSExp->getType();
1665
1666 BaseExpr = RHSExp;
1667 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001668 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001670 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1671 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001672 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001674 if (!(IndexExpr->getType()->isIntegerType() &&
1675 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001676 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1677 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001678
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001679 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001680 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1681 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001682 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1683
Douglas Gregore7450f52009-03-24 19:52:54 +00001684 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001685 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1686 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001687 // incomplete types are not object types.
1688 if (ResultType->isFunctionType()) {
1689 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1690 << ResultType << BaseExpr->getSourceRange();
1691 return ExprError();
1692 }
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Douglas Gregore7450f52009-03-24 19:52:54 +00001694 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001695 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001696 PDiag(diag::err_subscript_incomplete_type)
1697 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001698 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Chris Lattner1efaa952009-04-24 00:30:45 +00001700 // Diagnose bad cases where we step over interface counts.
1701 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1702 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1703 << ResultType << BaseExpr->getSourceRange();
1704 return ExprError();
1705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Sebastian Redl0eb23302009-01-19 00:08:26 +00001707 Base.release();
1708 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001709 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001710 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001711}
1712
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001713QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001714CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001715 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001716 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001717 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1718 // see FIXME there.
1719 //
1720 // FIXME: This logic can be greatly simplified by splitting it along
1721 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001722 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001723
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001724 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001725 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001726
Mike Stumpeed9cac2009-02-19 03:04:26 +00001727 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001728 // special names that indicate a subset of exactly half the elements are
1729 // to be selected.
1730 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001731
Nate Begeman353417a2009-01-18 01:47:54 +00001732 // This flag determines whether or not CompName has an 's' char prefix,
1733 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001734 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001735
1736 // Check that we've found one of the special components, or that the component
1737 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001738 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001739 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1740 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001741 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001742 do
1743 compStr++;
1744 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001745 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001746 do
1747 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001748 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001749 }
Nate Begeman353417a2009-01-18 01:47:54 +00001750
Mike Stumpeed9cac2009-02-19 03:04:26 +00001751 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001752 // We didn't get to the end of the string. This means the component names
1753 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001754 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1755 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001756 return QualType();
1757 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001758
Nate Begeman353417a2009-01-18 01:47:54 +00001759 // Ensure no component accessor exceeds the width of the vector type it
1760 // operates on.
1761 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00001762 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001763
1764 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001765 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001766
1767 while (*compStr) {
1768 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1769 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1770 << baseType << SourceRange(CompLoc);
1771 return QualType();
1772 }
1773 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001774 }
Nate Begeman8a997642008-05-09 06:41:27 +00001775
Nate Begeman353417a2009-01-18 01:47:54 +00001776 // If this is a halving swizzle, verify that the base type has an even
1777 // number of elements.
1778 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001779 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001780 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001781 return QualType();
1782 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001783
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001784 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001785 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001786 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001787 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001788 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001789 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00001790 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00001791 if (HexSwizzle)
1792 CompSize--;
1793
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001794 if (CompSize == 1)
1795 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001796
Nate Begeman213541a2008-04-18 23:10:10 +00001797 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001798 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001799 // diagostics look bad. We want extended vector types to appear built-in.
1800 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1801 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1802 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001803 }
1804 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001805}
1806
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001807static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001808 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001809 const Selector &Sel,
1810 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Anders Carlsson8f28f992009-08-26 18:25:21 +00001812 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001813 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001814 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001815 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001817 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1818 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001819 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001820 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001821 return D;
1822 }
1823 return 0;
1824}
1825
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001826static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001827 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001828 const Selector &Sel,
1829 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001830 // Check protocols on qualified interfaces.
1831 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001832 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001833 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001834 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001835 GDecl = PD;
1836 break;
1837 }
1838 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001839 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001840 GDecl = OMD;
1841 break;
1842 }
1843 }
1844 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001845 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001846 E = QIdTy->qual_end(); I != E; ++I) {
1847 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001848 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001849 if (GDecl)
1850 return GDecl;
1851 }
1852 }
1853 return GDecl;
1854}
Chris Lattner76a642f2009-02-15 22:43:40 +00001855
Mike Stump1eb44332009-09-09 15:08:12 +00001856Action::OwningExprResult
Anders Carlsson8f28f992009-08-26 18:25:21 +00001857Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001858 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001859 DeclarationName MemberName,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001860 bool HasExplicitTemplateArgs,
1861 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001862 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001863 unsigned NumExplicitTemplateArgs,
1864 SourceLocation RAngleLoc,
Douglas Gregorc68afe22009-09-03 21:38:09 +00001865 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1866 NamedDecl *FirstQualifierInScope) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001867 if (SS && SS->isInvalid())
1868 return ExprError();
1869
Nate Begeman2ef13e52009-08-10 23:49:36 +00001870 // Since this might be a postfix expression, get rid of ParenListExprs.
1871 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1872
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001873 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregora71d8192009-09-04 17:36:40 +00001874 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Steve Naroff3cc4af82007-12-16 21:42:28 +00001876 // Perform default conversions.
1877 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001878
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001879 QualType BaseType = BaseExpr->getType();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00001880
1881 // If the user is trying to apply -> or . to a function pointer
1882 // type, it's probably because the forgot parentheses to call that
1883 // function. Suggest the addition of those parentheses, build the
1884 // call, and continue on.
1885 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1886 if (const FunctionProtoType *Fun
1887 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
1888 QualType ResultTy = Fun->getResultType();
1889 if (Fun->getNumArgs() == 0 &&
1890 ((OpKind == tok::period && ResultTy->isRecordType()) ||
1891 (OpKind == tok::arrow && ResultTy->isPointerType() &&
1892 ResultTy->getAs<PointerType>()->getPointeeType()
1893 ->isRecordType()))) {
1894 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
1895 Diag(Loc, diag::err_member_reference_needs_call)
1896 << QualType(Fun, 0)
1897 << CodeModificationHint::CreateInsertion(Loc, "()");
1898
1899 OwningExprResult NewBase
1900 = ActOnCallExpr(S, ExprArg(*this, BaseExpr), Loc,
1901 MultiExprArg(*this, 0, 0), 0, Loc);
1902 if (NewBase.isInvalid())
1903 return move(NewBase);
1904
1905 BaseExpr = NewBase.takeAs<Expr>();
1906 DefaultFunctionArrayConversion(BaseExpr);
1907 BaseType = BaseExpr->getType();
1908 }
1909 }
1910 }
1911
David Chisnall0f436562009-08-17 16:35:33 +00001912 // If this is an Objective-C pseudo-builtin and a definition is provided then
1913 // use that.
1914 if (BaseType->isObjCIdType()) {
1915 // We have an 'id' type. Rather than fall through, we check if this
1916 // is a reference to 'isa'.
1917 if (BaseType != Context.ObjCIdRedefinitionType) {
1918 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001919 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00001920 }
David Chisnall0f436562009-08-17 16:35:33 +00001921 }
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001922 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001923
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001924 // Handle properties on ObjC 'Class' types.
1925 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1926 // Also must look for a getter name which uses property syntax.
1927 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1928 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1929 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1930 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1931 ObjCMethodDecl *Getter;
1932 // FIXME: need to also look locally in the implementation.
1933 if ((Getter = IFace->lookupClassMethod(Sel))) {
1934 // Check the use of this method.
1935 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1936 return ExprError();
1937 }
1938 // If we found a getter then this may be a valid dot-reference, we
1939 // will look for the matching setter, in case it is needed.
1940 Selector SetterSel =
1941 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1942 PP.getSelectorTable(), Member);
1943 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1944 if (!Setter) {
1945 // If this reference is in an @implementation, also check for 'private'
1946 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00001947 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001948 }
1949 // Look through local category implementations associated with the class.
1950 if (!Setter)
1951 Setter = IFace->getCategoryClassMethod(SetterSel);
1952
1953 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1954 return ExprError();
1955
1956 if (Getter || Setter) {
1957 QualType PType;
1958
1959 if (Getter)
1960 PType = Getter->getResultType();
1961 else
1962 // Get the expression type from Setter's incoming parameter.
1963 PType = (*(Setter->param_end() -1))->getType();
1964 // FIXME: we must check that the setter has property type.
1965 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
1966 PType,
1967 Setter, MemberLoc, BaseExpr));
1968 }
1969 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1970 << MemberName << BaseType);
1971 }
1972 }
1973
1974 if (BaseType->isObjCClassType() &&
1975 BaseType != Context.ObjCClassRedefinitionType) {
1976 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001977 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001978 }
1979
Chris Lattner68a057b2008-07-21 04:36:39 +00001980 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1981 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 if (OpKind == tok::arrow) {
Douglas Gregorc68afe22009-09-03 21:38:09 +00001983 if (BaseType->isDependentType()) {
1984 NestedNameSpecifier *Qualifier = 0;
1985 if (SS) {
1986 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1987 if (!FirstQualifierInScope)
1988 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
1989 }
Mike Stump1eb44332009-09-09 15:08:12 +00001990
1991 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001992 OpLoc, Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00001993 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001994 FirstQualifierInScope,
1995 MemberName,
1996 MemberLoc,
1997 HasExplicitTemplateArgs,
1998 LAngleLoc,
1999 ExplicitTemplateArgs,
2000 NumExplicitTemplateArgs,
2001 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002002 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002003 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002004 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002005 else if (BaseType->isObjCObjectPointerType())
2006 ;
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002007 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00002008 return ExprError(Diag(MemberLoc,
2009 diag::err_typecheck_member_reference_arrow)
2010 << BaseType << BaseExpr->getSourceRange());
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002011 } else if (BaseType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002012 // Require that the base type isn't a pointer type
Anders Carlsson4ef27702009-05-16 20:31:20 +00002013 // (so we'll report an error for)
2014 // T* t;
2015 // t.f;
Mike Stump1eb44332009-09-09 15:08:12 +00002016 //
Anders Carlsson4ef27702009-05-16 20:31:20 +00002017 // In Obj-C++, however, the above expression is valid, since it could be
2018 // accessing the 'f' property if T is an Obj-C interface. The extra check
2019 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenek6217b802009-07-29 21:53:49 +00002020 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002021
Mike Stump1eb44332009-09-09 15:08:12 +00002022 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorc68afe22009-09-03 21:38:09 +00002023 !PT->getPointeeType()->isRecordType())) {
2024 NestedNameSpecifier *Qualifier = 0;
2025 if (SS) {
2026 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2027 if (!FirstQualifierInScope)
2028 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2029 }
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002031 return Owned(CXXUnresolvedMemberExpr::Create(Context,
Mike Stump1eb44332009-09-09 15:08:12 +00002032 BaseExpr, false,
2033 OpLoc,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002034 Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002035 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002036 FirstQualifierInScope,
2037 MemberName,
2038 MemberLoc,
2039 HasExplicitTemplateArgs,
2040 LAngleLoc,
2041 ExplicitTemplateArgs,
2042 NumExplicitTemplateArgs,
2043 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002044 }
Anders Carlsson4ef27702009-05-16 20:31:20 +00002045 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002046
Chris Lattner68a057b2008-07-21 04:36:39 +00002047 // Handle field access to simple records. This also handles access to fields
2048 // of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002049 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002050 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00002051 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002052 PDiag(diag::err_typecheck_incomplete_tag)
2053 << BaseExpr->getSourceRange()))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002054 return ExprError();
2055
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002056 DeclContext *DC = RDecl;
2057 if (SS && SS->isSet()) {
2058 // If the member name was a qualified-id, look into the
2059 // nested-name-specifier.
2060 DC = computeDeclContext(*SS, false);
Douglas Gregor8d1c9ae2009-10-17 22:37:54 +00002061
2062 if (!isa<TypeDecl>(DC)) {
2063 Diag(MemberLoc, diag::err_qualified_member_nonclass)
2064 << DC << SS->getRange();
2065 return ExprError();
2066 }
Mike Stump1eb44332009-09-09 15:08:12 +00002067
2068 // FIXME: If DC is not computable, we should build a
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002069 // CXXUnresolvedMemberExpr.
2070 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2071 }
2072
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002073 // The record definition is complete, now make sure the member is valid.
John McCalla24dc2e2009-11-17 02:14:36 +00002074 LookupResult Result(*this, MemberName, MemberLoc, LookupMemberName);
2075 LookupQualifiedName(Result, DC);
Douglas Gregor7176fff2009-01-15 00:26:24 +00002076
John McCallf36e02d2009-10-09 21:13:30 +00002077 if (Result.empty())
Douglas Gregor3f093272009-10-13 21:16:44 +00002078 return ExprError(Diag(MemberLoc, diag::err_no_member)
2079 << MemberName << DC << BaseExpr->getSourceRange());
John McCalla24dc2e2009-11-17 02:14:36 +00002080 if (Result.isAmbiguous())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002081 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002082
John McCallf36e02d2009-10-09 21:13:30 +00002083 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2084
Douglas Gregora38c6872009-09-03 16:14:30 +00002085 if (SS && SS->isSet()) {
John McCallf36e02d2009-10-09 21:13:30 +00002086 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002087 QualType BaseTypeCanon
Douglas Gregora38c6872009-09-03 16:14:30 +00002088 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002089 QualType MemberTypeCanon
John McCallf36e02d2009-10-09 21:13:30 +00002090 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Douglas Gregora38c6872009-09-03 16:14:30 +00002092 if (BaseTypeCanon != MemberTypeCanon &&
2093 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2094 return ExprError(Diag(SS->getBeginLoc(),
2095 diag::err_not_direct_base_or_virtual)
2096 << MemberTypeCanon << BaseTypeCanon);
2097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Chris Lattner56cd21b2009-02-13 22:08:30 +00002099 // If the decl being referenced had an error, return an error for this
2100 // sub-expr without emitting another error, in order to avoid cascading
2101 // error cases.
2102 if (MemberDecl->isInvalidDecl())
2103 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002104
Anders Carlsson0f728562009-09-10 20:48:14 +00002105 bool ShouldCheckUse = true;
2106 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2107 // Don't diagnose the use of a virtual member function unless it's
2108 // explicitly qualified.
2109 if (MD->isVirtual() && (!SS || !SS->isSet()))
2110 ShouldCheckUse = false;
2111 }
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002112
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002113 // Check the use of this field
Anders Carlsson0f728562009-09-10 20:48:14 +00002114 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002115 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00002116
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002117 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002118 // We may have found a field within an anonymous union or struct
2119 // (C++ [class.union]).
2120 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002121 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002122 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002123
Douglas Gregor86f19402008-12-20 23:49:58 +00002124 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002125 QualType MemberType = FD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002126 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor86f19402008-12-20 23:49:58 +00002127 MemberType = Ref->getPointeeType();
2128 else {
John McCall0953e762009-09-24 19:53:00 +00002129 Qualifiers BaseQuals = BaseType.getQualifiers();
2130 BaseQuals.removeObjCGCAttr();
2131 if (FD->isMutable()) BaseQuals.removeConst();
2132
2133 Qualifiers MemberQuals
2134 = Context.getCanonicalType(MemberType).getQualifiers();
2135
2136 Qualifiers Combined = BaseQuals + MemberQuals;
2137 if (Combined != MemberQuals)
2138 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor86f19402008-12-20 23:49:58 +00002139 }
Eli Friedman51019072008-02-06 22:48:16 +00002140
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002141 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002142 if (PerformObjectMemberConversion(BaseExpr, FD))
2143 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002144 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002145 FD, MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002146 }
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002148 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2149 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002150 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2151 Var, MemberLoc,
2152 Var->getType().getNonReferenceType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002153 }
2154 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2155 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002156 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2157 MemberFn, MemberLoc,
2158 MemberFn->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002159 }
Mike Stump1eb44332009-09-09 15:08:12 +00002160 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +00002161 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2162 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002164 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002165 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2166 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002167 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002168 FunTmpl, MemberLoc, true,
2169 LAngleLoc, ExplicitTemplateArgs,
2170 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002171 Context.OverloadTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002173 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2174 FunTmpl, MemberLoc,
2175 Context.OverloadTy));
Douglas Gregor6b906862009-08-21 00:16:32 +00002176 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002177 if (OverloadedFunctionDecl *Ovl
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002178 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2179 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002180 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2181 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002182 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002183 Ovl, MemberLoc, true,
2184 LAngleLoc, ExplicitTemplateArgs,
2185 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002186 Context.OverloadTy));
2187
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002188 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2189 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002190 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002191 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2192 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002193 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2194 Enum, MemberLoc, Enum->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002195 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002196 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002197 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002198 << MemberName << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002199
Douglas Gregor86f19402008-12-20 23:49:58 +00002200 // We found a declaration kind that we didn't expect. This is a
2201 // generic error message that tells the user that she can't refer
2202 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002203 return ExprError(Diag(MemberLoc,
2204 diag::err_typecheck_member_reference_unknown)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002205 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002206 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002207
Douglas Gregora71d8192009-09-04 17:36:40 +00002208 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2209 // into a record type was handled above, any destructor we see here is a
2210 // pseudo-destructor.
2211 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2212 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002213 // The left hand side of the dot operator shall be of scalar type. The
2214 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002215 // type.
2216 if (!BaseType->isScalarType())
2217 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2218 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Douglas Gregora71d8192009-09-04 17:36:40 +00002220 // [...] The type designated by the pseudo-destructor-name shall be the
2221 // same as the object type.
2222 if (!MemberName.getCXXNameType()->isDependentType() &&
2223 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2224 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2225 << BaseType << MemberName.getCXXNameType()
2226 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002227
2228 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002229 // the form
2230 //
Mike Stump1eb44332009-09-09 15:08:12 +00002231 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2232 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002233 // shall designate the same scalar type.
2234 //
2235 // FIXME: DPG can't see any way to trigger this particular clause, so it
2236 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Douglas Gregora71d8192009-09-04 17:36:40 +00002238 // FIXME: We've lost the precise spelling of the type by going through
2239 // DeclarationName. Can we do better?
2240 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002241 OpKind == tok::arrow,
Douglas Gregora71d8192009-09-04 17:36:40 +00002242 OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002243 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregora71d8192009-09-04 17:36:40 +00002244 SS? SS->getRange() : SourceRange(),
2245 MemberName.getCXXNameType(),
2246 MemberLoc));
2247 }
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Chris Lattnera38e6b12008-07-21 04:59:05 +00002249 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2250 // (*Obj).ivar.
Steve Naroff14108da2009-07-10 23:34:53 +00002251 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2252 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002253 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002254 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002255 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002256 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002257 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2258
Steve Naroffc70e8d92009-07-16 00:25:06 +00002259 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2260 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002261 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Steve Naroffc70e8d92009-07-16 00:25:06 +00002263 if (IV) {
2264 // If the decl being referenced had an error, return an error for this
2265 // sub-expr without emitting another error, in order to avoid cascading
2266 // error cases.
2267 if (IV->isInvalidDecl())
2268 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002269
Steve Naroffc70e8d92009-07-16 00:25:06 +00002270 // Check whether we can reference this field.
2271 if (DiagnoseUseOfDecl(IV, MemberLoc))
2272 return ExprError();
2273 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2274 IV->getAccessControl() != ObjCIvarDecl::Package) {
2275 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2276 if (ObjCMethodDecl *MD = getCurMethodDecl())
2277 ClassOfMethodDecl = MD->getClassInterface();
2278 else if (ObjCImpDecl && getCurFunctionDecl()) {
2279 // Case of a c-function declared inside an objc implementation.
2280 // FIXME: For a c-style function nested inside an objc implementation
2281 // class, there is no implementation context available, so we pass
2282 // down the context as argument to this routine. Ideally, this context
2283 // need be passed down in the AST node and somehow calculated from the
2284 // AST for a function decl.
2285 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002286 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002287 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2288 ClassOfMethodDecl = IMPD->getClassInterface();
2289 else if (ObjCCategoryImplDecl* CatImplClass =
2290 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2291 ClassOfMethodDecl = CatImplClass->getClassInterface();
2292 }
Mike Stump1eb44332009-09-09 15:08:12 +00002293
2294 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2295 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002296 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002297 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002298 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002299 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2300 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002301 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002302 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002303 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002304
2305 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2306 MemberLoc, BaseExpr,
2307 OpKind == tok::arrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002308 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002309 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002310 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002311 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002312 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002313 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002314 // Handle properties on 'id' and qualified "id".
Mike Stump1eb44332009-09-09 15:08:12 +00002315 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroffde2e22d2009-07-15 18:40:39 +00002316 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002317 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002318 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Steve Naroff14108da2009-07-10 23:34:53 +00002320 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002321 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002322 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2323 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2324 // Check the use of this declaration
2325 if (DiagnoseUseOfDecl(PD, MemberLoc))
2326 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Steve Naroff14108da2009-07-10 23:34:53 +00002328 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2329 MemberLoc, BaseExpr));
2330 }
2331 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2332 // Check the use of this method.
2333 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2334 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002335
Steve Naroff14108da2009-07-10 23:34:53 +00002336 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002337 OMD->getResultType(),
2338 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002339 NULL, 0));
2340 }
2341 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002342
Steve Naroff14108da2009-07-10 23:34:53 +00002343 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002344 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002345 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002346 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2347 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002348 const ObjCObjectPointerType *OPT;
Mike Stump1eb44332009-09-09 15:08:12 +00002349 if (OpKind == tok::period &&
Steve Naroff14108da2009-07-10 23:34:53 +00002350 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2351 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2352 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002353 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002354
Daniel Dunbar2307d312008-09-03 01:05:41 +00002355 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002356 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002357 // Check whether we can reference this property.
2358 if (DiagnoseUseOfDecl(PD, MemberLoc))
2359 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002360 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002361 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002362 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002363 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2364 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002365 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002366 MemberLoc, BaseExpr));
2367 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002368 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002369 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2370 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002371 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002372 // Check whether we can reference this property.
2373 if (DiagnoseUseOfDecl(PD, MemberLoc))
2374 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002375
Steve Naroff6ece14c2009-01-21 00:14:39 +00002376 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002377 MemberLoc, BaseExpr));
2378 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002379 // If that failed, look for an "implicit" property by seeing if the nullary
2380 // selector is implemented.
2381
2382 // FIXME: The logic for looking up nullary and unary selectors should be
2383 // shared with the code in ActOnInstanceMessage.
2384
Anders Carlsson8f28f992009-08-26 18:25:21 +00002385 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002386 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002387
Daniel Dunbar2307d312008-09-03 01:05:41 +00002388 // If this reference is in an @implementation, check for 'private' methods.
2389 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002390 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002391
Steve Naroff7692ed62008-10-22 19:16:27 +00002392 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002393 if (!Getter)
2394 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002395 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002396 // Check if we can reference this property.
2397 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2398 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002399 }
2400 // If we found a getter then this may be a valid dot-reference, we
2401 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002402 Selector SetterSel =
2403 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002404 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002405 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002406 if (!Setter) {
2407 // If this reference is in an @implementation, also check for 'private'
2408 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002409 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002410 }
2411 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002412 if (!Setter)
2413 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002414
Steve Naroff1ca66942009-03-11 13:48:17 +00002415 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2416 return ExprError();
2417
2418 if (Getter || Setter) {
2419 QualType PType;
2420
2421 if (Getter)
2422 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002423 else
2424 // Get the expression type from Setter's incoming parameter.
2425 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002426 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002427 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002428 Setter, MemberLoc, BaseExpr));
2429 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002430 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002431 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002432 }
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Steve Narofff242b1b2009-07-24 17:54:45 +00002434 // Handle the following exceptional case (*Obj).isa.
Mike Stump1eb44332009-09-09 15:08:12 +00002435 if (OpKind == tok::period &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002436 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002437 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002438 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2439 Context.getObjCIdType()));
2440
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002441 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002442 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002443 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002444 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2445 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002446 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002447 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002448 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002449 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002450
Douglas Gregor214f31a2009-03-27 06:00:30 +00002451 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2452 << BaseType << BaseExpr->getSourceRange();
2453
Douglas Gregor214f31a2009-03-27 06:00:30 +00002454 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002455}
2456
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002457Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2458 SourceLocation OpLoc,
2459 tok::TokenKind OpKind,
2460 const CXXScopeSpec &SS,
2461 UnqualifiedId &Member,
2462 DeclPtrTy ObjCImpDecl,
2463 bool HasTrailingLParen) {
2464 if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2465 TemplateName Template
2466 = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2467
2468 // FIXME: We're going to end up looking up the template based on its name,
2469 // twice!
2470 DeclarationName Name;
2471 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2472 Name = ActualTemplate->getDeclName();
2473 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2474 Name = Ovl->getDeclName();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002475 else {
2476 DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2477 if (DTN->isIdentifier())
2478 Name = DTN->getIdentifier();
2479 else
2480 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2481 }
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002482
2483 // Translate the parser's template argument list in our AST format.
2484 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2485 Member.TemplateId->getTemplateArgs(),
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002486 Member.TemplateId->NumArgs);
2487
2488 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
2489 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002490 TemplateArgs);
2491 TemplateArgsPtr.release();
2492
2493 // Do we have the save the actual template name? We might need it...
2494 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2495 Member.TemplateId->TemplateNameLoc,
2496 Name, true, Member.TemplateId->LAngleLoc,
2497 TemplateArgs.data(), TemplateArgs.size(),
2498 Member.TemplateId->RAngleLoc, DeclPtrTy(),
2499 &SS);
2500 }
2501
2502 // FIXME: We lose a lot of source information by mapping directly to the
2503 // DeclarationName.
2504 OwningExprResult Result
2505 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2506 Member.getSourceRange().getBegin(),
2507 GetNameFromUnqualifiedId(Member),
2508 ObjCImpDecl, &SS);
2509
2510 if (Result.isInvalid() || HasTrailingLParen ||
2511 Member.getKind() != UnqualifiedId::IK_DestructorName)
2512 return move(Result);
2513
2514 // The only way a reference to a destructor can be used is to
2515 // immediately call them. Since the next token is not a '(', produce a
2516 // diagnostic and build the call now.
2517 Expr *E = (Expr *)Result.get();
2518 SourceLocation ExpectedLParenLoc
2519 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2520 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2521 << isa<CXXPseudoDestructorExpr>(E)
2522 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2523
2524 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2525 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002526}
2527
Anders Carlsson56c5e332009-08-25 03:49:14 +00002528Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2529 FunctionDecl *FD,
2530 ParmVarDecl *Param) {
2531 if (Param->hasUnparsedDefaultArg()) {
2532 Diag (CallLoc,
2533 diag::err_use_of_default_argument_to_function_declared_later) <<
2534 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002535 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002536 diag::note_default_argument_declared_here);
2537 } else {
2538 if (Param->hasUninstantiatedDefaultArg()) {
2539 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2540
2541 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002542 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002543
Mike Stump1eb44332009-09-09 15:08:12 +00002544 InstantiatingTemplate Inst(*this, CallLoc, Param,
2545 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002546 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002547
John McCallce3ff2b2009-08-25 22:02:44 +00002548 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002549 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002550 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002551
2552 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002553 /*FIXME:EqualLoc*/
2554 UninstExpr->getSourceRange().getBegin()))
2555 return ExprError();
2556 }
Mike Stump1eb44332009-09-09 15:08:12 +00002557
Anders Carlsson56c5e332009-08-25 03:49:14 +00002558 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Anders Carlsson56c5e332009-08-25 03:49:14 +00002560 // If the default expression creates temporaries, we need to
2561 // push them to the current stack of expression temporaries so they'll
2562 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002563 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002564 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002565 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002566 "Can't destroy temporaries in a default argument expr!");
2567 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2568 ExprTemporaries.push_back(E->getTemporary(I));
2569 }
2570 }
2571
2572 // We already type-checked the argument, so we know it works.
2573 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2574}
2575
Douglas Gregor88a35142008-12-22 05:46:06 +00002576/// ConvertArgumentsForCall - Converts the arguments specified in
2577/// Args/NumArgs to the parameter types of the function FDecl with
2578/// function prototype Proto. Call is the call expression itself, and
2579/// Fn is the function expression. For a C++ member function, this
2580/// routine does not attempt to convert the object argument. Returns
2581/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002582bool
2583Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002584 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002585 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002586 Expr **Args, unsigned NumArgs,
2587 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002588 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002589 // assignment, to the types of the corresponding parameter, ...
2590 unsigned NumArgsInProto = Proto->getNumArgs();
2591 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002592 bool Invalid = false;
2593
Douglas Gregor88a35142008-12-22 05:46:06 +00002594 // If too few arguments are available (and we don't have default
2595 // arguments for the remaining parameters), don't make the call.
2596 if (NumArgs < NumArgsInProto) {
2597 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2598 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2599 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2600 // Use default arguments for missing arguments
2601 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002602 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002603 }
2604
2605 // If too many are passed and not variadic, error on the extras and drop
2606 // them.
2607 if (NumArgs > NumArgsInProto) {
2608 if (!Proto->isVariadic()) {
2609 Diag(Args[NumArgsInProto]->getLocStart(),
2610 diag::err_typecheck_call_too_many_args)
2611 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2612 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2613 Args[NumArgs-1]->getLocEnd());
2614 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002615 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002616 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002617 }
2618 NumArgsToCheck = NumArgsInProto;
2619 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002620
Douglas Gregor88a35142008-12-22 05:46:06 +00002621 // Continue to check argument types (even if we have too few/many args).
2622 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2623 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002624
Douglas Gregor88a35142008-12-22 05:46:06 +00002625 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002626 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002627 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002628
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002629 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2630 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002631 PDiag(diag::err_call_incomplete_argument)
2632 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002633 return true;
2634
Douglas Gregor61366e92008-12-24 00:01:03 +00002635 // Pass the argument.
2636 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2637 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00002638
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00002639 if (!ProtoArgType->isReferenceType())
2640 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002641 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00002642 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump1eb44332009-09-09 15:08:12 +00002643
2644 OwningExprResult ArgExpr =
Anders Carlsson56c5e332009-08-25 03:49:14 +00002645 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2646 FDecl, Param);
2647 if (ArgExpr.isInvalid())
2648 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002649
Anders Carlsson56c5e332009-08-25 03:49:14 +00002650 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002651 }
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Douglas Gregor88a35142008-12-22 05:46:06 +00002653 Call->setArg(i, Arg);
2654 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002655
Douglas Gregor88a35142008-12-22 05:46:06 +00002656 // If this is a variadic call, handle args passed through "...".
2657 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002658 VariadicCallType CallType = VariadicFunction;
2659 if (Fn->getType()->isBlockPointerType())
2660 CallType = VariadicBlock; // Block
2661 else if (isa<MemberExpr>(Fn))
2662 CallType = VariadicMethod;
2663
Douglas Gregor88a35142008-12-22 05:46:06 +00002664 // Promote the arguments (C99 6.5.2.2p7).
Eli Friedman3e42ffd2009-11-14 04:43:10 +00002665 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002666 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002667 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002668 Call->setArg(i, Arg);
2669 }
2670 }
2671
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002672 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002673}
2674
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002675/// \brief "Deconstruct" the function argument of a call expression to find
2676/// the underlying declaration (if any), the name of the called function,
2677/// whether argument-dependent lookup is available, whether it has explicit
2678/// template arguments, etc.
2679void Sema::DeconstructCallFunction(Expr *FnExpr,
2680 NamedDecl *&Function,
2681 DeclarationName &Name,
2682 NestedNameSpecifier *&Qualifier,
2683 SourceRange &QualifierRange,
2684 bool &ArgumentDependentLookup,
2685 bool &HasExplicitTemplateArguments,
John McCall833ca992009-10-29 08:12:44 +00002686 const TemplateArgumentLoc *&ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002687 unsigned &NumExplicitTemplateArgs) {
2688 // Set defaults for all of the output parameters.
2689 Function = 0;
2690 Name = DeclarationName();
2691 Qualifier = 0;
2692 QualifierRange = SourceRange();
2693 ArgumentDependentLookup = getLangOptions().CPlusPlus;
2694 HasExplicitTemplateArguments = false;
2695
2696 // If we're directly calling a function, get the appropriate declaration.
2697 // Also, in C++, keep track of whether we should perform argument-dependent
2698 // lookup and whether there were any explicitly-specified template arguments.
2699 while (true) {
2700 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2701 FnExpr = IcExpr->getSubExpr();
2702 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2703 // Parentheses around a function disable ADL
2704 // (C++0x [basic.lookup.argdep]p1).
2705 ArgumentDependentLookup = false;
2706 FnExpr = PExpr->getSubExpr();
2707 } else if (isa<UnaryOperator>(FnExpr) &&
2708 cast<UnaryOperator>(FnExpr)->getOpcode()
2709 == UnaryOperator::AddrOf) {
2710 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002711 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2712 Function = dyn_cast<NamedDecl>(DRExpr->getDecl());
Douglas Gregora2813ce2009-10-23 18:54:35 +00002713 if ((Qualifier = DRExpr->getQualifier())) {
2714 ArgumentDependentLookup = false;
2715 QualifierRange = DRExpr->getQualifierRange();
2716 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002717 break;
2718 } else if (UnresolvedFunctionNameExpr *DepName
2719 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2720 Name = DepName->getName();
2721 break;
2722 } else if (TemplateIdRefExpr *TemplateIdRef
2723 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2724 Function = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2725 if (!Function)
2726 Function = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2727 HasExplicitTemplateArguments = true;
2728 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2729 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2730
2731 // C++ [temp.arg.explicit]p6:
2732 // [Note: For simple function names, argument dependent lookup (3.4.2)
2733 // applies even when the function name is not visible within the
2734 // scope of the call. This is because the call still has the syntactic
2735 // form of a function call (3.4.1). But when a function template with
2736 // explicit template arguments is used, the call does not have the
2737 // correct syntactic form unless there is a function template with
2738 // that name visible at the point of the call. If no such name is
2739 // visible, the call is not syntactically well-formed and
2740 // argument-dependent lookup does not apply. If some such name is
2741 // visible, argument dependent lookup applies and additional function
2742 // templates may be found in other namespaces.
2743 //
2744 // The summary of this paragraph is that, if we get to this point and the
2745 // template-id was not a qualified name, then argument-dependent lookup
2746 // is still possible.
2747 if ((Qualifier = TemplateIdRef->getQualifier())) {
2748 ArgumentDependentLookup = false;
2749 QualifierRange = TemplateIdRef->getQualifierRange();
2750 }
2751 break;
2752 } else {
2753 // Any kind of name that does not refer to a declaration (or
2754 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2755 ArgumentDependentLookup = false;
2756 break;
2757 }
2758 }
2759}
2760
Steve Narofff69936d2007-09-16 03:34:24 +00002761/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002762/// This provides the location of the left/right parens and a list of comma
2763/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002764Action::OwningExprResult
2765Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2766 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002767 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002768 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002769
2770 // Since this might be a postfix expression, get rid of ParenListExprs.
2771 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002773 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002774 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002775 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002776 FunctionDecl *FDecl = NULL;
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002777 NamedDecl *NDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002778 DeclarationName UnqualifiedName;
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Douglas Gregor88a35142008-12-22 05:46:06 +00002780 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002781 // If this is a pseudo-destructor expression, build the call immediately.
2782 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2783 if (NumArgs > 0) {
2784 // Pseudo-destructor calls should not have any arguments.
2785 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2786 << CodeModificationHint::CreateRemoval(
2787 SourceRange(Args[0]->getLocStart(),
2788 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Douglas Gregora71d8192009-09-04 17:36:40 +00002790 for (unsigned I = 0; I != NumArgs; ++I)
2791 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Douglas Gregora71d8192009-09-04 17:36:40 +00002793 NumArgs = 0;
2794 }
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Douglas Gregora71d8192009-09-04 17:36:40 +00002796 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2797 RParenLoc));
2798 }
Mike Stump1eb44332009-09-09 15:08:12 +00002799
Douglas Gregor17330012009-02-04 15:01:18 +00002800 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002801 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002802 // FIXME: Will need to cache the results of name lookup (including ADL) in
2803 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002804 bool Dependent = false;
2805 if (Fn->isTypeDependent())
2806 Dependent = true;
2807 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2808 Dependent = true;
2809
2810 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002811 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002812 Context.DependentTy, RParenLoc));
2813
2814 // Determine whether this is a call to an object (C++ [over.call.object]).
2815 if (Fn->getType()->isRecordType())
2816 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2817 CommaLocs, RParenLoc));
2818
Douglas Gregorfa047642009-02-04 00:32:51 +00002819 // Determine whether this is a call to a member function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002820 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2821 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2822 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2823 isa<CXXMethodDecl>(MemDecl) ||
2824 (isa<FunctionTemplateDecl>(MemDecl) &&
2825 isa<CXXMethodDecl>(
2826 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002827 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2828 CommaLocs, RParenLoc));
Douglas Gregore53060f2009-06-25 22:08:12 +00002829 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002830
2831 // Determine whether this is a call to a pointer-to-member function.
2832 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2833 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2834 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002835 if (const FunctionProtoType *FPT =
2836 dyn_cast<FunctionProtoType>(BO->getType())) {
2837 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002838
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002839 ExprOwningPtr<CXXMemberCallExpr>
2840 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2841 NumArgs, ResultTy,
2842 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002843
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002844 if (CheckCallReturnType(FPT->getResultType(),
2845 BO->getRHS()->getSourceRange().getBegin(),
2846 TheCall.get(), 0))
2847 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00002848
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002849 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2850 RParenLoc))
2851 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002852
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002853 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2854 }
2855 return ExprError(Diag(Fn->getLocStart(),
2856 diag::err_typecheck_call_not_function)
2857 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002858 }
2859 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002860 }
2861
Douglas Gregorfa047642009-02-04 00:32:51 +00002862 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002863 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002864 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregorfa047642009-02-04 00:32:51 +00002865 bool ADL = true;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002866 bool HasExplicitTemplateArgs = 0;
John McCall833ca992009-10-29 08:12:44 +00002867 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002868 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002869 NestedNameSpecifier *Qualifier = 0;
2870 SourceRange QualifierRange;
2871 DeconstructCallFunction(Fn, NDecl, UnqualifiedName, Qualifier, QualifierRange,
2872 ADL,HasExplicitTemplateArgs, ExplicitTemplateArgs,
2873 NumExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002874
Douglas Gregor17330012009-02-04 15:01:18 +00002875 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregore53060f2009-06-25 22:08:12 +00002876 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002877 if (NDecl) {
2878 FDecl = dyn_cast<FunctionDecl>(NDecl);
2879 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregore53060f2009-06-25 22:08:12 +00002880 FDecl = FunctionTemplate->getTemplatedDecl();
2881 else
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002882 FDecl = dyn_cast<FunctionDecl>(NDecl);
2883 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor17330012009-02-04 15:01:18 +00002884 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002885
Mike Stump1eb44332009-09-09 15:08:12 +00002886 if (Ovl || FunctionTemplate ||
Douglas Gregore53060f2009-06-25 22:08:12 +00002887 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002888 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00002889 if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002890 ADL = false;
2891
Douglas Gregorf9201e02009-02-11 23:02:49 +00002892 // We don't perform ADL in C.
2893 if (!getLangOptions().CPlusPlus)
2894 ADL = false;
2895
Douglas Gregore53060f2009-06-25 22:08:12 +00002896 if (Ovl || FunctionTemplate || ADL) {
Mike Stump1eb44332009-09-09 15:08:12 +00002897 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002898 HasExplicitTemplateArgs,
2899 ExplicitTemplateArgs,
2900 NumExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002901 LParenLoc, Args, NumArgs, CommaLocs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002902 RParenLoc, ADL);
Douglas Gregorfa047642009-02-04 00:32:51 +00002903 if (!FDecl)
2904 return ExprError();
2905
Douglas Gregor097bfb12009-10-23 22:18:25 +00002906 Fn = FixOverloadedFunctionReference(Fn, FDecl);
Douglas Gregorfa047642009-02-04 00:32:51 +00002907 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002908 }
Chris Lattner04421082008-04-08 04:40:51 +00002909
2910 // Promote the function operand.
2911 UsualUnaryConversions(Fn);
2912
Chris Lattner925e60d2007-12-28 05:29:59 +00002913 // Make the call expr early, before semantic checks. This guarantees cleanup
2914 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002915 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2916 Args, NumArgs,
2917 Context.BoolTy,
2918 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002919
Steve Naroffdd972f22008-09-05 22:11:13 +00002920 const FunctionType *FuncT;
2921 if (!Fn->getType()->isBlockPointerType()) {
2922 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2923 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00002924 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002925 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002926 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2927 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00002928 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002929 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00002930 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00002931 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002932 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002933 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002934 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2935 << Fn->getType() << Fn->getSourceRange());
2936
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002937 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002938 if (CheckCallReturnType(FuncT->getResultType(),
2939 Fn->getSourceRange().getBegin(), TheCall.get(),
2940 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002941 return ExprError();
2942
Chris Lattner925e60d2007-12-28 05:29:59 +00002943 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002944 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002945
Douglas Gregor72564e72009-02-26 23:50:07 +00002946 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002947 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002948 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002949 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002950 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002951 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002952
Douglas Gregor74734d52009-04-02 15:37:10 +00002953 if (FDecl) {
2954 // Check if we have too few/too many template arguments, based
2955 // on our knowledge of the function definition.
2956 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002957 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002958 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00002959 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002960 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2961 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2962 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2963 }
2964 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002965 }
2966
Steve Naroffb291ab62007-08-28 23:30:39 +00002967 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002968 for (unsigned i = 0; i != NumArgs; i++) {
2969 Expr *Arg = Args[i];
2970 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002971 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2972 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002973 PDiag(diag::err_call_incomplete_argument)
2974 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002975 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002976 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002977 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002978 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002979
Douglas Gregor88a35142008-12-22 05:46:06 +00002980 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2981 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002982 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2983 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002984
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002985 // Check for sentinels
2986 if (NDecl)
2987 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002988
Chris Lattner59907c42007-08-10 20:18:51 +00002989 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00002990 if (FDecl) {
2991 if (CheckFunctionCall(FDecl, TheCall.get()))
2992 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002993
Douglas Gregor7814e6d2009-09-12 00:22:50 +00002994 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00002995 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2996 } else if (NDecl) {
2997 if (CheckBlockCall(NDecl, TheCall.get()))
2998 return ExprError();
2999 }
Chris Lattner59907c42007-08-10 20:18:51 +00003000
Anders Carlssonec74c592009-08-16 03:06:32 +00003001 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003002}
3003
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003004Action::OwningExprResult
3005Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3006 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003007 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003008 //FIXME: Preserve type source info.
3009 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003010 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003011 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003012 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003013
Eli Friedman6223c222008-05-20 05:22:08 +00003014 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003015 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003016 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3017 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003018 } else if (!literalType->isDependentType() &&
3019 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003020 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003021 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003022 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003023 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003024
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003025 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003026 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003027 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003028
Chris Lattner371f2582008-12-04 23:50:19 +00003029 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003030 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003031 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003032 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003033 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003034 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003035 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003036 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003037}
3038
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003039Action::OwningExprResult
3040Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003041 SourceLocation RBraceLoc) {
3042 unsigned NumInit = initlist.size();
3043 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003044
Steve Naroff08d92e42007-09-15 18:49:24 +00003045 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003046 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003047
Mike Stumpeed9cac2009-02-19 03:04:26 +00003048 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003049 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003050 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003051 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003052}
3053
Anders Carlsson82debc72009-10-18 18:12:03 +00003054static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3055 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003056 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003057 return CastExpr::CK_NoOp;
3058
3059 if (SrcTy->hasPointerRepresentation()) {
3060 if (DestTy->hasPointerRepresentation())
3061 return CastExpr::CK_BitCast;
3062 if (DestTy->isIntegerType())
3063 return CastExpr::CK_PointerToIntegral;
3064 }
3065
3066 if (SrcTy->isIntegerType()) {
3067 if (DestTy->isIntegerType())
3068 return CastExpr::CK_IntegralCast;
3069 if (DestTy->hasPointerRepresentation())
3070 return CastExpr::CK_IntegralToPointer;
3071 if (DestTy->isRealFloatingType())
3072 return CastExpr::CK_IntegralToFloating;
3073 }
3074
3075 if (SrcTy->isRealFloatingType()) {
3076 if (DestTy->isRealFloatingType())
3077 return CastExpr::CK_FloatingCast;
3078 if (DestTy->isIntegerType())
3079 return CastExpr::CK_FloatingToIntegral;
3080 }
3081
3082 // FIXME: Assert here.
3083 // assert(false && "Unhandled cast combination!");
3084 return CastExpr::CK_Unknown;
3085}
3086
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003087/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003088bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003089 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003090 CXXMethodDecl *& ConversionDecl,
3091 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003092 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003093 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3094 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003095
Eli Friedman199ea952009-08-15 19:02:19 +00003096 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003097
3098 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3099 // type needs to be scalar.
3100 if (castType->isVoidType()) {
3101 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003102 Kind = CastExpr::CK_ToVoid;
3103 return false;
3104 }
3105
3106 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003107 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003108 (castType->isStructureType() || castType->isUnionType())) {
3109 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003110 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003111 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3112 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003113 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003114 return false;
3115 }
3116
3117 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003118 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003119 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003120 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003121 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003122 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003123 if (Context.hasSameUnqualifiedType(Field->getType(),
3124 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003125 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3126 << castExpr->getSourceRange();
3127 break;
3128 }
3129 }
3130 if (Field == FieldEnd)
3131 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3132 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003133 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003134 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003135 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003136
3137 // Reject any other conversions to non-scalar types.
3138 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3139 << castType << castExpr->getSourceRange();
3140 }
3141
3142 if (!castExpr->getType()->isScalarType() &&
3143 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003144 return Diag(castExpr->getLocStart(),
3145 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003146 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003147 }
3148
Anders Carlsson16a89042009-10-16 05:23:41 +00003149 if (castType->isExtVectorType())
3150 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3151
Anders Carlssonc3516322009-10-16 02:48:28 +00003152 if (castType->isVectorType())
3153 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3154 if (castExpr->getType()->isVectorType())
3155 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3156
3157 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003158 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003159
Anders Carlsson16a89042009-10-16 05:23:41 +00003160 if (isa<ObjCSelectorExpr>(castExpr))
3161 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3162
Anders Carlssonc3516322009-10-16 02:48:28 +00003163 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003164 QualType castExprType = castExpr->getType();
3165 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3166 return Diag(castExpr->getLocStart(),
3167 diag::err_cast_pointer_from_non_pointer_int)
3168 << castExprType << castExpr->getSourceRange();
3169 } else if (!castExpr->getType()->isArithmeticType()) {
3170 if (!castType->isIntegralType() && castType->isArithmeticType())
3171 return Diag(castExpr->getLocStart(),
3172 diag::err_cast_pointer_to_non_pointer_int)
3173 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003174 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003175
3176 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003177 return false;
3178}
3179
Anders Carlssonc3516322009-10-16 02:48:28 +00003180bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3181 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003182 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003183
Anders Carlssona64db8f2007-11-27 05:51:55 +00003184 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003185 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003186 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003187 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003188 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003189 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003190 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003191 } else
3192 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003193 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003194 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003195
Anders Carlssonc3516322009-10-16 02:48:28 +00003196 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003197 return false;
3198}
3199
Anders Carlsson16a89042009-10-16 05:23:41 +00003200bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3201 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003202 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003203
3204 QualType SrcTy = CastExpr->getType();
3205
Nate Begeman9b10da62009-06-27 22:05:55 +00003206 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3207 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003208 if (SrcTy->isVectorType()) {
3209 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3210 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3211 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003212 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003213 return false;
3214 }
3215
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003216 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003217 // conversion will take place first from scalar to elt type, and then
3218 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003219 if (SrcTy->isPointerType())
3220 return Diag(R.getBegin(),
3221 diag::err_invalid_conversion_between_vector_and_scalar)
3222 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003223
3224 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3225 ImpCastExprToType(CastExpr, DestElemTy,
3226 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003227
3228 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003229 return false;
3230}
3231
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003232Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003233Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003234 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003235 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003237 assert((Ty != 0) && (Op.get() != 0) &&
3238 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003239
Nate Begeman2ef13e52009-08-10 23:49:36 +00003240 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003241 //FIXME: Preserve type source info.
3242 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Nate Begeman2ef13e52009-08-10 23:49:36 +00003244 // If the Expr being casted is a ParenListExpr, handle it specially.
3245 if (isa<ParenListExpr>(castExpr))
3246 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003247 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003248 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003249 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003250 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003251
3252 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003253 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003254 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003255
Anders Carlsson0aebc812009-09-09 21:33:21 +00003256 if (CastArg.isInvalid())
3257 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003258
Anders Carlsson0aebc812009-09-09 21:33:21 +00003259 castExpr = CastArg.takeAs<Expr>();
3260 } else {
3261 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003262 }
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003264 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003265 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003266 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003267}
3268
Nate Begeman2ef13e52009-08-10 23:49:36 +00003269/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3270/// of comma binary operators.
3271Action::OwningExprResult
3272Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3273 Expr *expr = EA.takeAs<Expr>();
3274 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3275 if (!E)
3276 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Nate Begeman2ef13e52009-08-10 23:49:36 +00003278 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003279
Nate Begeman2ef13e52009-08-10 23:49:36 +00003280 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3281 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3282 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Nate Begeman2ef13e52009-08-10 23:49:36 +00003284 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3285}
3286
3287Action::OwningExprResult
3288Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3289 SourceLocation RParenLoc, ExprArg Op,
3290 QualType Ty) {
3291 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003292
3293 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003294 // then handle it as such.
3295 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3296 if (PE->getNumExprs() == 0) {
3297 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3298 return ExprError();
3299 }
3300
3301 llvm::SmallVector<Expr *, 8> initExprs;
3302 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3303 initExprs.push_back(PE->getExpr(i));
3304
3305 // FIXME: This means that pretty-printing the final AST will produce curly
3306 // braces instead of the original commas.
3307 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003308 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003309 initExprs.size(), RParenLoc);
3310 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003311 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003312 Owned(E));
3313 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003314 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003315 // sequence of BinOp comma operators.
3316 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3317 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3318 }
3319}
3320
3321Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3322 SourceLocation R,
3323 MultiExprArg Val) {
3324 unsigned nexprs = Val.size();
3325 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3326 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3327 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3328 return Owned(expr);
3329}
3330
Sebastian Redl28507842009-02-26 14:39:58 +00003331/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3332/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003333/// C99 6.5.15
3334QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3335 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003336 // C++ is sufficiently different to merit its own checker.
3337 if (getLangOptions().CPlusPlus)
3338 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3339
John McCallb13c87f2009-11-05 09:23:39 +00003340 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3341
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003342 UsualUnaryConversions(Cond);
3343 UsualUnaryConversions(LHS);
3344 UsualUnaryConversions(RHS);
3345 QualType CondTy = Cond->getType();
3346 QualType LHSTy = LHS->getType();
3347 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003348
Reid Spencer5f016e22007-07-11 17:01:13 +00003349 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003350 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3351 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3352 << CondTy;
3353 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003354 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003355
Chris Lattner70d67a92008-01-06 22:42:25 +00003356 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003357 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3358 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003359
Chris Lattner70d67a92008-01-06 22:42:25 +00003360 // If both operands have arithmetic type, do the usual arithmetic conversions
3361 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003362 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3363 UsualArithmeticConversions(LHS, RHS);
3364 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003365 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003366
Chris Lattner70d67a92008-01-06 22:42:25 +00003367 // If both operands are the same structure or union type, the result is that
3368 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003369 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3370 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003371 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003372 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003373 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003374 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003375 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003376 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003377
Chris Lattner70d67a92008-01-06 22:42:25 +00003378 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003379 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003380 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3381 if (!LHSTy->isVoidType())
3382 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3383 << RHS->getSourceRange();
3384 if (!RHSTy->isVoidType())
3385 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3386 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003387 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3388 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003389 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003390 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003391 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3392 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003393 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003394 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003395 // promote the null to a pointer.
3396 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003397 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003398 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003399 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003400 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003401 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003402 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003403 }
David Chisnall0f436562009-08-17 16:35:33 +00003404 // Handle things like Class and struct objc_class*. Here we case the result
3405 // to the pseudo-builtin, because that will be implicitly cast back to the
3406 // redefinition type if an attempt is made to access its fields.
3407 if (LHSTy->isObjCClassType() &&
3408 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003409 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003410 return LHSTy;
3411 }
3412 if (RHSTy->isObjCClassType() &&
3413 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003414 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003415 return RHSTy;
3416 }
3417 // And the same for struct objc_object* / id
3418 if (LHSTy->isObjCIdType() &&
3419 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003420 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003421 return LHSTy;
3422 }
3423 if (RHSTy->isObjCIdType() &&
3424 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003425 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003426 return RHSTy;
3427 }
Steve Naroff7154a772009-07-01 14:36:47 +00003428 // Handle block pointer types.
3429 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3430 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3431 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3432 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003433 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3434 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003435 return destType;
3436 }
3437 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3438 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3439 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003440 }
Steve Naroff7154a772009-07-01 14:36:47 +00003441 // We have 2 block pointer types.
3442 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3443 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003444 return LHSTy;
3445 }
Steve Naroff7154a772009-07-01 14:36:47 +00003446 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003447 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3448 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003449
Steve Naroff7154a772009-07-01 14:36:47 +00003450 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3451 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003452 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3453 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3454 // In this situation, we assume void* type. No especially good
3455 // reason, but this is what gcc does, and we do have to pick
3456 // to get a consistent AST.
3457 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003458 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3459 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003460 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003461 }
Steve Naroff7154a772009-07-01 14:36:47 +00003462 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003463 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3464 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003465 return LHSTy;
3466 }
Steve Naroff7154a772009-07-01 14:36:47 +00003467 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003468 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003469
Steve Naroff7154a772009-07-01 14:36:47 +00003470 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3471 // Two identical object pointer types are always compatible.
3472 return LHSTy;
3473 }
John McCall183700f2009-09-21 23:43:11 +00003474 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3475 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003476 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Steve Naroff7154a772009-07-01 14:36:47 +00003478 // If both operands are interfaces and either operand can be
3479 // assigned to the other, use that type as the composite
3480 // type. This allows
3481 // xxx ? (A*) a : (B*) b
3482 // where B is a subclass of A.
3483 //
3484 // Additionally, as for assignment, if either type is 'id'
3485 // allow silent coercion. Finally, if the types are
3486 // incompatible then make sure to use 'id' as the composite
3487 // type so the result is acceptable for sending messages to.
3488
3489 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3490 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003491 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003492 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003493 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003494 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003495 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003496 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003497 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003498 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003499 // GCC allows qualified id and any Objective-C type to devolve to
3500 // id. Currently localizing to here until clear this should be
3501 // part of ObjCQualifiedIdTypesAreCompatible.
3502 compositeType = Context.getObjCIdType();
3503 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003504 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003505 } else if (!(compositeType =
3506 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3507 ;
3508 else {
Steve Naroff7154a772009-07-01 14:36:47 +00003509 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3510 << LHSTy << RHSTy
3511 << LHS->getSourceRange() << RHS->getSourceRange();
3512 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003513 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3514 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003515 return incompatTy;
3516 }
3517 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003518 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3519 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003520 return compositeType;
3521 }
Steve Naroffc715e782009-07-29 15:09:39 +00003522 // Check Objective-C object pointer types and 'void *'
3523 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003524 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003525 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003526 QualType destPointee
3527 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003528 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003529 // Add qualifiers if necessary.
3530 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3531 // Promote to void*.
3532 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003533 return destType;
3534 }
3535 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00003536 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003537 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003538 QualType destPointee
3539 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003540 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003541 // Add qualifiers if necessary.
3542 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3543 // Promote to void*.
3544 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003545 return destType;
3546 }
Steve Naroff7154a772009-07-01 14:36:47 +00003547 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3548 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3549 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003550 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3551 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003552
3553 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3554 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3555 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00003556 QualType destPointee
3557 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003558 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003559 // Add qualifiers if necessary.
3560 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3561 // Promote to void*.
3562 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003563 return destType;
3564 }
3565 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00003566 QualType destPointee
3567 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003568 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003569 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003570 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003571 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003572 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003573 return destType;
3574 }
3575
3576 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3577 // Two identical pointer types are always compatible.
3578 return LHSTy;
3579 }
3580 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3581 rhptee.getUnqualifiedType())) {
3582 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3583 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3584 // In this situation, we assume void* type. No especially good
3585 // reason, but this is what gcc does, and we do have to pick
3586 // to get a consistent AST.
3587 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003588 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3589 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003590 return incompatTy;
3591 }
3592 // The pointer types are compatible.
3593 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3594 // differently qualified versions of compatible types, the result type is
3595 // a pointer to an appropriately qualified version of the *composite*
3596 // type.
3597 // FIXME: Need to calculate the composite type.
3598 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00003599 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3600 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003601 return LHSTy;
3602 }
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Steve Naroff7154a772009-07-01 14:36:47 +00003604 // GCC compatibility: soften pointer/integer mismatch.
3605 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3606 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3607 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003608 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003609 return RHSTy;
3610 }
3611 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3612 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3613 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003614 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003615 return LHSTy;
3616 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003617
Chris Lattner70d67a92008-01-06 22:42:25 +00003618 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003619 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3620 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003621 return QualType();
3622}
3623
Steve Narofff69936d2007-09-16 03:34:24 +00003624/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003625/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003626Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3627 SourceLocation ColonLoc,
3628 ExprArg Cond, ExprArg LHS,
3629 ExprArg RHS) {
3630 Expr *CondExpr = (Expr *) Cond.get();
3631 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003632
3633 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3634 // was the condition.
3635 bool isLHSNull = LHSExpr == 0;
3636 if (isLHSNull)
3637 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003638
3639 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003640 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003641 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003642 return ExprError();
3643
3644 Cond.release();
3645 LHS.release();
3646 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003647 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003648 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003649 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003650}
3651
Reid Spencer5f016e22007-07-11 17:01:13 +00003652// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003653// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003654// routine is it effectively iqnores the qualifiers on the top level pointee.
3655// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3656// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003657Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003658Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3659 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003660
David Chisnall0f436562009-08-17 16:35:33 +00003661 if ((lhsType->isObjCClassType() &&
3662 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3663 (rhsType->isObjCClassType() &&
3664 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3665 return Compatible;
3666 }
3667
Reid Spencer5f016e22007-07-11 17:01:13 +00003668 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003669 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3670 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003671
Reid Spencer5f016e22007-07-11 17:01:13 +00003672 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003673 lhptee = Context.getCanonicalType(lhptee);
3674 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003675
Chris Lattner5cf216b2008-01-04 18:04:52 +00003676 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003677
3678 // C99 6.5.16.1p1: This following citation is common to constraints
3679 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3680 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003681 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003682 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003683 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003684
Mike Stumpeed9cac2009-02-19 03:04:26 +00003685 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3686 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003687 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003688 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003689 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003690 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003691
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003692 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003693 assert(rhptee->isFunctionType());
3694 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003695 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003696
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003697 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003698 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003699 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003700
3701 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003702 assert(lhptee->isFunctionType());
3703 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003704 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003705 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003706 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003707 lhptee = lhptee.getUnqualifiedType();
3708 rhptee = rhptee.getUnqualifiedType();
3709 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3710 // Check if the pointee types are compatible ignoring the sign.
3711 // We explicitly check for char so that we catch "char" vs
3712 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00003713 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003714 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003715 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003716 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003717
3718 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003719 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003720 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003721 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003722
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003723 if (lhptee == rhptee) {
3724 // Types are compatible ignoring the sign. Qualifier incompatibility
3725 // takes priority over sign incompatibility because the sign
3726 // warning can be disabled.
3727 if (ConvTy != Compatible)
3728 return ConvTy;
3729 return IncompatiblePointerSign;
3730 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003731
3732 // If we are a multi-level pointer, it's possible that our issue is simply
3733 // one of qualification - e.g. char ** -> const char ** is not allowed. If
3734 // the eventual target type is the same and the pointers have the same
3735 // level of indirection, this must be the issue.
3736 if (lhptee->isPointerType() && rhptee->isPointerType()) {
3737 do {
3738 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
3739 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
3740
3741 lhptee = Context.getCanonicalType(lhptee);
3742 rhptee = Context.getCanonicalType(rhptee);
3743 } while (lhptee->isPointerType() && rhptee->isPointerType());
3744
Douglas Gregora4923eb2009-11-16 21:35:15 +00003745 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00003746 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003747 }
3748
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003749 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00003750 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003751 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003752 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003753}
3754
Steve Naroff1c7d0672008-09-04 15:10:53 +00003755/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3756/// block pointer types are compatible or whether a block and normal pointer
3757/// are compatible. It is more restrict than comparing two function pointer
3758// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003759Sema::AssignConvertType
3760Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003761 QualType rhsType) {
3762 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003763
Steve Naroff1c7d0672008-09-04 15:10:53 +00003764 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003765 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3766 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003767
Steve Naroff1c7d0672008-09-04 15:10:53 +00003768 // make sure we operate on the canonical type
3769 lhptee = Context.getCanonicalType(lhptee);
3770 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003771
Steve Naroff1c7d0672008-09-04 15:10:53 +00003772 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003773
Steve Naroff1c7d0672008-09-04 15:10:53 +00003774 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003775 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00003776 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003777
Eli Friedman26784c12009-06-08 05:08:54 +00003778 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003779 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003780 return ConvTy;
3781}
3782
Mike Stumpeed9cac2009-02-19 03:04:26 +00003783/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3784/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003785/// pointers. Here are some objectionable examples that GCC considers warnings:
3786///
3787/// int a, *pint;
3788/// short *pshort;
3789/// struct foo *pfoo;
3790///
3791/// pint = pshort; // warning: assignment from incompatible pointer type
3792/// a = pint; // warning: assignment makes integer from pointer without a cast
3793/// pint = a; // warning: assignment makes pointer from integer without a cast
3794/// pint = pfoo; // warning: assignment from incompatible pointer type
3795///
3796/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003797/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003798///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003799Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003800Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003801 // Get canonical types. We're not formatting these types, just comparing
3802 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003803 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3804 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003805
3806 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003807 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003808
David Chisnall0f436562009-08-17 16:35:33 +00003809 if ((lhsType->isObjCClassType() &&
3810 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3811 (rhsType->isObjCClassType() &&
3812 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3813 return Compatible;
3814 }
3815
Douglas Gregor9d293df2008-10-28 00:22:11 +00003816 // If the left-hand side is a reference type, then we are in a
3817 // (rare!) case where we've allowed the use of references in C,
3818 // e.g., as a parameter type in a built-in function. In this case,
3819 // just make sure that the type referenced is compatible with the
3820 // right-hand side type. The caller is responsible for adjusting
3821 // lhsType so that the resulting expression does not have reference
3822 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003823 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00003824 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003825 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003826 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003827 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003828 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3829 // to the same ExtVector type.
3830 if (lhsType->isExtVectorType()) {
3831 if (rhsType->isExtVectorType())
3832 return lhsType == rhsType ? Compatible : Incompatible;
3833 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3834 return Compatible;
3835 }
Mike Stump1eb44332009-09-09 15:08:12 +00003836
Nate Begemanbe2341d2008-07-14 18:02:46 +00003837 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003838 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003839 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003840 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003841 if (getLangOptions().LaxVectorConversions &&
3842 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003843 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003844 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003845 }
3846 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003847 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003848
Chris Lattnere8b3e962008-01-04 23:32:24 +00003849 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003850 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003851
Chris Lattner78eca282008-04-07 06:49:41 +00003852 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003853 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003854 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003855
Chris Lattner78eca282008-04-07 06:49:41 +00003856 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003857 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003858
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003859 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003860 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003861 if (lhsType->isVoidPointerType()) // an exception to the rule.
3862 return Compatible;
3863 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003864 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003865 if (rhsType->getAs<BlockPointerType>()) {
3866 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003867 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003868
3869 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003870 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003871 return Compatible;
3872 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003873 return Incompatible;
3874 }
3875
3876 if (isa<BlockPointerType>(lhsType)) {
3877 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003878 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003879
Steve Naroffb4406862008-09-29 18:10:17 +00003880 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003881 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003882 return Compatible;
3883
Steve Naroff1c7d0672008-09-04 15:10:53 +00003884 if (rhsType->isBlockPointerType())
3885 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003886
Ted Kremenek6217b802009-07-29 21:53:49 +00003887 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003888 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003889 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003890 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003891 return Incompatible;
3892 }
3893
Steve Naroff14108da2009-07-10 23:34:53 +00003894 if (isa<ObjCObjectPointerType>(lhsType)) {
3895 if (rhsType->isIntegerType())
3896 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003898 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003899 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003900 if (rhsType->isVoidPointerType()) // an exception to the rule.
3901 return Compatible;
3902 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003903 }
3904 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003905 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3906 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003907 if (Context.typesAreCompatible(lhsType, rhsType))
3908 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00003909 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3910 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003911 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003912 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003913 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003914 if (RHSPT->getPointeeType()->isVoidType())
3915 return Compatible;
3916 }
3917 // Treat block pointers as objects.
3918 if (rhsType->isBlockPointerType())
3919 return Compatible;
3920 return Incompatible;
3921 }
Chris Lattner78eca282008-04-07 06:49:41 +00003922 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003923 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003924 if (lhsType == Context.BoolTy)
3925 return Compatible;
3926
3927 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003928 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003929
Mike Stumpeed9cac2009-02-19 03:04:26 +00003930 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003931 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003932
3933 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003934 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003935 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003936 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003937 }
Steve Naroff14108da2009-07-10 23:34:53 +00003938 if (isa<ObjCObjectPointerType>(rhsType)) {
3939 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3940 if (lhsType == Context.BoolTy)
3941 return Compatible;
3942
3943 if (lhsType->isIntegerType())
3944 return PointerToInt;
3945
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003946 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003947 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003948 if (lhsType->isVoidPointerType()) // an exception to the rule.
3949 return Compatible;
3950 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003951 }
3952 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003953 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00003954 return Compatible;
3955 return Incompatible;
3956 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003957
Chris Lattnerfc144e22008-01-04 23:18:45 +00003958 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003959 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003960 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003961 }
3962 return Incompatible;
3963}
3964
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003965/// \brief Constructs a transparent union from an expression that is
3966/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00003967static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003968 QualType UnionType, FieldDecl *Field) {
3969 // Build an initializer list that designates the appropriate member
3970 // of the transparent union.
3971 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3972 &E, 1,
3973 SourceLocation());
3974 Initializer->setType(UnionType);
3975 Initializer->setInitializedFieldInUnion(Field);
3976
3977 // Build a compound literal constructing a value of the transparent
3978 // union type from this initializer list.
3979 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3980 false);
3981}
3982
3983Sema::AssignConvertType
3984Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3985 QualType FromType = rExpr->getType();
3986
Mike Stump1eb44332009-09-09 15:08:12 +00003987 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003988 // transparent_union GCC extension.
3989 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003990 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003991 return Incompatible;
3992
3993 // The field to initialize within the transparent union.
3994 RecordDecl *UD = UT->getDecl();
3995 FieldDecl *InitField = 0;
3996 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003997 for (RecordDecl::field_iterator it = UD->field_begin(),
3998 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003999 it != itend; ++it) {
4000 if (it->getType()->isPointerType()) {
4001 // If the transparent union contains a pointer type, we allow:
4002 // 1) void pointer
4003 // 2) null pointer constant
4004 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004005 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004006 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004007 InitField = *it;
4008 break;
4009 }
Mike Stump1eb44332009-09-09 15:08:12 +00004010
Douglas Gregorce940492009-09-25 04:25:58 +00004011 if (rExpr->isNullPointerConstant(Context,
4012 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004013 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004014 InitField = *it;
4015 break;
4016 }
4017 }
4018
4019 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4020 == Compatible) {
4021 InitField = *it;
4022 break;
4023 }
4024 }
4025
4026 if (!InitField)
4027 return Incompatible;
4028
4029 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4030 return Compatible;
4031}
4032
Chris Lattner5cf216b2008-01-04 18:04:52 +00004033Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004034Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004035 if (getLangOptions().CPlusPlus) {
4036 if (!lhsType->isRecordType()) {
4037 // C++ 5.17p3: If the left operand is not of class type, the
4038 // expression is implicitly converted (C++ 4) to the
4039 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004040 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4041 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004042 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004043 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004044 }
4045
4046 // FIXME: Currently, we fall through and treat C++ classes like C
4047 // structures.
4048 }
4049
Steve Naroff529a4ad2007-11-27 17:58:44 +00004050 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4051 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004052 if ((lhsType->isPointerType() ||
4053 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004054 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004055 && rExpr->isNullPointerConstant(Context,
4056 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004057 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004058 return Compatible;
4059 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004060
Chris Lattner943140e2007-10-16 02:55:40 +00004061 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004062 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004063 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004064 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004065 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004066 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004067 if (!lhsType->isReferenceType())
4068 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004069
Chris Lattner5cf216b2008-01-04 18:04:52 +00004070 Sema::AssignConvertType result =
4071 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004072
Steve Narofff1120de2007-08-24 22:33:52 +00004073 // C99 6.5.16.1p2: The value of the right operand is converted to the
4074 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004075 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4076 // so that we can use references in built-in functions even in C.
4077 // The getNonReferenceType() call makes sure that the resulting expression
4078 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004079 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004080 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4081 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004082 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004083}
4084
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004085QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004086 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004087 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004088 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004089 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004090}
4091
Mike Stumpeed9cac2009-02-19 03:04:26 +00004092inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004093 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004094 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004095 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004096 QualType lhsType =
4097 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4098 QualType rhsType =
4099 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004100
Nate Begemanbe2341d2008-07-14 18:02:46 +00004101 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004102 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004103 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004104
Nate Begemanbe2341d2008-07-14 18:02:46 +00004105 // Handle the case of a vector & extvector type of the same size and element
4106 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004107 if (getLangOptions().LaxVectorConversions) {
4108 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004109 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4110 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004111 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004112 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004113 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004114 }
4115 }
4116 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004117
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004118 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4119 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4120 bool swapped = false;
4121 if (rhsType->isExtVectorType()) {
4122 swapped = true;
4123 std::swap(rex, lex);
4124 std::swap(rhsType, lhsType);
4125 }
Mike Stump1eb44332009-09-09 15:08:12 +00004126
Nate Begemandde25982009-06-28 19:12:57 +00004127 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004128 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004129 QualType EltTy = LV->getElementType();
4130 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4131 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004132 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004133 if (swapped) std::swap(rex, lex);
4134 return lhsType;
4135 }
4136 }
4137 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4138 rhsType->isRealFloatingType()) {
4139 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004140 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004141 if (swapped) std::swap(rex, lex);
4142 return lhsType;
4143 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004144 }
4145 }
Mike Stump1eb44332009-09-09 15:08:12 +00004146
Nate Begemandde25982009-06-28 19:12:57 +00004147 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004148 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004149 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004150 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004151 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004152}
4153
Reid Spencer5f016e22007-07-11 17:01:13 +00004154inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004155 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004156 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004157 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004158
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004159 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004160
Steve Naroffa4332e22007-07-17 00:58:39 +00004161 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004162 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004163 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004164}
4165
4166inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004167 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004168 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4169 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4170 return CheckVectorOperands(Loc, lex, rex);
4171 return InvalidOperands(Loc, lex, rex);
4172 }
Steve Naroff90045e82007-07-13 23:32:42 +00004173
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004174 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004175
Steve Naroffa4332e22007-07-17 00:58:39 +00004176 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004177 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004178 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004179}
4180
4181inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004182 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004183 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4184 QualType compType = CheckVectorOperands(Loc, lex, rex);
4185 if (CompLHSTy) *CompLHSTy = compType;
4186 return compType;
4187 }
Steve Naroff49b45262007-07-13 16:58:59 +00004188
Eli Friedmanab3a8522009-03-28 01:22:36 +00004189 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004190
Reid Spencer5f016e22007-07-11 17:01:13 +00004191 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004192 if (lex->getType()->isArithmeticType() &&
4193 rex->getType()->isArithmeticType()) {
4194 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004195 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004196 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004197
Eli Friedmand72d16e2008-05-18 18:08:51 +00004198 // Put any potential pointer into PExp
4199 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004200 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004201 std::swap(PExp, IExp);
4202
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004203 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004204
Eli Friedmand72d16e2008-05-18 18:08:51 +00004205 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004206 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004207
Chris Lattnerb5f15622009-04-24 23:50:08 +00004208 // Check for arithmetic on pointers to incomplete types.
4209 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004210 if (getLangOptions().CPlusPlus) {
4211 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004212 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004213 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004214 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004215
4216 // GNU extension: arithmetic on pointer to void
4217 Diag(Loc, diag::ext_gnu_void_ptr)
4218 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004219 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004220 if (getLangOptions().CPlusPlus) {
4221 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4222 << lex->getType() << lex->getSourceRange();
4223 return QualType();
4224 }
4225
4226 // GNU extension: arithmetic on pointer to function
4227 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4228 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004229 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004230 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004231 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004232 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004233 PExp->getType()->isObjCObjectPointerType()) &&
4234 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004235 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4236 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004237 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004238 return QualType();
4239 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004240 // Diagnose bad cases where we step over interface counts.
4241 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4242 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4243 << PointeeTy << PExp->getSourceRange();
4244 return QualType();
4245 }
Mike Stump1eb44332009-09-09 15:08:12 +00004246
Eli Friedmanab3a8522009-03-28 01:22:36 +00004247 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004248 QualType LHSTy = Context.isPromotableBitField(lex);
4249 if (LHSTy.isNull()) {
4250 LHSTy = lex->getType();
4251 if (LHSTy->isPromotableIntegerType())
4252 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004253 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004254 *CompLHSTy = LHSTy;
4255 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004256 return PExp->getType();
4257 }
4258 }
4259
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004260 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004261}
4262
Chris Lattnereca7be62008-04-07 05:30:13 +00004263// C99 6.5.6
4264QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004265 SourceLocation Loc, QualType* CompLHSTy) {
4266 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4267 QualType compType = CheckVectorOperands(Loc, lex, rex);
4268 if (CompLHSTy) *CompLHSTy = compType;
4269 return compType;
4270 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004271
Eli Friedmanab3a8522009-03-28 01:22:36 +00004272 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004273
Chris Lattner6e4ab612007-12-09 21:53:25 +00004274 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004275
Chris Lattner6e4ab612007-12-09 21:53:25 +00004276 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004277 if (lex->getType()->isArithmeticType()
4278 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004279 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004280 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004281 }
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Chris Lattner6e4ab612007-12-09 21:53:25 +00004283 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004284 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004285 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004286
Douglas Gregore7450f52009-03-24 19:52:54 +00004287 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004288
Douglas Gregore7450f52009-03-24 19:52:54 +00004289 bool ComplainAboutVoid = false;
4290 Expr *ComplainAboutFunc = 0;
4291 if (lpointee->isVoidType()) {
4292 if (getLangOptions().CPlusPlus) {
4293 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4294 << lex->getSourceRange() << rex->getSourceRange();
4295 return QualType();
4296 }
4297
4298 // GNU C extension: arithmetic on pointer to void
4299 ComplainAboutVoid = true;
4300 } else if (lpointee->isFunctionType()) {
4301 if (getLangOptions().CPlusPlus) {
4302 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004303 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004304 return QualType();
4305 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004306
4307 // GNU C extension: arithmetic on pointer to function
4308 ComplainAboutFunc = lex;
4309 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004310 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004311 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004312 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004313 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004314 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004315
Chris Lattnerb5f15622009-04-24 23:50:08 +00004316 // Diagnose bad cases where we step over interface counts.
4317 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4318 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4319 << lpointee << lex->getSourceRange();
4320 return QualType();
4321 }
Mike Stump1eb44332009-09-09 15:08:12 +00004322
Chris Lattner6e4ab612007-12-09 21:53:25 +00004323 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004324 if (rex->getType()->isIntegerType()) {
4325 if (ComplainAboutVoid)
4326 Diag(Loc, diag::ext_gnu_void_ptr)
4327 << lex->getSourceRange() << rex->getSourceRange();
4328 if (ComplainAboutFunc)
4329 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004330 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004331 << ComplainAboutFunc->getSourceRange();
4332
Eli Friedmanab3a8522009-03-28 01:22:36 +00004333 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004334 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004335 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004336
Chris Lattner6e4ab612007-12-09 21:53:25 +00004337 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004338 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004339 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004340
Douglas Gregore7450f52009-03-24 19:52:54 +00004341 // RHS must be a completely-type object type.
4342 // Handle the GNU void* extension.
4343 if (rpointee->isVoidType()) {
4344 if (getLangOptions().CPlusPlus) {
4345 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4346 << lex->getSourceRange() << rex->getSourceRange();
4347 return QualType();
4348 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004349
Douglas Gregore7450f52009-03-24 19:52:54 +00004350 ComplainAboutVoid = true;
4351 } else if (rpointee->isFunctionType()) {
4352 if (getLangOptions().CPlusPlus) {
4353 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004354 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004355 return QualType();
4356 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004357
4358 // GNU extension: arithmetic on pointer to function
4359 if (!ComplainAboutFunc)
4360 ComplainAboutFunc = rex;
4361 } else if (!rpointee->isDependentType() &&
4362 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004363 PDiag(diag::err_typecheck_sub_ptr_object)
4364 << rex->getSourceRange()
4365 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004366 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004367
Eli Friedman88d936b2009-05-16 13:54:38 +00004368 if (getLangOptions().CPlusPlus) {
4369 // Pointee types must be the same: C++ [expr.add]
4370 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4371 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4372 << lex->getType() << rex->getType()
4373 << lex->getSourceRange() << rex->getSourceRange();
4374 return QualType();
4375 }
4376 } else {
4377 // Pointee types must be compatible C99 6.5.6p3
4378 if (!Context.typesAreCompatible(
4379 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4380 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4381 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4382 << lex->getType() << rex->getType()
4383 << lex->getSourceRange() << rex->getSourceRange();
4384 return QualType();
4385 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004386 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004387
Douglas Gregore7450f52009-03-24 19:52:54 +00004388 if (ComplainAboutVoid)
4389 Diag(Loc, diag::ext_gnu_void_ptr)
4390 << lex->getSourceRange() << rex->getSourceRange();
4391 if (ComplainAboutFunc)
4392 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004393 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004394 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004395
4396 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004397 return Context.getPointerDiffType();
4398 }
4399 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004400
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004401 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004402}
4403
Chris Lattnereca7be62008-04-07 05:30:13 +00004404// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004405QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004406 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004407 // C99 6.5.7p2: Each of the operands shall have integer type.
4408 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004409 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004410
Nate Begeman2207d792009-10-25 02:26:48 +00004411 // Vector shifts promote their scalar inputs to vector type.
4412 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4413 return CheckVectorOperands(Loc, lex, rex);
4414
Chris Lattnerca5eede2007-12-12 05:47:28 +00004415 // Shifts don't perform usual arithmetic conversions, they just do integer
4416 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004417 QualType LHSTy = Context.isPromotableBitField(lex);
4418 if (LHSTy.isNull()) {
4419 LHSTy = lex->getType();
4420 if (LHSTy->isPromotableIntegerType())
4421 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004422 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004423 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004424 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004425
Chris Lattnerca5eede2007-12-12 05:47:28 +00004426 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004427
Ryan Flynnd0439682009-08-07 16:20:20 +00004428 // Sanity-check shift operands
4429 llvm::APSInt Right;
4430 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004431 if (!rex->isValueDependent() &&
4432 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004433 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004434 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4435 else {
4436 llvm::APInt LeftBits(Right.getBitWidth(),
4437 Context.getTypeSize(lex->getType()));
4438 if (Right.uge(LeftBits))
4439 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4440 }
4441 }
4442
Chris Lattnerca5eede2007-12-12 05:47:28 +00004443 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004444 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004445}
4446
John McCall5dbad3d2009-11-06 08:49:08 +00004447/// \brief Implements -Wsign-compare.
4448///
4449/// \param lex the left-hand expression
4450/// \param rex the right-hand expression
4451/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004452/// \param Equality whether this is an "equality-like" join, which
4453/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004454void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004455 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004456 // Don't warn if we're in an unevaluated context.
4457 if (ExprEvalContext == Unevaluated)
4458 return;
4459
John McCall45aa4552009-11-05 00:40:04 +00004460 QualType lt = lex->getType(), rt = rex->getType();
4461
4462 // Only warn if both operands are integral.
4463 if (!lt->isIntegerType() || !rt->isIntegerType())
4464 return;
4465
Sebastian Redl732429c2009-11-05 21:09:23 +00004466 // If either expression is value-dependent, don't warn. We'll get another
4467 // chance at instantiation time.
4468 if (lex->isValueDependent() || rex->isValueDependent())
4469 return;
4470
John McCall45aa4552009-11-05 00:40:04 +00004471 // The rule is that the signed operand becomes unsigned, so isolate the
4472 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00004473 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00004474 if (lt->isSignedIntegerType()) {
4475 if (rt->isSignedIntegerType()) return;
4476 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00004477 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00004478 } else {
4479 if (!rt->isSignedIntegerType()) return;
4480 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00004481 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00004482 }
4483
John McCall5dbad3d2009-11-06 08:49:08 +00004484 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00004485 // then (1) the result type will be signed and (2) the unsigned
4486 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00004487 // of the comparison will be exact.
4488 if (Context.getIntWidth(signedOperand->getType()) >
4489 Context.getIntWidth(unsignedOperand->getType()))
4490 return;
4491
John McCall45aa4552009-11-05 00:40:04 +00004492 // If the value is a non-negative integer constant, then the
4493 // signed->unsigned conversion won't change it.
4494 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00004495 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00004496 assert(value.isSigned() && "result of signed expression not signed");
4497
4498 if (value.isNonNegative())
4499 return;
4500 }
4501
John McCall5dbad3d2009-11-06 08:49:08 +00004502 if (Equality) {
4503 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00004504 // constant which cannot collide with a overflowed signed operand,
4505 // then reinterpreting the signed operand as unsigned will not
4506 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00004507 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4508 assert(!value.isSigned() && "result of unsigned expression is signed");
4509
4510 // 2's complement: test the top bit.
4511 if (value.isNonNegative())
4512 return;
4513 }
4514 }
4515
John McCallb13c87f2009-11-05 09:23:39 +00004516 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00004517 << lex->getType() << rex->getType()
4518 << lex->getSourceRange() << rex->getSourceRange();
4519}
4520
Douglas Gregor0c6db942009-05-04 06:07:12 +00004521// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004522QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004523 unsigned OpaqueOpc, bool isRelational) {
4524 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4525
Nate Begemanbe2341d2008-07-14 18:02:46 +00004526 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004527 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004528
John McCall5dbad3d2009-11-06 08:49:08 +00004529 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
4530 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00004531
Chris Lattnera5937dd2007-08-26 01:18:55 +00004532 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00004533 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4534 UsualArithmeticConversions(lex, rex);
4535 else {
4536 UsualUnaryConversions(lex);
4537 UsualUnaryConversions(rex);
4538 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004539 QualType lType = lex->getType();
4540 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004541
Mike Stumpaf199f32009-05-07 18:43:07 +00004542 if (!lType->isFloatingType()
4543 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00004544 // For non-floating point types, check for self-comparisons of the form
4545 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4546 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00004547 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00004548 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00004549 Expr *LHSStripped = lex->IgnoreParens();
4550 Expr *RHSStripped = rex->IgnoreParens();
4551 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4552 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00004553 if (DRL->getDecl() == DRR->getDecl() &&
4554 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004555 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00004556
Chris Lattner55660a72009-03-08 19:39:53 +00004557 if (isa<CastExpr>(LHSStripped))
4558 LHSStripped = LHSStripped->IgnoreParenCasts();
4559 if (isa<CastExpr>(RHSStripped))
4560 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00004561
Chris Lattner55660a72009-03-08 19:39:53 +00004562 // Warn about comparisons against a string constant (unless the other
4563 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00004564 Expr *literalString = 0;
4565 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00004566 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004567 !RHSStripped->isNullPointerConstant(Context,
4568 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004569 literalString = lex;
4570 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004571 } else if ((isa<StringLiteral>(RHSStripped) ||
4572 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004573 !LHSStripped->isNullPointerConstant(Context,
4574 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004575 literalString = rex;
4576 literalStringStripped = RHSStripped;
4577 }
4578
4579 if (literalString) {
4580 std::string resultComparison;
4581 switch (Opc) {
4582 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4583 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4584 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4585 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4586 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4587 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4588 default: assert(false && "Invalid comparison operator");
4589 }
4590 Diag(Loc, diag::warn_stringcompare)
4591 << isa<ObjCEncodeExpr>(literalStringStripped)
4592 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00004593 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4594 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4595 "strcmp(")
4596 << CodeModificationHint::CreateInsertion(
4597 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00004598 resultComparison);
4599 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00004600 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004601
Douglas Gregor447b69e2008-11-19 03:25:36 +00004602 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00004603 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00004604
Chris Lattnera5937dd2007-08-26 01:18:55 +00004605 if (isRelational) {
4606 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004607 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004608 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004609 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004610 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00004611 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004612 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00004613 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004614
Chris Lattnera5937dd2007-08-26 01:18:55 +00004615 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004616 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004617 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004618
Douglas Gregorce940492009-09-25 04:25:58 +00004619 bool LHSIsNull = lex->isNullPointerConstant(Context,
4620 Expr::NPC_ValueDependentIsNull);
4621 bool RHSIsNull = rex->isNullPointerConstant(Context,
4622 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004623
Chris Lattnera5937dd2007-08-26 01:18:55 +00004624 // All of the following pointer related warnings are GCC extensions, except
4625 // when handling null pointer constants. One day, we can consider making them
4626 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00004627 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00004628 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004629 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00004630 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004631 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004632
Douglas Gregor0c6db942009-05-04 06:07:12 +00004633 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00004634 if (LCanPointeeTy == RCanPointeeTy)
4635 return ResultTy;
4636
Douglas Gregor0c6db942009-05-04 06:07:12 +00004637 // C++ [expr.rel]p2:
4638 // [...] Pointer conversions (4.10) and qualification
4639 // conversions (4.4) are performed on pointer operands (or on
4640 // a pointer operand and a null pointer constant) to bring
4641 // them to their composite pointer type. [...]
4642 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00004643 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00004644 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00004645 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004646 if (T.isNull()) {
4647 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4648 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4649 return QualType();
4650 }
4651
Eli Friedman73c39ab2009-10-20 08:27:19 +00004652 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4653 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004654 return ResultTy;
4655 }
Eli Friedman3075e762009-08-23 00:27:47 +00004656 // C99 6.5.9p2 and C99 6.5.8p2
4657 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4658 RCanPointeeTy.getUnqualifiedType())) {
4659 // Valid unless a relational comparison of function pointers
4660 if (isRelational && LCanPointeeTy->isFunctionType()) {
4661 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4662 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4663 }
4664 } else if (!isRelational &&
4665 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4666 // Valid unless comparison between non-null pointer and function pointer
4667 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4668 && !LHSIsNull && !RHSIsNull) {
4669 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4670 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4671 }
4672 } else {
4673 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004674 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004675 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004676 }
Eli Friedman3075e762009-08-23 00:27:47 +00004677 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004678 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004679 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004680 }
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004682 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00004683 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00004684 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00004685 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004686 (lType->isPointerType() ||
4687 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004688 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004689 return ResultTy;
4690 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004691 if (LHSIsNull &&
4692 (rType->isPointerType() ||
4693 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004694 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004695 return ResultTy;
4696 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004697
4698 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00004699 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004700 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4701 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004702 // In addition, pointers to members can be compared, or a pointer to
4703 // member and a null pointer constant. Pointer to member conversions
4704 // (4.11) and qualification conversions (4.4) are performed to bring
4705 // them to a common type. If one operand is a null pointer constant,
4706 // the common type is the type of the other operand. Otherwise, the
4707 // common type is a pointer to member type similar (4.4) to the type
4708 // of one of the operands, with a cv-qualification signature (4.4)
4709 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00004710 // types.
4711 QualType T = FindCompositePointerType(lex, rex);
4712 if (T.isNull()) {
4713 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4714 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4715 return QualType();
4716 }
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Eli Friedman73c39ab2009-10-20 08:27:19 +00004718 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4719 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004720 return ResultTy;
4721 }
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Douglas Gregor20b3e992009-08-24 17:42:35 +00004723 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004724 if (lType->isNullPtrType() && rType->isNullPtrType())
4725 return ResultTy;
4726 }
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Steve Naroff1c7d0672008-09-04 15:10:53 +00004728 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004729 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004730 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4731 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004732
Steve Naroff1c7d0672008-09-04 15:10:53 +00004733 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00004734 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004735 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00004736 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00004737 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004738 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004739 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004740 }
Steve Naroff59f53942008-09-28 01:11:11 +00004741 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004742 if (!isRelational
4743 && ((lType->isBlockPointerType() && rType->isPointerType())
4744 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00004745 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004746 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004747 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004748 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004749 ->getPointeeType()->isVoidType())))
4750 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4751 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004752 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004753 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004754 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004755 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004756
Steve Naroff14108da2009-07-10 23:34:53 +00004757 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004758 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004759 const PointerType *LPT = lType->getAs<PointerType>();
4760 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004761 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004762 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004763 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004764 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004765
Steve Naroffa8069f12008-11-17 19:49:16 +00004766 if (!LPtrToVoid && !RPtrToVoid &&
4767 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004768 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004769 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004770 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004771 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004772 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004773 }
Steve Naroff14108da2009-07-10 23:34:53 +00004774 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004775 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00004776 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4777 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004778 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004779 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00004780 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004781 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004782 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004783 unsigned DiagID = 0;
4784 if (RHSIsNull) {
4785 if (isRelational)
4786 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4787 } else if (isRelational)
4788 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4789 else
4790 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004791
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004792 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004793 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004794 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004795 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004796 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004797 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004798 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004799 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004800 unsigned DiagID = 0;
4801 if (LHSIsNull) {
4802 if (isRelational)
4803 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4804 } else if (isRelational)
4805 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4806 else
4807 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004808
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004809 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004810 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004811 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004812 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004813 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004814 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004815 }
Steve Naroff39218df2008-09-04 16:56:14 +00004816 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004817 if (!isRelational && RHSIsNull
4818 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004819 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004820 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004821 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004822 if (!isRelational && LHSIsNull
4823 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004824 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004825 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004826 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004827 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004828}
4829
Nate Begemanbe2341d2008-07-14 18:02:46 +00004830/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004831/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004832/// like a scalar comparison, a vector comparison produces a vector of integer
4833/// types.
4834QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004835 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004836 bool isRelational) {
4837 // Check to make sure we're operating on vectors of the same type and width,
4838 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004839 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004840 if (vType.isNull())
4841 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004842
Nate Begemanbe2341d2008-07-14 18:02:46 +00004843 QualType lType = lex->getType();
4844 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004845
Nate Begemanbe2341d2008-07-14 18:02:46 +00004846 // For non-floating point types, check for self-comparisons of the form
4847 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4848 // often indicate logic errors in the program.
4849 if (!lType->isFloatingType()) {
4850 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4851 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4852 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004853 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004854 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004855
Nate Begemanbe2341d2008-07-14 18:02:46 +00004856 // Check for comparisons of floating point operands using != and ==.
4857 if (!isRelational && lType->isFloatingType()) {
4858 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004859 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004860 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004861
Nate Begemanbe2341d2008-07-14 18:02:46 +00004862 // Return the type for the comparison, which is the same as vector type for
4863 // integer vectors, or an integer type of identical size and number of
4864 // elements for floating point vectors.
4865 if (lType->isIntegerType())
4866 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004867
John McCall183700f2009-09-21 23:43:11 +00004868 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004869 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004870 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004871 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004872 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004873 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4874
Mike Stumpeed9cac2009-02-19 03:04:26 +00004875 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004876 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004877 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4878}
4879
Reid Spencer5f016e22007-07-11 17:01:13 +00004880inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004881 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00004882 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004883 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004884
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004885 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004886
Steve Naroffa4332e22007-07-17 00:58:39 +00004887 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004888 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004889 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004890}
4891
4892inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00004893 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004894 UsualUnaryConversions(lex);
4895 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004896
Anders Carlsson04905012009-10-16 01:44:21 +00004897 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4898 return InvalidOperands(Loc, lex, rex);
4899
4900 if (Context.getLangOptions().CPlusPlus) {
4901 // C++ [expr.log.and]p2
4902 // C++ [expr.log.or]p2
4903 return Context.BoolTy;
4904 }
4905
4906 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004907}
4908
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004909/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4910/// is a read-only property; return true if so. A readonly property expression
4911/// depends on various declarations and thus must be treated specially.
4912///
Mike Stump1eb44332009-09-09 15:08:12 +00004913static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004914 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4915 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4916 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4917 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004918 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00004919 BaseType->getAsObjCInterfacePointerType())
4920 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4921 if (S.isPropertyReadonly(PDecl, IFace))
4922 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004923 }
4924 }
4925 return false;
4926}
4927
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004928/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4929/// emit an error and return true. If so, return false.
4930static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004931 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00004932 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004933 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004934 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4935 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004936 if (IsLV == Expr::MLV_Valid)
4937 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004938
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004939 unsigned Diag = 0;
4940 bool NeedType = false;
4941 switch (IsLV) { // C99 6.5.16p2
4942 default: assert(0 && "Unknown result from isModifiableLvalue!");
4943 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004944 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004945 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4946 NeedType = true;
4947 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004948 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004949 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4950 NeedType = true;
4951 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00004952 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004953 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4954 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004955 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004956 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4957 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004958 case Expr::MLV_IncompleteType:
4959 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00004960 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00004961 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4962 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00004963 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004964 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4965 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00004966 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004967 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4968 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00004969 case Expr::MLV_ReadonlyProperty:
4970 Diag = diag::error_readonly_property_assignment;
4971 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00004972 case Expr::MLV_NoSetterProperty:
4973 Diag = diag::error_nosetter_property_assignment;
4974 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004975 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00004976
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004977 SourceRange Assign;
4978 if (Loc != OrigLoc)
4979 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004980 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004981 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004982 else
Mike Stump1eb44332009-09-09 15:08:12 +00004983 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004984 return true;
4985}
4986
4987
4988
4989// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004990QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4991 SourceLocation Loc,
4992 QualType CompoundType) {
4993 // Verify that LHS is a modifiable lvalue, and emit error if not.
4994 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004995 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004996
4997 QualType LHSType = LHS->getType();
4998 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004999
Chris Lattner5cf216b2008-01-04 18:04:52 +00005000 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005001 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005002 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005003 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005004 // Special case of NSObject attributes on c-style pointer types.
5005 if (ConvTy == IncompatiblePointer &&
5006 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005007 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005008 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005009 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005010 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005011
Chris Lattner2c156472008-08-21 18:04:13 +00005012 // If the RHS is a unary plus or minus, check to see if they = and + are
5013 // right next to each other. If so, the user may have typo'd "x =+ 4"
5014 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005015 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005016 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5017 RHSCheck = ICE->getSubExpr();
5018 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5019 if ((UO->getOpcode() == UnaryOperator::Plus ||
5020 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005021 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005022 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005023 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5024 // And there is a space or other character before the subexpr of the
5025 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005026 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5027 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005028 Diag(Loc, diag::warn_not_compound_assign)
5029 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5030 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005031 }
Chris Lattner2c156472008-08-21 18:04:13 +00005032 }
5033 } else {
5034 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005035 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005036 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005037
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005038 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5039 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005040 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005041
Reid Spencer5f016e22007-07-11 17:01:13 +00005042 // C99 6.5.16p3: The type of an assignment expression is the type of the
5043 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005044 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005045 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5046 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005047 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005048 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005049 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005050}
5051
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005052// C99 6.5.17
5053QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005054 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005055 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005056
5057 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5058 // incomplete in C++).
5059
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005060 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005061}
5062
Steve Naroff49b45262007-07-13 16:58:59 +00005063/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5064/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005065QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5066 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005067 if (Op->isTypeDependent())
5068 return Context.DependentTy;
5069
Chris Lattner3528d352008-11-21 07:05:48 +00005070 QualType ResType = Op->getType();
5071 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005072
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005073 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5074 // Decrement of bool is not allowed.
5075 if (!isInc) {
5076 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5077 return QualType();
5078 }
5079 // Increment of bool sets it to true, but is deprecated.
5080 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5081 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005082 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005083 } else if (ResType->isAnyPointerType()) {
5084 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005085
Chris Lattner3528d352008-11-21 07:05:48 +00005086 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005087 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005088 if (getLangOptions().CPlusPlus) {
5089 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5090 << Op->getSourceRange();
5091 return QualType();
5092 }
5093
5094 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005095 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005096 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005097 if (getLangOptions().CPlusPlus) {
5098 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5099 << Op->getType() << Op->getSourceRange();
5100 return QualType();
5101 }
5102
5103 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005104 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005105 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005106 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005107 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005108 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005109 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005110 // Diagnose bad cases where we step over interface counts.
5111 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5112 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5113 << PointeeTy << Op->getSourceRange();
5114 return QualType();
5115 }
Chris Lattner3528d352008-11-21 07:05:48 +00005116 } else if (ResType->isComplexType()) {
5117 // C99 does not support ++/-- on complex types, we allow as an extension.
5118 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005119 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005120 } else {
5121 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005122 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005123 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005124 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005125 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005126 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005127 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005128 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005129 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005130}
5131
Anders Carlsson369dee42008-02-01 07:15:58 +00005132/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005133/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005134/// where the declaration is needed for type checking. We only need to
5135/// handle cases when the expression references a function designator
5136/// or is an lvalue. Here are some examples:
5137/// - &(x) => x
5138/// - &*****f => f for f a function designator.
5139/// - &s.xx => s
5140/// - &s.zz[1].yy -> s, if zz is an array
5141/// - *(x + 1) -> x, if x is an array
5142/// - &"123"[2] -> 0
5143/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005144static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005145 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005146 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005147 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005148 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005149 // If this is an arrow operator, the address is an offset from
5150 // the base's value, so the object the base refers to is
5151 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005152 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005153 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005154 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005155 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005156 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005157 // FIXME: This code shouldn't be necessary! We should catch the implicit
5158 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005159 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5160 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5161 if (ICE->getSubExpr()->getType()->isArrayType())
5162 return getPrimaryDecl(ICE->getSubExpr());
5163 }
5164 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005165 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005166 case Stmt::UnaryOperatorClass: {
5167 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005168
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005169 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005170 case UnaryOperator::Real:
5171 case UnaryOperator::Imag:
5172 case UnaryOperator::Extension:
5173 return getPrimaryDecl(UO->getSubExpr());
5174 default:
5175 return 0;
5176 }
5177 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005178 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005179 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005180 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005181 // If the result of an implicit cast is an l-value, we care about
5182 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005183 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005184 default:
5185 return 0;
5186 }
5187}
5188
5189/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005190/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005191/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005192/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005193/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005194/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005195/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005196QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005197 // Make sure to ignore parentheses in subsequent checks
5198 op = op->IgnoreParens();
5199
Douglas Gregor9103bb22008-12-17 22:52:20 +00005200 if (op->isTypeDependent())
5201 return Context.DependentTy;
5202
Steve Naroff08f19672008-01-13 17:10:08 +00005203 if (getLangOptions().C99) {
5204 // Implement C99-only parts of addressof rules.
5205 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5206 if (uOp->getOpcode() == UnaryOperator::Deref)
5207 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5208 // (assuming the deref expression is valid).
5209 return uOp->getSubExpr()->getType();
5210 }
5211 // Technically, there should be a check for array subscript
5212 // expressions here, but the result of one is always an lvalue anyway.
5213 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005214 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005215 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005216
Eli Friedman441cf102009-05-16 23:27:50 +00005217 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5218 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005219 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005220 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005221 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005222 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5223 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005224 return QualType();
5225 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005226 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005227 // The operand cannot be a bit-field
5228 Diag(OpLoc, diag::err_typecheck_address_of)
5229 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005230 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005231 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5232 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005233 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005234 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005235 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005236 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005237 } else if (isa<ObjCPropertyRefExpr>(op)) {
5238 // cannot take address of a property expression.
5239 Diag(OpLoc, diag::err_typecheck_address_of)
5240 << "property expression" << op->getSourceRange();
5241 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005242 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5243 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005244 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5245 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Steve Naroffbcb2b612008-02-29 23:30:25 +00005246 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005247 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005248 // with the register storage-class specifier.
5249 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5250 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005251 Diag(OpLoc, diag::err_typecheck_address_of)
5252 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005253 return QualType();
5254 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00005255 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5256 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005257 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005258 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005259 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005260 // Could be a pointer to member, though, if there is an explicit
5261 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005262 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005263 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005264 if (Ctx && Ctx->isRecord()) {
5265 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005266 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005267 diag::err_cannot_form_pointer_to_member_of_reference_type)
5268 << FD->getDeclName() << FD->getType();
5269 return QualType();
5270 }
Mike Stump1eb44332009-09-09 15:08:12 +00005271
Sebastian Redlebc07d52009-02-03 20:19:35 +00005272 return Context.getMemberPointerType(op->getType(),
5273 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005274 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005275 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005276 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005277 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005278 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005279 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5280 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005281 return Context.getMemberPointerType(op->getType(),
5282 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5283 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005284 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005285 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005286
Eli Friedman441cf102009-05-16 23:27:50 +00005287 if (lval == Expr::LV_IncompleteVoidType) {
5288 // Taking the address of a void variable is technically illegal, but we
5289 // allow it in cases which are otherwise valid.
5290 // Example: "extern void x; void* y = &x;".
5291 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5292 }
5293
Reid Spencer5f016e22007-07-11 17:01:13 +00005294 // If the operand has type "type", the result has type "pointer to type".
5295 return Context.getPointerType(op->getType());
5296}
5297
Chris Lattner22caddc2008-11-23 09:13:29 +00005298QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005299 if (Op->isTypeDependent())
5300 return Context.DependentTy;
5301
Chris Lattner22caddc2008-11-23 09:13:29 +00005302 UsualUnaryConversions(Op);
5303 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005304
Chris Lattner22caddc2008-11-23 09:13:29 +00005305 // Note that per both C89 and C99, this is always legal, even if ptype is an
5306 // incomplete type or void. It would be possible to warn about dereferencing
5307 // a void pointer, but it's completely well-defined, and such a warning is
5308 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005309 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005310 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005311
John McCall183700f2009-09-21 23:43:11 +00005312 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005313 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005314
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005315 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005316 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005317 return QualType();
5318}
5319
5320static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5321 tok::TokenKind Kind) {
5322 BinaryOperator::Opcode Opc;
5323 switch (Kind) {
5324 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005325 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5326 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005327 case tok::star: Opc = BinaryOperator::Mul; break;
5328 case tok::slash: Opc = BinaryOperator::Div; break;
5329 case tok::percent: Opc = BinaryOperator::Rem; break;
5330 case tok::plus: Opc = BinaryOperator::Add; break;
5331 case tok::minus: Opc = BinaryOperator::Sub; break;
5332 case tok::lessless: Opc = BinaryOperator::Shl; break;
5333 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5334 case tok::lessequal: Opc = BinaryOperator::LE; break;
5335 case tok::less: Opc = BinaryOperator::LT; break;
5336 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5337 case tok::greater: Opc = BinaryOperator::GT; break;
5338 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5339 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5340 case tok::amp: Opc = BinaryOperator::And; break;
5341 case tok::caret: Opc = BinaryOperator::Xor; break;
5342 case tok::pipe: Opc = BinaryOperator::Or; break;
5343 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5344 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5345 case tok::equal: Opc = BinaryOperator::Assign; break;
5346 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5347 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5348 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5349 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5350 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5351 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5352 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5353 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5354 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5355 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5356 case tok::comma: Opc = BinaryOperator::Comma; break;
5357 }
5358 return Opc;
5359}
5360
5361static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5362 tok::TokenKind Kind) {
5363 UnaryOperator::Opcode Opc;
5364 switch (Kind) {
5365 default: assert(0 && "Unknown unary op!");
5366 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5367 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5368 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5369 case tok::star: Opc = UnaryOperator::Deref; break;
5370 case tok::plus: Opc = UnaryOperator::Plus; break;
5371 case tok::minus: Opc = UnaryOperator::Minus; break;
5372 case tok::tilde: Opc = UnaryOperator::Not; break;
5373 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005374 case tok::kw___real: Opc = UnaryOperator::Real; break;
5375 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5376 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5377 }
5378 return Opc;
5379}
5380
Douglas Gregoreaebc752008-11-06 23:29:22 +00005381/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5382/// operator @p Opc at location @c TokLoc. This routine only supports
5383/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005384Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5385 unsigned Op,
5386 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005387 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005388 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005389 // The following two variables are used for compound assignment operators
5390 QualType CompLHSTy; // Type of LHS after promotions for computation
5391 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005392
5393 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005394 case BinaryOperator::Assign:
5395 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5396 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005397 case BinaryOperator::PtrMemD:
5398 case BinaryOperator::PtrMemI:
5399 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5400 Opc == BinaryOperator::PtrMemI);
5401 break;
5402 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005403 case BinaryOperator::Div:
5404 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5405 break;
5406 case BinaryOperator::Rem:
5407 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5408 break;
5409 case BinaryOperator::Add:
5410 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5411 break;
5412 case BinaryOperator::Sub:
5413 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5414 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005415 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005416 case BinaryOperator::Shr:
5417 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5418 break;
5419 case BinaryOperator::LE:
5420 case BinaryOperator::LT:
5421 case BinaryOperator::GE:
5422 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005423 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005424 break;
5425 case BinaryOperator::EQ:
5426 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005427 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005428 break;
5429 case BinaryOperator::And:
5430 case BinaryOperator::Xor:
5431 case BinaryOperator::Or:
5432 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5433 break;
5434 case BinaryOperator::LAnd:
5435 case BinaryOperator::LOr:
5436 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5437 break;
5438 case BinaryOperator::MulAssign:
5439 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005440 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5441 CompLHSTy = CompResultTy;
5442 if (!CompResultTy.isNull())
5443 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005444 break;
5445 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005446 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5447 CompLHSTy = CompResultTy;
5448 if (!CompResultTy.isNull())
5449 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005450 break;
5451 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005452 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5453 if (!CompResultTy.isNull())
5454 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005455 break;
5456 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005457 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5458 if (!CompResultTy.isNull())
5459 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005460 break;
5461 case BinaryOperator::ShlAssign:
5462 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005463 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5464 CompLHSTy = CompResultTy;
5465 if (!CompResultTy.isNull())
5466 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005467 break;
5468 case BinaryOperator::AndAssign:
5469 case BinaryOperator::XorAssign:
5470 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005471 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5472 CompLHSTy = CompResultTy;
5473 if (!CompResultTy.isNull())
5474 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005475 break;
5476 case BinaryOperator::Comma:
5477 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5478 break;
5479 }
5480 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005481 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005482 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005483 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5484 else
5485 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005486 CompLHSTy, CompResultTy,
5487 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005488}
5489
Sebastian Redlaee3c932009-10-27 12:10:02 +00005490/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5491/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005492static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5493 const PartialDiagnostic &PD,
5494 SourceRange ParenRange)
5495{
5496 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5497 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5498 // We can't display the parentheses, so just dig the
5499 // warning/error and return.
5500 Self.Diag(Loc, PD);
5501 return;
5502 }
5503
5504 Self.Diag(Loc, PD)
5505 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5506 << CodeModificationHint::CreateInsertion(EndLoc, ")");
5507}
5508
Sebastian Redlaee3c932009-10-27 12:10:02 +00005509/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5510/// operators are mixed in a way that suggests that the programmer forgot that
5511/// comparison operators have higher precedence. The most typical example of
5512/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005513static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5514 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005515 typedef BinaryOperator BinOp;
5516 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5517 rhsopc = static_cast<BinOp::Opcode>(-1);
5518 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005519 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00005520 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005521 rhsopc = BO->getOpcode();
5522
5523 // Subs are not binary operators.
5524 if (lhsopc == -1 && rhsopc == -1)
5525 return;
5526
5527 // Bitwise operations are sometimes used as eager logical ops.
5528 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00005529 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5530 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005531 return;
5532
Sebastian Redlaee3c932009-10-27 12:10:02 +00005533 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005534 SuggestParentheses(Self, OpLoc,
5535 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005536 << SourceRange(lhs->getLocStart(), OpLoc)
5537 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5538 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5539 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005540 SuggestParentheses(Self, OpLoc,
5541 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005542 << SourceRange(OpLoc, rhs->getLocEnd())
5543 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5544 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005545}
5546
5547/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5548/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5549/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5550static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5551 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005552 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005553 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5554}
5555
Reid Spencer5f016e22007-07-11 17:01:13 +00005556// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005557Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5558 tok::TokenKind Kind,
5559 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005560 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00005561 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00005562
Steve Narofff69936d2007-09-16 03:34:24 +00005563 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5564 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005565
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005566 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5567 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5568
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005569 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
5570}
5571
5572Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
5573 BinaryOperator::Opcode Opc,
5574 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005575 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00005576 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00005577 rhs->getType()->isOverloadableType())) {
5578 // Find all of the overloaded operators visible from this
5579 // point. We perform both an operator-name lookup from the local
5580 // scope and an argument-dependent lookup based on the types of
5581 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005582 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00005583 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5584 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005585 if (S)
5586 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5587 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00005588 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00005589 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00005590 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005591 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005592 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005593
Douglas Gregor063daf62009-03-13 18:40:31 +00005594 // Build the (potentially-overloaded, potentially-dependent)
5595 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005596 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005597 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005598
Douglas Gregoreaebc752008-11-06 23:29:22 +00005599 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005600 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00005601}
5602
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005603Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005604 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005605 ExprArg InputArg) {
5606 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00005607
Mike Stump390b4cc2009-05-16 07:39:55 +00005608 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005609 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00005610 QualType resultType;
5611 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005612 case UnaryOperator::OffsetOf:
5613 assert(false && "Invalid unary operator");
5614 break;
5615
Reid Spencer5f016e22007-07-11 17:01:13 +00005616 case UnaryOperator::PreInc:
5617 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00005618 case UnaryOperator::PostInc:
5619 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005620 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00005621 Opc == UnaryOperator::PreInc ||
5622 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005623 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005624 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00005625 resultType = CheckAddressOfOperand(Input, OpLoc);
5626 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005627 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00005628 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00005629 resultType = CheckIndirectionOperand(Input, OpLoc);
5630 break;
5631 case UnaryOperator::Plus:
5632 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005633 UsualUnaryConversions(Input);
5634 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005635 if (resultType->isDependentType())
5636 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005637 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5638 break;
5639 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5640 resultType->isEnumeralType())
5641 break;
5642 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5643 Opc == UnaryOperator::Plus &&
5644 resultType->isPointerType())
5645 break;
5646
Sebastian Redl0eb23302009-01-19 00:08:26 +00005647 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5648 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005649 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005650 UsualUnaryConversions(Input);
5651 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005652 if (resultType->isDependentType())
5653 break;
Chris Lattner02a65142008-07-25 23:52:49 +00005654 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5655 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5656 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005657 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005658 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00005659 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005660 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5661 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005662 break;
5663 case UnaryOperator::LNot: // logical negation
5664 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005665 DefaultFunctionArrayConversion(Input);
5666 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005667 if (resultType->isDependentType())
5668 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005669 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00005670 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5671 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005672 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00005673 // In C++, it's bool. C++ 5.3.1p8
5674 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005675 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00005676 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00005677 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00005678 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00005679 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005680 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00005681 resultType = Input->getType();
5682 break;
5683 }
5684 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005685 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005686
5687 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00005688 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005689}
5690
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005691Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5692 UnaryOperator::Opcode Opc,
5693 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005694 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00005695 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
5696 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005697 // Find all of the overloaded operators visible from this
5698 // point. We perform both an operator-name lookup from the local
5699 // scope and an argument-dependent lookup based on the types of
5700 // the arguments.
5701 FunctionSet Functions;
5702 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5703 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005704 if (S)
5705 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5706 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00005707 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005708 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005709 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005710 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005711
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005712 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5713 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005714
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005715 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5716}
5717
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005718// Unary Operators. 'Tok' is the token for the operator.
5719Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5720 tok::TokenKind Op, ExprArg input) {
5721 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
5722}
5723
Steve Naroff1b273c42007-09-16 14:56:35 +00005724/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00005725Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5726 SourceLocation LabLoc,
5727 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005728 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00005729 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00005730
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00005731 // If we haven't seen this label yet, create a forward reference. It
5732 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00005733 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00005734 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005735
Reid Spencer5f016e22007-07-11 17:01:13 +00005736 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00005737 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5738 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00005739}
5740
Sebastian Redlf53597f2009-03-15 17:47:39 +00005741Sema::OwningExprResult
5742Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5743 SourceLocation RPLoc) { // "({..})"
5744 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005745 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5746 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5747
Eli Friedmandca2b732009-01-24 23:09:00 +00005748 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00005749 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005750 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00005751
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005752 // FIXME: there are a variety of strange constraints to enforce here, for
5753 // example, it is not possible to goto into a stmt expression apparently.
5754 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005755
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005756 // If there are sub stmts in the compound stmt, take the type of the last one
5757 // as the type of the stmtexpr.
5758 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005759
Chris Lattner611b2ec2008-07-26 19:51:01 +00005760 if (!Compound->body_empty()) {
5761 Stmt *LastStmt = Compound->body_back();
5762 // If LastStmt is a label, skip down through into the body.
5763 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5764 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005765
Chris Lattner611b2ec2008-07-26 19:51:01 +00005766 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005767 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00005768 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005769
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005770 // FIXME: Check that expression type is complete/non-abstract; statement
5771 // expressions are not lvalues.
5772
Sebastian Redlf53597f2009-03-15 17:47:39 +00005773 substmt.release();
5774 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005775}
Steve Naroffd34e9152007-08-01 22:05:33 +00005776
Sebastian Redlf53597f2009-03-15 17:47:39 +00005777Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5778 SourceLocation BuiltinLoc,
5779 SourceLocation TypeLoc,
5780 TypeTy *argty,
5781 OffsetOfComponent *CompPtr,
5782 unsigned NumComponents,
5783 SourceLocation RPLoc) {
5784 // FIXME: This function leaks all expressions in the offset components on
5785 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005786 // FIXME: Preserve type source info.
5787 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005788 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005789
Sebastian Redl28507842009-02-26 14:39:58 +00005790 bool Dependent = ArgTy->isDependentType();
5791
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005792 // We must have at least one component that refers to the type, and the first
5793 // one is known to be a field designator. Verify that the ArgTy represents
5794 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00005795 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005796 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005797
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005798 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5799 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00005800
Eli Friedman35183ac2009-02-27 06:44:11 +00005801 // Otherwise, create a null pointer as the base, and iteratively process
5802 // the offsetof designators.
5803 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5804 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005805 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00005806 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00005807
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005808 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5809 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00005810 // FIXME: This diagnostic isn't actually visible because the location is in
5811 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005812 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005813 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5814 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005815
Sebastian Redl28507842009-02-26 14:39:58 +00005816 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00005817 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005818
John McCalld00f2002009-11-04 03:03:43 +00005819 if (RequireCompleteType(TypeLoc, Res->getType(),
5820 diag::err_offsetof_incomplete_type))
5821 return ExprError();
5822
Sebastian Redl28507842009-02-26 14:39:58 +00005823 // FIXME: Dependent case loses a lot of information here. And probably
5824 // leaks like a sieve.
5825 for (unsigned i = 0; i != NumComponents; ++i) {
5826 const OffsetOfComponent &OC = CompPtr[i];
5827 if (OC.isBrackets) {
5828 // Offset of an array sub-field. TODO: Should we allow vector elements?
5829 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5830 if (!AT) {
5831 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005832 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5833 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005834 }
5835
5836 // FIXME: C++: Verify that operator[] isn't overloaded.
5837
Eli Friedman35183ac2009-02-27 06:44:11 +00005838 // Promote the array so it looks more like a normal array subscript
5839 // expression.
5840 DefaultFunctionArrayConversion(Res);
5841
Sebastian Redl28507842009-02-26 14:39:58 +00005842 // C99 6.5.2.1p1
5843 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005844 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005845 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005846 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00005847 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005848 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00005849
5850 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5851 OC.LocEnd);
5852 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005853 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005854
Ted Kremenek6217b802009-07-29 21:53:49 +00005855 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00005856 if (!RC) {
5857 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005858 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5859 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005860 }
Chris Lattner704fe352007-08-30 17:59:59 +00005861
Sebastian Redl28507842009-02-26 14:39:58 +00005862 // Get the decl corresponding to this.
5863 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005864 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005865 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00005866 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5867 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5868 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005869 DidWarnAboutNonPOD = true;
5870 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005871 }
Mike Stump1eb44332009-09-09 15:08:12 +00005872
John McCalla24dc2e2009-11-17 02:14:36 +00005873 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
5874 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00005875
Sebastian Redl28507842009-02-26 14:39:58 +00005876 FieldDecl *MemberDecl
John McCallf36e02d2009-10-09 21:13:30 +00005877 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redlf53597f2009-03-15 17:47:39 +00005878 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005879 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00005880 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5881 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005882
Sebastian Redl28507842009-02-26 14:39:58 +00005883 // FIXME: C++: Verify that MemberDecl isn't a static field.
5884 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005885 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005886 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00005887 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005888 } else {
5889 // MemberDecl->getType() doesn't get the right qualifiers, but it
5890 // doesn't matter here.
5891 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5892 MemberDecl->getType().getNonReferenceType());
5893 }
Sebastian Redl28507842009-02-26 14:39:58 +00005894 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005895 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005896
Sebastian Redlf53597f2009-03-15 17:47:39 +00005897 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5898 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005899}
5900
5901
Sebastian Redlf53597f2009-03-15 17:47:39 +00005902Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5903 TypeTy *arg1,TypeTy *arg2,
5904 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005905 // FIXME: Preserve type source info.
5906 QualType argT1 = GetTypeFromParser(arg1);
5907 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005908
Steve Naroffd34e9152007-08-01 22:05:33 +00005909 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005910
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005911 if (getLangOptions().CPlusPlus) {
5912 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5913 << SourceRange(BuiltinLoc, RPLoc);
5914 return ExprError();
5915 }
5916
Sebastian Redlf53597f2009-03-15 17:47:39 +00005917 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5918 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005919}
5920
Sebastian Redlf53597f2009-03-15 17:47:39 +00005921Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5922 ExprArg cond,
5923 ExprArg expr1, ExprArg expr2,
5924 SourceLocation RPLoc) {
5925 Expr *CondExpr = static_cast<Expr*>(cond.get());
5926 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5927 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005928
Steve Naroffd04fdd52007-08-03 21:21:27 +00005929 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5930
Sebastian Redl28507842009-02-26 14:39:58 +00005931 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00005932 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005933 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005934 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00005935 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00005936 } else {
5937 // The conditional expression is required to be a constant expression.
5938 llvm::APSInt condEval(32);
5939 SourceLocation ExpLoc;
5940 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00005941 return ExprError(Diag(ExpLoc,
5942 diag::err_typecheck_choose_expr_requires_constant)
5943 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00005944
Sebastian Redl28507842009-02-26 14:39:58 +00005945 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5946 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00005947 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5948 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00005949 }
5950
Sebastian Redlf53597f2009-03-15 17:47:39 +00005951 cond.release(); expr1.release(); expr2.release();
5952 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00005953 resType, RPLoc,
5954 resType->isDependentType(),
5955 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00005956}
5957
Steve Naroff4eb206b2008-09-03 18:15:37 +00005958//===----------------------------------------------------------------------===//
5959// Clang Extensions.
5960//===----------------------------------------------------------------------===//
5961
5962/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00005963void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005964 // Analyze block parameters.
5965 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005966
Steve Naroff4eb206b2008-09-03 18:15:37 +00005967 // Add BSI to CurBlock.
5968 BSI->PrevBlockInfo = CurBlock;
5969 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005970
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005971 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005972 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00005973 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00005974 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00005975 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5976 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005977
Steve Naroff090276f2008-10-10 01:28:17 +00005978 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00005979 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00005980}
5981
Mike Stump98eb8a72009-02-04 22:31:32 +00005982void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00005983 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00005984
5985 if (ParamInfo.getNumTypeObjects() == 0
5986 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005987 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00005988 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5989
Mike Stump4eeab842009-04-28 01:10:27 +00005990 if (T->isArrayType()) {
5991 Diag(ParamInfo.getSourceRange().getBegin(),
5992 diag::err_block_returns_array);
5993 return;
5994 }
5995
Mike Stump98eb8a72009-02-04 22:31:32 +00005996 // The parameter list is optional, if there was none, assume ().
5997 if (!T->isFunctionType())
5998 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5999
6000 CurBlock->hasPrototype = true;
6001 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006002 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006003 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006004 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006005 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006006 // FIXME: remove the attribute.
6007 }
John McCall183700f2009-09-21 23:43:11 +00006008 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006009
Chris Lattner9097af12009-04-11 19:27:54 +00006010 // Do not allow returning a objc interface by-value.
6011 if (RetTy->isObjCInterfaceType()) {
6012 Diag(ParamInfo.getSourceRange().getBegin(),
6013 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6014 return;
6015 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006016 return;
6017 }
6018
Steve Naroff4eb206b2008-09-03 18:15:37 +00006019 // Analyze arguments to block.
6020 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6021 "Not a function declarator!");
6022 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006023
Steve Naroff090276f2008-10-10 01:28:17 +00006024 CurBlock->hasPrototype = FTI.hasPrototype;
6025 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006026
Steve Naroff4eb206b2008-09-03 18:15:37 +00006027 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6028 // no arguments, not a function that takes a single void argument.
6029 if (FTI.hasPrototype &&
6030 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006031 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6032 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006033 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006034 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006035 } else if (FTI.hasPrototype) {
6036 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006037 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006038 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006039 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006040 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006041 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006042 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006043 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006044 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6045 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6046 // If this has an identifier, add it to the scope stack.
6047 if ((*AI)->getIdentifier())
6048 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006049
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006050 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006051 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006052 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006053 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006054 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006055 // FIXME: remove the attribute.
6056 }
Mike Stump1eb44332009-09-09 15:08:12 +00006057
Chris Lattner9097af12009-04-11 19:27:54 +00006058 // Analyze the return type.
6059 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006060 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006061
Chris Lattner9097af12009-04-11 19:27:54 +00006062 // Do not allow returning a objc interface by-value.
6063 if (RetTy->isObjCInterfaceType()) {
6064 Diag(ParamInfo.getSourceRange().getBegin(),
6065 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6066 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006067 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006068}
6069
6070/// ActOnBlockError - If there is an error parsing a block, this callback
6071/// is invoked to pop the information about the block from the action impl.
6072void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6073 // Ensure that CurBlock is deleted.
6074 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006075
Chris Lattner17a78302009-04-19 05:28:12 +00006076 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6077
Steve Naroff4eb206b2008-09-03 18:15:37 +00006078 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006079 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006080 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006081 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006082}
6083
6084/// ActOnBlockStmtExpr - This is called when the body of a block statement
6085/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006086Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6087 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006088 // If blocks are disabled, emit an error.
6089 if (!LangOpts.Blocks)
6090 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006091
Steve Naroff4eb206b2008-09-03 18:15:37 +00006092 // Ensure that CurBlock is deleted.
6093 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006094
Steve Naroff090276f2008-10-10 01:28:17 +00006095 PopDeclContext();
6096
Steve Naroff4eb206b2008-09-03 18:15:37 +00006097 // Pop off CurBlock, handle nested blocks.
6098 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006099
Steve Naroff4eb206b2008-09-03 18:15:37 +00006100 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006101 if (!BSI->ReturnType.isNull())
6102 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006103
Steve Naroff4eb206b2008-09-03 18:15:37 +00006104 llvm::SmallVector<QualType, 8> ArgTypes;
6105 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6106 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006107
Mike Stump56925862009-07-28 22:04:01 +00006108 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006109 QualType BlockTy;
6110 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006111 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6112 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006113 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006114 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006115 BSI->isVariadic, 0, false, false, 0, 0,
6116 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006117
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006118 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006119 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006120 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006121
Chris Lattner17a78302009-04-19 05:28:12 +00006122 // If needed, diagnose invalid gotos and switches in the block.
6123 if (CurFunctionNeedsScopeChecking)
6124 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6125 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006126
Anders Carlssone9146f22009-05-01 19:49:17 +00006127 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006128 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006129 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6130 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006131}
6132
Sebastian Redlf53597f2009-03-15 17:47:39 +00006133Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6134 ExprArg expr, TypeTy *type,
6135 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006136 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006137 Expr *E = static_cast<Expr*>(expr.get());
6138 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006139
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006140 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006141
6142 // Get the va_list type
6143 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006144 if (VaListType->isArrayType()) {
6145 // Deal with implicit array decay; for example, on x86-64,
6146 // va_list is an array, but it's supposed to decay to
6147 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006148 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006149 // Make sure the input expression also decays appropriately.
6150 UsualUnaryConversions(E);
6151 } else {
6152 // Otherwise, the va_list argument must be an l-value because
6153 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006154 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006155 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006156 return ExprError();
6157 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006158
Douglas Gregordd027302009-05-19 23:10:31 +00006159 if (!E->isTypeDependent() &&
6160 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006161 return ExprError(Diag(E->getLocStart(),
6162 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006163 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006164 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006165
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006166 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006167 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006168
Sebastian Redlf53597f2009-03-15 17:47:39 +00006169 expr.release();
6170 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6171 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006172}
6173
Sebastian Redlf53597f2009-03-15 17:47:39 +00006174Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006175 // The type of __null will be int or long, depending on the size of
6176 // pointers on the target.
6177 QualType Ty;
6178 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6179 Ty = Context.IntTy;
6180 else
6181 Ty = Context.LongTy;
6182
Sebastian Redlf53597f2009-03-15 17:47:39 +00006183 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006184}
6185
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006186static void
6187MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6188 QualType DstType,
6189 Expr *SrcExpr,
6190 CodeModificationHint &Hint) {
6191 if (!SemaRef.getLangOptions().ObjC1)
6192 return;
6193
6194 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6195 if (!PT)
6196 return;
6197
6198 // Check if the destination is of type 'id'.
6199 if (!PT->isObjCIdType()) {
6200 // Check if the destination is the 'NSString' interface.
6201 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6202 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6203 return;
6204 }
6205
6206 // Strip off any parens and casts.
6207 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6208 if (!SL || SL->isWide())
6209 return;
6210
6211 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6212}
6213
Chris Lattner5cf216b2008-01-04 18:04:52 +00006214bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6215 SourceLocation Loc,
6216 QualType DstType, QualType SrcType,
6217 Expr *SrcExpr, const char *Flavor) {
6218 // Decode the result (notice that AST's are still created for extensions).
6219 bool isInvalid = false;
6220 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006221 CodeModificationHint Hint;
6222
Chris Lattner5cf216b2008-01-04 18:04:52 +00006223 switch (ConvTy) {
6224 default: assert(0 && "Unknown conversion type");
6225 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006226 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006227 DiagKind = diag::ext_typecheck_convert_pointer_int;
6228 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006229 case IntToPointer:
6230 DiagKind = diag::ext_typecheck_convert_int_pointer;
6231 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006232 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006233 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006234 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6235 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006236 case IncompatiblePointerSign:
6237 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6238 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006239 case FunctionVoidPointer:
6240 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6241 break;
6242 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006243 // If the qualifiers lost were because we were applying the
6244 // (deprecated) C++ conversion from a string literal to a char*
6245 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6246 // Ideally, this check would be performed in
6247 // CheckPointerTypesForAssignment. However, that would require a
6248 // bit of refactoring (so that the second argument is an
6249 // expression, rather than a type), which should be done as part
6250 // of a larger effort to fix CheckPointerTypesForAssignment for
6251 // C++ semantics.
6252 if (getLangOptions().CPlusPlus &&
6253 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6254 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006255 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6256 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006257 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006258 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006259 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006260 case IntToBlockPointer:
6261 DiagKind = diag::err_int_to_block_pointer;
6262 break;
6263 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006264 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006265 break;
Steve Naroff39579072008-10-14 22:18:38 +00006266 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006267 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006268 // it can give a more specific diagnostic.
6269 DiagKind = diag::warn_incompatible_qualified_id;
6270 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006271 case IncompatibleVectors:
6272 DiagKind = diag::warn_incompatible_vectors;
6273 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006274 case Incompatible:
6275 DiagKind = diag::err_typecheck_convert_incompatible;
6276 isInvalid = true;
6277 break;
6278 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006279
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006280 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006281 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006282 return isInvalid;
6283}
Anders Carlssone21555e2008-11-30 19:50:32 +00006284
Chris Lattner3bf68932009-04-25 21:59:05 +00006285bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006286 llvm::APSInt ICEResult;
6287 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6288 if (Result)
6289 *Result = ICEResult;
6290 return false;
6291 }
6292
Anders Carlssone21555e2008-11-30 19:50:32 +00006293 Expr::EvalResult EvalResult;
6294
Mike Stumpeed9cac2009-02-19 03:04:26 +00006295 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006296 EvalResult.HasSideEffects) {
6297 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6298
6299 if (EvalResult.Diag) {
6300 // We only show the note if it's not the usual "invalid subexpression"
6301 // or if it's actually in a subexpression.
6302 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6303 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6304 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6305 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006306
Anders Carlssone21555e2008-11-30 19:50:32 +00006307 return true;
6308 }
6309
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006310 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6311 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006312
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006313 if (EvalResult.Diag &&
6314 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6315 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006316
Anders Carlssone21555e2008-11-30 19:50:32 +00006317 if (Result)
6318 *Result = EvalResult.Val.getInt();
6319 return false;
6320}
Douglas Gregore0762c92009-06-19 23:52:42 +00006321
Mike Stump1eb44332009-09-09 15:08:12 +00006322Sema::ExpressionEvaluationContext
6323Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006324 // Introduce a new set of potentially referenced declarations to the stack.
6325 if (NewContext == PotentiallyPotentiallyEvaluated)
6326 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump1eb44332009-09-09 15:08:12 +00006327
Douglas Gregorac7610d2009-06-22 20:57:11 +00006328 std::swap(ExprEvalContext, NewContext);
6329 return NewContext;
6330}
6331
Mike Stump1eb44332009-09-09 15:08:12 +00006332void
Douglas Gregorac7610d2009-06-22 20:57:11 +00006333Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6334 ExpressionEvaluationContext NewContext) {
6335 ExprEvalContext = NewContext;
6336
6337 if (OldContext == PotentiallyPotentiallyEvaluated) {
6338 // Mark any remaining declarations in the current position of the stack
6339 // as "referenced". If they were not meant to be referenced, semantic
6340 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6341 PotentiallyReferencedDecls RemainingDecls;
6342 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6343 PotentiallyReferencedDeclStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00006344
Douglas Gregorac7610d2009-06-22 20:57:11 +00006345 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6346 IEnd = RemainingDecls.end();
6347 I != IEnd; ++I)
6348 MarkDeclarationReferenced(I->first, I->second);
6349 }
6350}
Douglas Gregore0762c92009-06-19 23:52:42 +00006351
6352/// \brief Note that the given declaration was referenced in the source code.
6353///
6354/// This routine should be invoke whenever a given declaration is referenced
6355/// in the source code, and where that reference occurred. If this declaration
6356/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6357/// C99 6.9p3), then the declaration will be marked as used.
6358///
6359/// \param Loc the location where the declaration was referenced.
6360///
6361/// \param D the declaration that has been referenced by the source code.
6362void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6363 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006364
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006365 if (D->isUsed())
6366 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006367
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006368 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6369 // template or not. The reason for this is that unevaluated expressions
6370 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6371 // -Wunused-parameters)
6372 if (isa<ParmVarDecl>(D) ||
6373 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006374 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006375
Douglas Gregore0762c92009-06-19 23:52:42 +00006376 // Do not mark anything as "used" within a dependent context; wait for
6377 // an instantiation.
6378 if (CurContext->isDependentContext())
6379 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006380
Douglas Gregorac7610d2009-06-22 20:57:11 +00006381 switch (ExprEvalContext) {
6382 case Unevaluated:
6383 // We are in an expression that is not potentially evaluated; do nothing.
6384 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006385
Douglas Gregorac7610d2009-06-22 20:57:11 +00006386 case PotentiallyEvaluated:
6387 // We are in a potentially-evaluated expression, so this declaration is
6388 // "used"; handle this below.
6389 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006390
Douglas Gregorac7610d2009-06-22 20:57:11 +00006391 case PotentiallyPotentiallyEvaluated:
6392 // We are in an expression that may be potentially evaluated; queue this
6393 // declaration reference until we know whether the expression is
6394 // potentially evaluated.
6395 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6396 return;
6397 }
Mike Stump1eb44332009-09-09 15:08:12 +00006398
Douglas Gregore0762c92009-06-19 23:52:42 +00006399 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006400 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006401 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006402 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6403 if (!Constructor->isUsed())
6404 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006405 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006406 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006407 if (!Constructor->isUsed())
6408 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6409 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006410 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6411 if (Destructor->isImplicit() && !Destructor->isUsed())
6412 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006413
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006414 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6415 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6416 MethodDecl->getOverloadedOperator() == OO_Equal) {
6417 if (!MethodDecl->isUsed())
6418 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6419 }
6420 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006421 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006422 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006423 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006424 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006425 bool AlreadyInstantiated = false;
6426 if (FunctionTemplateSpecializationInfo *SpecInfo
6427 = Function->getTemplateSpecializationInfo()) {
6428 if (SpecInfo->getPointOfInstantiation().isInvalid())
6429 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006430 else if (SpecInfo->getTemplateSpecializationKind()
6431 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006432 AlreadyInstantiated = true;
6433 } else if (MemberSpecializationInfo *MSInfo
6434 = Function->getMemberSpecializationInfo()) {
6435 if (MSInfo->getPointOfInstantiation().isInvalid())
6436 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006437 else if (MSInfo->getTemplateSpecializationKind()
6438 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006439 AlreadyInstantiated = true;
6440 }
6441
6442 if (!AlreadyInstantiated)
6443 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6444 }
6445
Douglas Gregore0762c92009-06-19 23:52:42 +00006446 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006447 Function->setUsed(true);
6448 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006449 }
Mike Stump1eb44332009-09-09 15:08:12 +00006450
Douglas Gregore0762c92009-06-19 23:52:42 +00006451 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006452 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006453 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006454 Var->getInstantiatedFromStaticDataMember()) {
6455 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6456 assert(MSInfo && "Missing member specialization information?");
6457 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6458 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6459 MSInfo->setPointOfInstantiation(Loc);
6460 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6461 }
6462 }
Mike Stump1eb44332009-09-09 15:08:12 +00006463
Douglas Gregore0762c92009-06-19 23:52:42 +00006464 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006465
Douglas Gregore0762c92009-06-19 23:52:42 +00006466 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006467 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006468 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006469}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006470
6471bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6472 CallExpr *CE, FunctionDecl *FD) {
6473 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6474 return false;
6475
6476 PartialDiagnostic Note =
6477 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6478 << FD->getDeclName() : PDiag();
6479 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6480
6481 if (RequireCompleteType(Loc, ReturnType,
6482 FD ?
6483 PDiag(diag::err_call_function_incomplete_return)
6484 << CE->getSourceRange() << FD->getDeclName() :
6485 PDiag(diag::err_call_incomplete_return)
6486 << CE->getSourceRange(),
6487 std::make_pair(NoteLoc, Note)))
6488 return true;
6489
6490 return false;
6491}
6492
John McCall5a881bb2009-10-12 21:59:07 +00006493// Diagnose the common s/=/==/ typo. Note that adding parentheses
6494// will prevent this condition from triggering, which is what we want.
6495void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6496 SourceLocation Loc;
6497
John McCalla52ef082009-11-11 02:41:58 +00006498 unsigned diagnostic = diag::warn_condition_is_assignment;
6499
John McCall5a881bb2009-10-12 21:59:07 +00006500 if (isa<BinaryOperator>(E)) {
6501 BinaryOperator *Op = cast<BinaryOperator>(E);
6502 if (Op->getOpcode() != BinaryOperator::Assign)
6503 return;
6504
John McCallc8d8ac52009-11-12 00:06:05 +00006505 // Greylist some idioms by putting them into a warning subcategory.
6506 if (ObjCMessageExpr *ME
6507 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
6508 Selector Sel = ME->getSelector();
6509
John McCallc8d8ac52009-11-12 00:06:05 +00006510 // self = [<foo> init...]
6511 if (isSelfExpr(Op->getLHS())
6512 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
6513 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6514
6515 // <foo> = [<bar> nextObject]
6516 else if (Sel.isUnarySelector() &&
6517 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
6518 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6519 }
John McCalla52ef082009-11-11 02:41:58 +00006520
John McCall5a881bb2009-10-12 21:59:07 +00006521 Loc = Op->getOperatorLoc();
6522 } else if (isa<CXXOperatorCallExpr>(E)) {
6523 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6524 if (Op->getOperator() != OO_Equal)
6525 return;
6526
6527 Loc = Op->getOperatorLoc();
6528 } else {
6529 // Not an assignment.
6530 return;
6531 }
6532
John McCall5a881bb2009-10-12 21:59:07 +00006533 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00006534 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00006535
John McCalla52ef082009-11-11 02:41:58 +00006536 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00006537 << E->getSourceRange()
6538 << CodeModificationHint::CreateInsertion(Open, "(")
6539 << CodeModificationHint::CreateInsertion(Close, ")");
6540}
6541
6542bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6543 DiagnoseAssignmentAsCondition(E);
6544
6545 if (!E->isTypeDependent()) {
6546 DefaultFunctionArrayConversion(E);
6547
6548 QualType T = E->getType();
6549
6550 if (getLangOptions().CPlusPlus) {
6551 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6552 return true;
6553 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6554 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6555 << T << E->getSourceRange();
6556 return true;
6557 }
6558 }
6559
6560 return false;
6561}