blob: 4dd3c2dbef4d0ea76e4e8a6ae32a05a44bbcf948 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
David Chisnall0f436562009-08-17 16:35:33 +000030
Douglas Gregor48f3bb92009-02-18 21:56:37 +000031/// \brief Determine whether the use of this declaration is valid, and
32/// emit any corresponding diagnostics.
33///
34/// This routine diagnoses various problems with referencing
35/// declarations that can occur when using a declaration. For example,
36/// it might warn if a deprecated or unavailable declaration is being
37/// used, or produce an error (and return true) if a C++0x deleted
38/// function is being used.
39///
Chris Lattner52338262009-10-25 22:31:57 +000040/// If IgnoreDeprecated is set to true, this should not want about deprecated
41/// decls.
42///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000043/// \returns true if there was an error (this declaration cannot be
44/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000045///
46bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
47 bool IgnoreDeprecated) {
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>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000050 // Implementing deprecated stuff requires referencing deprecated
Chris Lattner52338262009-10-25 22:31:57 +000051 // stuff. Don't warn if we are implementing a deprecated construct.
52 bool isSilenced = IgnoreDeprecated;
Mike Stump1eb44332009-09-09 15:08:12 +000053
Chris Lattnerf15970c2009-02-16 19:35:30 +000054 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
55 // If this reference happens *in* a deprecated function or method, don't
56 // warn.
Chris Lattner52338262009-10-25 22:31:57 +000057 isSilenced |= ND->getAttr<DeprecatedAttr>() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +000058
Chris Lattnerf15970c2009-02-16 19:35:30 +000059 // If this is an Objective-C method implementation, check to see if the
60 // method was deprecated on the declaration, not the definition.
61 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
62 // The semantic decl context of a ObjCMethodDecl is the
63 // ObjCImplementationDecl.
64 if (ObjCImplementationDecl *Impl
65 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
Mike Stump1eb44332009-09-09 15:08:12 +000066
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000067 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerf15970c2009-02-16 19:35:30 +000068 MD->isInstanceMethod());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000069 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerf15970c2009-02-16 19:35:30 +000070 }
71 }
72 }
Mike Stump1eb44332009-09-09 15:08:12 +000073
Chris Lattnerf15970c2009-02-16 19:35:30 +000074 if (!isSilenced)
Chris Lattner76a642f2009-02-15 22:43:40 +000075 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
76 }
77
Chris Lattnerffb93682009-10-25 17:21:40 +000078 // See if the decl is unavailable
79 if (D->getAttr<UnavailableAttr>()) {
80 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
81 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
82 }
83
Douglas Gregor48f3bb92009-02-18 21:56:37 +000084 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000085 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000086 if (FD->isDeleted()) {
87 Diag(Loc, diag::err_deleted_function_use);
88 Diag(D->getLocation(), diag::note_unavailable_here) << true;
89 return true;
90 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000091 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000092
Douglas Gregor48f3bb92009-02-18 21:56:37 +000093 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000094}
95
Fariborz Jahanian5b530052009-05-13 18:09:35 +000096/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000097/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000098/// attribute. It warns if call does not have the sentinel argument.
99///
100void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000101 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000102 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000103 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000104 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000105 int sentinelPos = attr->getSentinel();
106 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Mike Stump390b4cc2009-05-16 07:39:55 +0000108 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
109 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000110 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000111 bool warnNotEnoughArgs = false;
112 int isMethod = 0;
113 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
114 // skip over named parameters.
115 ObjCMethodDecl::param_iterator P, E = MD->param_end();
116 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
117 if (nullPos)
118 --nullPos;
119 else
120 ++i;
121 }
122 warnNotEnoughArgs = (P != E || i >= NumArgs);
123 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000124 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000125 // skip over named parameters.
126 ObjCMethodDecl::param_iterator P, E = FD->param_end();
127 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
128 if (nullPos)
129 --nullPos;
130 else
131 ++i;
132 }
133 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000134 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000135 // block or function pointer call.
136 QualType Ty = V->getType();
137 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000138 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000139 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
140 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000141 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
142 unsigned NumArgsInProto = Proto->getNumArgs();
143 unsigned k;
144 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
145 if (nullPos)
146 --nullPos;
147 else
148 ++i;
149 }
150 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
151 }
152 if (Ty->isBlockPointerType())
153 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000154 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000155 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000156 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000157 return;
158
159 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000160 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000161 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000162 return;
163 }
164 int sentinel = i;
165 while (sentinelPos > 0 && i < NumArgs-1) {
166 --sentinelPos;
167 ++i;
168 }
169 if (sentinelPos > 0) {
170 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000171 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000172 return;
173 }
174 while (i < NumArgs-1) {
175 ++i;
176 ++sentinel;
177 }
178 Expr *sentinelExpr = Args[sentinel];
179 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
Douglas Gregorce940492009-09-25 04:25:58 +0000180 !sentinelExpr->isNullPointerConstant(Context,
181 Expr::NPC_ValueDependentIsNull))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000182 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000183 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000184 }
185 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000186}
187
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000188SourceRange Sema::getExprRange(ExprTy *E) const {
189 Expr *Ex = (Expr *)E;
190 return Ex? Ex->getSourceRange() : SourceRange();
191}
192
Chris Lattnere7a2e912008-07-25 21:10:04 +0000193//===----------------------------------------------------------------------===//
194// Standard Promotions and Conversions
195//===----------------------------------------------------------------------===//
196
Chris Lattnere7a2e912008-07-25 21:10:04 +0000197/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
198void Sema::DefaultFunctionArrayConversion(Expr *&E) {
199 QualType Ty = E->getType();
200 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
201
Chris Lattnere7a2e912008-07-25 21:10:04 +0000202 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000203 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000204 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000205 else if (Ty->isArrayType()) {
206 // In C90 mode, arrays only promote to pointers if the array expression is
207 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
208 // type 'array of type' is converted to an expression that has type 'pointer
209 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
210 // that has type 'array of type' ...". The relevant change is "an lvalue"
211 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000212 //
213 // C++ 4.2p1:
214 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
215 // T" can be converted to an rvalue of type "pointer to T".
216 //
217 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
218 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000219 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
220 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000221 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000222}
223
224/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000225/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000226/// sometimes surpressed. For example, the array->pointer conversion doesn't
227/// apply if the array is an argument to the sizeof or address (&) operators.
228/// In these instances, this routine should *not* be called.
229Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
230 QualType Ty = Expr->getType();
231 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Douglas Gregorfc24e442009-05-01 20:41:21 +0000233 // C99 6.3.1.1p2:
234 //
235 // The following may be used in an expression wherever an int or
236 // unsigned int may be used:
237 // - an object or expression with an integer type whose integer
238 // conversion rank is less than or equal to the rank of int
239 // and unsigned int.
240 // - A bit-field of type _Bool, int, signed int, or unsigned int.
241 //
242 // If an int can represent all values of the original type, the
243 // value is converted to an int; otherwise, it is converted to an
244 // unsigned int. These are called the integer promotions. All
245 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000246 QualType PTy = Context.isPromotableBitField(Expr);
247 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000248 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000249 return Expr;
250 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000251 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000252 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000253 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000254 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000255 }
256
Douglas Gregorfc24e442009-05-01 20:41:21 +0000257 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000258 return Expr;
259}
260
Chris Lattner05faf172008-07-25 22:25:12 +0000261/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000262/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000263/// double. All other argument types are converted by UsualUnaryConversions().
264void Sema::DefaultArgumentPromotion(Expr *&Expr) {
265 QualType Ty = Expr->getType();
266 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattner05faf172008-07-25 22:25:12 +0000268 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000269 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000270 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000271 return ImpCastExprToType(Expr, Context.DoubleTy,
272 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattner05faf172008-07-25 22:25:12 +0000274 UsualUnaryConversions(Expr);
275}
276
Chris Lattner312531a2009-04-12 08:11:20 +0000277/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
278/// will warn if the resulting type is not a POD type, and rejects ObjC
279/// interfaces passed by value. This returns true if the argument type is
280/// completely illegal.
281bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000282 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Chris Lattner312531a2009-04-12 08:11:20 +0000284 if (Expr->getType()->isObjCInterfaceType()) {
285 Diag(Expr->getLocStart(),
286 diag::err_cannot_pass_objc_interface_to_vararg)
287 << Expr->getType() << CT;
288 return true;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000289 }
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattner312531a2009-04-12 08:11:20 +0000291 if (!Expr->getType()->isPODType())
292 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
293 << Expr->getType() << CT;
294
295 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000296}
297
298
Chris Lattnere7a2e912008-07-25 21:10:04 +0000299/// UsualArithmeticConversions - Performs various conversions that are common to
300/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000301/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000302/// responsible for emitting appropriate error diagnostics.
303/// FIXME: verify the conversion rules for "complex int" are consistent with
304/// GCC.
305QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
306 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000307 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000308 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000309
310 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000311
Mike Stump1eb44332009-09-09 15:08:12 +0000312 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000313 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000314 QualType lhs =
315 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000316 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000317 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000318
319 // If both types are identical, no conversion is needed.
320 if (lhs == rhs)
321 return lhs;
322
323 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
324 // The caller can deal with this (e.g. pointer + int).
325 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
326 return lhs;
327
Douglas Gregor2d833e32009-05-02 00:36:19 +0000328 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000329 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000330 if (!LHSBitfieldPromoteTy.isNull())
331 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000332 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000333 if (!RHSBitfieldPromoteTy.isNull())
334 rhs = RHSBitfieldPromoteTy;
335
Eli Friedmana95d7572009-08-19 07:44:53 +0000336 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000337 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000338 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
339 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000340 return destType;
341}
342
Chris Lattnere7a2e912008-07-25 21:10:04 +0000343//===----------------------------------------------------------------------===//
344// Semantic Analysis for various Expression Types
345//===----------------------------------------------------------------------===//
346
347
Steve Narofff69936d2007-09-16 03:34:24 +0000348/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000349/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
350/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
351/// multiple tokens. However, the common case is that StringToks points to one
352/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000353///
354Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000355Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 assert(NumStringToks && "Must have at least one string!");
357
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000358 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000360 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000361
362 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
363 for (unsigned i = 0; i != NumStringToks; ++i)
364 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000365
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000366 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000367 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000368 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000369
370 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
371 if (getLangOptions().CPlusPlus)
372 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000373
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000374 // Get an array type for the string, according to C99 6.4.5. This includes
375 // the nul terminator character as well as the string length for pascal
376 // strings.
377 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000378 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000379 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000382 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000383 Literal.GetStringLength(),
384 Literal.AnyWide, StrTy,
385 &StringTokLocs[0],
386 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000387}
388
Chris Lattner639e2d32008-10-20 05:16:36 +0000389/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
390/// CurBlock to VD should cause it to be snapshotted (as we do for auto
391/// variables defined outside the block) or false if this is not needed (e.g.
392/// for values inside the block or for globals).
393///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000394/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
395/// up-to-date.
396///
Chris Lattner639e2d32008-10-20 05:16:36 +0000397static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
398 ValueDecl *VD) {
399 // If the value is defined inside the block, we couldn't snapshot it even if
400 // we wanted to.
401 if (CurBlock->TheDecl == VD->getDeclContext())
402 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattner639e2d32008-10-20 05:16:36 +0000404 // If this is an enum constant or function, it is constant, don't snapshot.
405 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
406 return false;
407
408 // If this is a reference to an extern, static, or global variable, no need to
409 // snapshot it.
410 // FIXME: What about 'const' variables in C++?
411 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000412 if (!Var->hasLocalStorage())
413 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000415 // Blocks that have these can't be constant.
416 CurBlock->hasBlockDeclRefExprs = true;
417
418 // If we have nested blocks, the decl may be declared in an outer block (in
419 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
420 // be defined outside all of the current blocks (in which case the blocks do
421 // all get the bit). Walk the nesting chain.
422 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
423 NextBlock = NextBlock->PrevBlockInfo) {
424 // If we found the defining block for the variable, don't mark the block as
425 // having a reference outside it.
426 if (NextBlock->TheDecl == VD->getDeclContext())
427 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000429 // Otherwise, the DeclRef from the inner block causes the outer one to need
430 // a snapshot as well.
431 NextBlock->hasBlockDeclRefExprs = true;
432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattner639e2d32008-10-20 05:16:36 +0000434 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000435}
436
Chris Lattner639e2d32008-10-20 05:16:36 +0000437
438
Douglas Gregora2813ce2009-10-23 18:54:35 +0000439/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000440Sema::OwningExprResult
Sebastian Redlebc07d52009-02-03 20:19:35 +0000441Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
442 bool TypeDependent, bool ValueDependent,
443 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000444 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
445 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000446 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000447 << D->getDeclName();
448 return ExprError();
449 }
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Anders Carlssone41590d2009-06-24 00:10:43 +0000451 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
452 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
453 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
454 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000455 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000456 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000457 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000458 << D->getIdentifier();
459 return ExprError();
460 }
461 }
462 }
463 }
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Douglas Gregore0762c92009-06-19 23:52:42 +0000465 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Douglas Gregora2813ce2009-10-23 18:54:35 +0000467 return Owned(DeclRefExpr::Create(Context,
468 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
469 SS? SS->getRange() : SourceRange(),
470 D, Loc,
471 Ty, TypeDependent, ValueDependent));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000472}
473
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000474/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
475/// variable corresponding to the anonymous union or struct whose type
476/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000477static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
478 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000479 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000480 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Mike Stump390b4cc2009-05-16 07:39:55 +0000482 // FIXME: Once Decls are directly linked together, this will be an O(1)
483 // operation rather than a slow walk through DeclContext's vector (which
484 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000485 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000486 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000487 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000488 D != DEnd; ++D) {
489 if (*D == Record) {
490 // The object for the anonymous struct/union directly
491 // follows its type in the list of declarations.
492 ++D;
493 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000494 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000495 return *D;
496 }
497 }
498
499 assert(false && "Missing object for anonymous record");
500 return 0;
501}
502
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000503/// \brief Given a field that represents a member of an anonymous
504/// struct/union, build the path from that field's context to the
505/// actual member.
506///
507/// Construct the sequence of field member references we'll have to
508/// perform to get to the field in the anonymous union/struct. The
509/// list of members is built from the field outward, so traverse it
510/// backwards to go from an object in the current context to the field
511/// we found.
512///
513/// \returns The variable from which the field access should begin,
514/// for an anonymous struct/union that is not a member of another
515/// class. Otherwise, returns NULL.
516VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
517 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000518 assert(Field->getDeclContext()->isRecord() &&
519 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
520 && "Field must be stored inside an anonymous struct or union");
521
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000522 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000523 VarDecl *BaseObject = 0;
524 DeclContext *Ctx = Field->getDeclContext();
525 do {
526 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000527 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000528 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000529 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000530 else {
531 BaseObject = cast<VarDecl>(AnonObject);
532 break;
533 }
534 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000535 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000536 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000537
538 return BaseObject;
539}
540
541Sema::OwningExprResult
542Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
543 FieldDecl *Field,
544 Expr *BaseObjectExpr,
545 SourceLocation OpLoc) {
546 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000547 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000548 AnonFields);
549
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000550 // Build the expression that refers to the base object, from
551 // which we will build a sequence of member references to each
552 // of the anonymous union objects and, eventually, the field we
553 // found via name lookup.
554 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000555 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000556 if (BaseObject) {
557 // BaseObject is an anonymous struct/union variable (and is,
558 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000559 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000560 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000561 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000562 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000563 BaseQuals
564 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000565 } else if (BaseObjectExpr) {
566 // The caller provided the base object expression. Determine
567 // whether its a pointer and whether it adds any qualifiers to the
568 // anonymous struct/union fields we're looking into.
569 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000570 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000571 BaseObjectIsPointer = true;
572 ObjectType = ObjectPtr->getPointeeType();
573 }
John McCall0953e762009-09-24 19:53:00 +0000574 BaseQuals
575 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000576 } else {
577 // We've found a member of an anonymous struct/union that is
578 // inside a non-anonymous struct/union, so in a well-formed
579 // program our base object expression is "this".
580 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
581 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000582 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000583 = Context.getTagDeclType(
584 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
585 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000586 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000587 == Context.getCanonicalType(ThisType)) ||
588 IsDerivedFrom(ThisType, AnonFieldType)) {
589 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000590 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000591 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000592 BaseObjectIsPointer = true;
593 }
594 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000595 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
596 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000597 }
John McCall0953e762009-09-24 19:53:00 +0000598 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000599 }
600
Mike Stump1eb44332009-09-09 15:08:12 +0000601 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000602 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
603 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000604 }
605
606 // Build the implicit member references to the field of the
607 // anonymous struct/union.
608 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000609 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000610 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
611 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
612 FI != FIEnd; ++FI) {
613 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000614 Qualifiers MemberTypeQuals =
615 Context.getCanonicalType(MemberType).getQualifiers();
616
617 // CVR attributes from the base are picked up by members,
618 // except that 'mutable' members don't pick up 'const'.
619 if ((*FI)->isMutable())
620 ResultQuals.removeConst();
621
622 // GC attributes are never picked up by members.
623 ResultQuals.removeObjCGCAttr();
624
625 // TR 18037 does not allow fields to be declared with address spaces.
626 assert(!MemberTypeQuals.hasAddressSpace());
627
628 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
629 if (NewQuals != MemberTypeQuals)
630 MemberType = Context.getQualifiedType(MemberType, NewQuals);
631
Douglas Gregore0762c92009-06-19 23:52:42 +0000632 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000633 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000634 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
635 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000636 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000637 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000638 }
639
Sebastian Redlcd965b92009-01-18 18:53:16 +0000640 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000641}
642
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000643Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
644 const CXXScopeSpec &SS,
645 UnqualifiedId &Name,
646 bool HasTrailingLParen,
647 bool IsAddressOfOperand) {
648 if (Name.getKind() == UnqualifiedId::IK_TemplateId) {
649 ASTTemplateArgsPtr TemplateArgsPtr(*this,
650 Name.TemplateId->getTemplateArgs(),
651 Name.TemplateId->getTemplateArgIsType(),
652 Name.TemplateId->NumArgs);
653 return ActOnTemplateIdExpr(SS,
654 TemplateTy::make(Name.TemplateId->Template),
655 Name.TemplateId->TemplateNameLoc,
656 Name.TemplateId->LAngleLoc,
657 TemplateArgsPtr,
658 Name.TemplateId->getTemplateArgLocations(),
659 Name.TemplateId->RAngleLoc);
660 }
661
662 // FIXME: We lose a bunch of source information by doing this. Later,
663 // we'll want to merge ActOnDeclarationNameExpr's logic into
664 // ActOnIdExpression.
665 return ActOnDeclarationNameExpr(S,
666 Name.StartLocation,
667 GetNameFromUnqualifiedId(Name),
668 HasTrailingLParen,
669 &SS,
670 IsAddressOfOperand);
671}
672
Douglas Gregor10c42622008-11-18 15:03:34 +0000673/// ActOnDeclarationNameExpr - The parser has read some kind of name
674/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
675/// performs lookup on that name and returns an expression that refers
676/// to that name. This routine isn't directly called from the parser,
677/// because the parser doesn't know about DeclarationName. Rather,
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000678/// this routine is called by ActOnIdExpression, which contains a
679/// parsed UnqualifiedId.
Douglas Gregor10c42622008-11-18 15:03:34 +0000680///
681/// HasTrailingLParen indicates whether this identifier is used in a
682/// function call context. LookupCtx is only used for a C++
683/// qualified-id (foo::bar) to indicate the class or namespace that
684/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000685///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000686/// isAddressOfOperand means that this expression is the direct operand
687/// of an address-of operator. This matters because this is the only
688/// situation where a qualified name referencing a non-static member may
689/// appear outside a member function of this class.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000690Sema::OwningExprResult
691Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
692 DeclarationName Name, bool HasTrailingLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000693 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000694 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000695 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000696 if (SS && SS->isInvalid())
697 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000698
699 // C++ [temp.dep.expr]p3:
700 // An id-expression is type-dependent if it contains:
701 // -- a nested-name-specifier that contains a class-name that
702 // names a dependent type.
Douglas Gregor00c44862009-05-29 14:49:33 +0000703 // FIXME: Member of the current instantiation.
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000704 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000705 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
Mike Stump1eb44332009-09-09 15:08:12 +0000706 Loc, SS->getRange(),
Anders Carlsson9b31df42009-07-09 00:05:08 +0000707 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
708 isAddressOfOperand));
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000709 }
710
John McCallf36e02d2009-10-09 21:13:30 +0000711 LookupResult Lookup;
712 LookupParsedName(Lookup, S, SS, Name, LookupOrdinaryName, false, true, Loc);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000713
Sebastian Redlcd965b92009-01-18 18:53:16 +0000714 if (Lookup.isAmbiguous()) {
715 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
716 SS && SS->isSet() ? SS->getRange()
717 : SourceRange());
718 return ExprError();
Chris Lattner5cb10d32009-04-24 22:30:50 +0000719 }
Mike Stump1eb44332009-09-09 15:08:12 +0000720
John McCallf36e02d2009-10-09 21:13:30 +0000721 NamedDecl *D = Lookup.getAsSingleDecl(Context);
Douglas Gregor5c37de72008-12-06 00:22:45 +0000722
Chris Lattner8a934232008-03-31 00:36:02 +0000723 // If this reference is in an Objective-C method, then ivar lookup happens as
724 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000725 IdentifierInfo *II = Name.getAsIdentifierInfo();
726 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000727 // There are two cases to handle here. 1) scoped lookup could have failed,
728 // in which case we should look for an ivar. 2) scoped lookup could have
Mike Stump1eb44332009-09-09 15:08:12 +0000729 // found a decl, but that decl is outside the current instance method (i.e.
730 // a global variable). In these two cases, we do a lookup for an ivar with
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000731 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000732 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000733 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000734 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000735 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000736 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000737 if (DiagnoseUseOfDecl(IV, Loc))
738 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattner5cb10d32009-04-24 22:30:50 +0000740 // If we're referencing an invalid decl, just return this as a silent
741 // error node. The error diagnostic was already emitted on the decl.
742 if (IV->isInvalidDecl())
743 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000745 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
746 // If a class method attemps to use a free standing ivar, this is
747 // an error.
748 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
749 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
750 << IV->getDeclName());
751 // If a class method uses a global variable, even if an ivar with
752 // same name exists, use the global.
753 if (!IsClsMethod) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000754 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
755 ClassDeclared != IFace)
756 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stump390b4cc2009-05-16 07:39:55 +0000757 // FIXME: This should use a new expr for a direct reference, don't
758 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000759 IdentifierInfo &II = Context.Idents.get("self");
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000760 UnqualifiedId SelfName;
761 SelfName.setIdentifier(&II, SourceLocation());
762 CXXScopeSpec SelfScopeSpec;
763 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
764 SelfName, false, false);
Douglas Gregore0762c92009-06-19 23:52:42 +0000765 MarkDeclarationReferenced(Loc, IV);
Mike Stump1eb44332009-09-09 15:08:12 +0000766 return Owned(new (Context)
767 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlssone9146f22009-05-01 19:49:17 +0000768 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000769 }
Chris Lattner8a934232008-03-31 00:36:02 +0000770 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000771 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000772 // We should warn if a local variable hides an ivar.
773 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000774 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000775 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000776 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
777 IFace == ClassDeclared)
Chris Lattner5cb10d32009-04-24 22:30:50 +0000778 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000779 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000780 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000781 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000782 if (D == 0 && II->isStr("super")) {
Steve Naroffdd53eb52009-03-05 20:12:00 +0000783 QualType T;
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Steve Naroffdd53eb52009-03-05 20:12:00 +0000785 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff14108da2009-07-10 23:34:53 +0000786 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
787 getCurMethodDecl()->getClassInterface()));
Steve Naroffdd53eb52009-03-05 20:12:00 +0000788 else
789 T = Context.getObjCClassType();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000790 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000791 }
Chris Lattner8a934232008-03-31 00:36:02 +0000792 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000793
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000794 // Determine whether this name might be a candidate for
795 // argument-dependent lookup.
Mike Stump1eb44332009-09-09 15:08:12 +0000796 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000797 HasTrailingLParen;
798
799 if (ADL && D == 0) {
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000800 // We've seen something of the form
801 //
802 // identifier(
803 //
804 // and we did not find any entity by the name
805 // "identifier". However, this identifier is still subject to
806 // argument-dependent lookup, so keep track of the name.
807 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
808 Context.OverloadTy,
809 Loc));
810 }
811
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 if (D == 0) {
813 // Otherwise, this could be an implicitly declared function reference (legal
814 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000815 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000816 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000817 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 else {
819 // If this name wasn't predeclared and if this is not a function call,
820 // diagnose the problem.
Douglas Gregor3f093272009-10-13 21:16:44 +0000821 if (SS && !SS->isEmpty())
822 return ExprError(Diag(Loc, diag::err_no_member)
823 << Name << computeDeclContext(*SS, false)
824 << SS->getRange());
825 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000826 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000827 return ExprError(Diag(Loc, diag::err_undeclared_use)
828 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000829 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000830 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 }
832 }
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Douglas Gregor751f9a42009-06-30 15:47:41 +0000834 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
835 // Warn about constructs like:
836 // if (void *X = foo()) { ... } else { X }.
837 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Douglas Gregor751f9a42009-06-30 15:47:41 +0000839 // FIXME: In a template instantiation, we don't have scope
840 // information to check this property.
841 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
842 Scope *CheckS = S;
843 while (CheckS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000844 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000845 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
846 if (Var->getType()->isBooleanType())
847 ExprError(Diag(Loc, diag::warn_value_always_false)
848 << Var->getDeclName());
849 else
850 ExprError(Diag(Loc, diag::warn_value_always_zero)
851 << Var->getDeclName());
852 break;
853 }
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Douglas Gregor751f9a42009-06-30 15:47:41 +0000855 // Move up one more control parent to check again.
856 CheckS = CheckS->getControlParent();
857 if (CheckS)
858 CheckS = CheckS->getParent();
859 }
860 }
861 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
862 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
863 // C99 DR 316 says that, if a function type comes from a
864 // function definition (without a prototype), that type is only
865 // used for checking compatibility. Therefore, when referencing
866 // the function, we pretend that we don't have the full function
867 // type.
868 if (DiagnoseUseOfDecl(Func, Loc))
869 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000870
Douglas Gregor751f9a42009-06-30 15:47:41 +0000871 QualType T = Func->getType();
872 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +0000873 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +0000874 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
875 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
876 }
877 }
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Douglas Gregor751f9a42009-06-30 15:47:41 +0000879 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
880}
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000881/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000882bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000883Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
884 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +0000885 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000886 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000887 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000888 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000889 if (DestType->isDependentType() || From->getType()->isDependentType())
890 return false;
891 QualType FromRecordType = From->getType();
892 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +0000893 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000894 DestType = Context.getPointerType(DestType);
895 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000896 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000897 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
898 CheckDerivedToBaseConversion(FromRecordType,
899 DestRecordType,
900 From->getSourceRange().getBegin(),
901 From->getSourceRange()))
902 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +0000903 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
904 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000905 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000906 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000907}
Douglas Gregor751f9a42009-06-30 15:47:41 +0000908
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000909/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +0000910static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
911 const CXXScopeSpec *SS, NamedDecl *Member,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000912 SourceLocation Loc, QualType Ty) {
913 if (SS && SS->isSet())
Mike Stump1eb44332009-09-09 15:08:12 +0000914 return MemberExpr::Create(C, Base, isArrow,
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000915 (NestedNameSpecifier *)SS->getScopeRep(),
Mike Stump1eb44332009-09-09 15:08:12 +0000916 SS->getRange(), Member, Loc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +0000917 // FIXME: Explicit template argument lists
918 false, SourceLocation(), 0, 0, SourceLocation(),
919 Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000921 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
922}
923
Douglas Gregor751f9a42009-06-30 15:47:41 +0000924/// \brief Complete semantic analysis for a reference to the given declaration.
925Sema::OwningExprResult
926Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
927 bool HasTrailingLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000928 const CXXScopeSpec *SS,
Douglas Gregor751f9a42009-06-30 15:47:41 +0000929 bool isAddressOfOperand) {
930 assert(D && "Cannot refer to a NULL declaration");
931 DeclarationName Name = D->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Sebastian Redlebc07d52009-02-03 20:19:35 +0000933 // If this is an expression of the form &Class::member, don't build an
934 // implicit member ref, because we want a pointer to the member in general,
935 // not any specific instance's member.
936 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000937 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000938 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000939 QualType DType;
940 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
941 DType = FD->getType().getNonReferenceType();
942 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
943 DType = Method->getType();
944 } else if (isa<OverloadedFunctionDecl>(D)) {
945 DType = Context.OverloadTy;
946 }
947 // Could be an inner type. That's diagnosed below, so ignore it here.
948 if (!DType.isNull()) {
949 // The pointer is type- and value-dependent if it points into something
950 // dependent.
Douglas Gregor00c44862009-05-29 14:49:33 +0000951 bool Dependent = DC->isDependentContext();
Anders Carlssone41590d2009-06-24 00:10:43 +0000952 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redlebc07d52009-02-03 20:19:35 +0000953 }
954 }
955 }
956
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000957 // We may have found a field within an anonymous union or struct
958 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +0000959 // FIXME: This needs to happen post-isImplicitMemberReference?
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000960 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
961 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
962 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000963
Douglas Gregore961afb2009-10-22 07:08:30 +0000964 // Cope with an implicit member access in a C++ non-static member function.
965 QualType ThisType, MemberType;
966 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
967 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
968 MarkDeclarationReferenced(Loc, D);
969 if (PerformObjectMemberConversion(This, D))
970 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +0000971
Douglas Gregore961afb2009-10-22 07:08:30 +0000972 bool ShouldCheckUse = true;
973 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
974 // Don't diagnose the use of a virtual member function unless it's
975 // explicitly qualified.
976 if (MD->isVirtual() && (!SS || !SS->isSet()))
977 ShouldCheckUse = false;
Douglas Gregor88a35142008-12-22 05:46:06 +0000978 }
Douglas Gregore961afb2009-10-22 07:08:30 +0000979
980 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
981 return ExprError();
982 return Owned(BuildMemberExpr(Context, This, true, SS, D,
983 Loc, MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000984 }
985
Douglas Gregor44b43212008-12-11 16:49:14 +0000986 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000987 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
988 if (MD->isStatic())
989 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000990 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
991 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000992 }
993
Douglas Gregor88a35142008-12-22 05:46:06 +0000994 // Any other ways we could have found the field in a well-formed
995 // program would have been turned into implicit member expressions
996 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000997 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
998 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000999 }
Douglas Gregor88a35142008-12-22 05:46:06 +00001000
Reid Spencer5f016e22007-07-11 17:01:13 +00001001 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001002 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001003 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001004 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001005 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001006 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00001007
Steve Naroffdd972f22008-09-05 22:11:13 +00001008 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001009 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +00001010 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1011 false, false, SS);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001012 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +00001013 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1014 false, false, SS);
Anders Carlsson598da5b2009-08-29 01:06:32 +00001015 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
Mike Stump1eb44332009-09-09 15:08:12 +00001016 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1017 /*TypeDependent=*/true,
Anders Carlsson598da5b2009-08-29 01:06:32 +00001018 /*ValueDependent=*/true, SS);
1019
Steve Naroffdd972f22008-09-05 22:11:13 +00001020 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001021
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001022 // Check whether this declaration can be used. Note that we suppress
1023 // this check when we're going to perform argument-dependent lookup
1024 // on this function name, because this might not be the function
1025 // that overload resolution actually selects.
Mike Stump1eb44332009-09-09 15:08:12 +00001026 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001027 HasTrailingLParen;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001028 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1029 return ExprError();
1030
Steve Naroffdd972f22008-09-05 22:11:13 +00001031 // Only create DeclRefExpr's for valid Decl's.
1032 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001033 return ExprError();
1034
Chris Lattner639e2d32008-10-20 05:16:36 +00001035 // If the identifier reference is inside a block, and it refers to a value
1036 // that is outside the block, create a BlockDeclRefExpr instead of a
1037 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1038 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001039 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001040 // We do not do this for things like enum constants, global variables, etc,
1041 // as they do not get snapshotted.
1042 //
1043 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001044 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001045 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001046 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001047 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001048 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001049 // This is to record that a 'const' was actually synthesize and added.
1050 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001051 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Eli Friedman5fdeae12009-03-22 23:00:19 +00001053 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001054 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001055 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001056 }
1057 // If this reference is not in a block or if the referenced variable is
1058 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001059
Douglas Gregor898574e2008-12-05 23:32:09 +00001060 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +00001061 bool ValueDependent = false;
1062 if (getLangOptions().CPlusPlus) {
1063 // C++ [temp.dep.expr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001064 // An id-expression is type-dependent if it contains:
Douglas Gregor83f96f62008-12-10 20:57:37 +00001065 // - an identifier that was declared with a dependent type,
1066 if (VD->getType()->isDependentType())
1067 TypeDependent = true;
1068 // - FIXME: a template-id that is dependent,
1069 // - a conversion-function-id that specifies a dependent type,
1070 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1071 Name.getCXXNameType()->isDependentType())
1072 TypeDependent = true;
1073 // - a nested-name-specifier that contains a class-name that
1074 // names a dependent type.
1075 else if (SS && !SS->isEmpty()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001076 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor83f96f62008-12-10 20:57:37 +00001077 DC; DC = DC->getParent()) {
1078 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001079 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001080 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1081 if (Context.getTypeDeclType(Record)->isDependentType()) {
1082 TypeDependent = true;
1083 break;
1084 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001085 }
1086 }
1087 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001088
Douglas Gregor83f96f62008-12-10 20:57:37 +00001089 // C++ [temp.dep.constexpr]p2:
1090 //
1091 // An identifier is value-dependent if it is:
1092 // - a name declared with a dependent type,
1093 if (TypeDependent)
1094 ValueDependent = true;
1095 // - the name of a non-type template parameter,
1096 else if (isa<NonTypeTemplateParmDecl>(VD))
1097 ValueDependent = true;
1098 // - a constant with integral or enumeration type and is
1099 // initialized with an expression that is value-dependent
Eli Friedmanc1494122009-06-11 01:11:20 +00001100 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
Mike Stumpfbf68702009-11-03 22:20:01 +00001101 if (Context.getCanonicalType(Dcl->getType()).getCVRQualifiers()
1102 == Qualifiers::Const &&
Eli Friedmanc1494122009-06-11 01:11:20 +00001103 Dcl->getInit()) {
1104 ValueDependent = Dcl->getInit()->isValueDependent();
1105 }
1106 }
Douglas Gregor83f96f62008-12-10 20:57:37 +00001107 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001108
Anders Carlssone41590d2009-06-24 00:10:43 +00001109 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1110 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001111}
1112
Sebastian Redlcd965b92009-01-18 18:53:16 +00001113Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1114 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001115 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001116
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001118 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001119 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1120 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1121 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001123
Chris Lattnerfa28b302008-01-12 08:14:25 +00001124 // Pre-defined identifiers are of type char[x], where x is the length of the
1125 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Anders Carlsson3a082d82009-09-08 18:24:21 +00001127 Decl *currentDecl = getCurFunctionOrMethodDecl();
1128 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001129 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001130 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001131 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001132
Anders Carlsson773f3972009-09-11 01:22:35 +00001133 QualType ResTy;
1134 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1135 ResTy = Context.DependentTy;
1136 } else {
1137 unsigned Length =
1138 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001139
Anders Carlsson773f3972009-09-11 01:22:35 +00001140 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001141 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001142 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1143 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001144 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001145}
1146
Sebastian Redlcd965b92009-01-18 18:53:16 +00001147Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 llvm::SmallString<16> CharBuffer;
1149 CharBuffer.resize(Tok.getLength());
1150 const char *ThisTokBegin = &CharBuffer[0];
1151 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001152
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1154 Tok.getLocation(), PP);
1155 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001156 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001157
1158 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1159
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001160 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1161 Literal.isWide(),
1162 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001163}
1164
Sebastian Redlcd965b92009-01-18 18:53:16 +00001165Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1166 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1168 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001169 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001170 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001171 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001172 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001173 }
Ted Kremenek28396602009-01-13 23:19:12 +00001174
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001176 // Add padding so that NumericLiteralParser can overread by one character.
1177 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001179
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 // Get the spelling of the token, which eliminates trigraphs, etc.
1181 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001182
Mike Stump1eb44332009-09-09 15:08:12 +00001183 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 Tok.getLocation(), PP);
1185 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001186 return ExprError();
1187
Chris Lattner5d661452007-08-26 03:42:43 +00001188 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001189
Chris Lattner5d661452007-08-26 03:42:43 +00001190 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001191 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001192 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001193 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001194 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001195 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001196 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001197 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001198
1199 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1200
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001201 // isExact will be set by GetFloatValue().
1202 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001203 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1204 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001205
Chris Lattner5d661452007-08-26 03:42:43 +00001206 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001207 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001208 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001209 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001210
Neil Boothb9449512007-08-29 22:00:19 +00001211 // long long is a C99 feature.
1212 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001213 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001214 Diag(Tok.getLocation(), diag::ext_longlong);
1215
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001217 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 if (Literal.GetIntegerValue(ResultVal)) {
1220 // If this value didn't fit into uintmax_t, warn and force to ull.
1221 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001222 Ty = Context.UnsignedLongLongTy;
1223 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001224 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 } else {
1226 // If this value fits into a ULL, try to figure out what else it fits into
1227 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001228
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1230 // be an unsigned int.
1231 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1232
1233 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001234 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001235 if (!Literal.isLong && !Literal.isLongLong) {
1236 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001237 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001238
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 // Does it fit in a unsigned int?
1240 if (ResultVal.isIntN(IntSize)) {
1241 // Does it fit in a signed int?
1242 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001243 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001245 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001246 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001249
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001251 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001252 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001253
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 // Does it fit in a unsigned long?
1255 if (ResultVal.isIntN(LongSize)) {
1256 // Does it fit in a signed long?
1257 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001258 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001260 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001261 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001263 }
1264
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001266 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001267 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001268
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 // Does it fit in a unsigned long long?
1270 if (ResultVal.isIntN(LongLongSize)) {
1271 // Does it fit in a signed long long?
1272 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001273 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001275 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001276 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 }
1278 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001279
Reid Spencer5f016e22007-07-11 17:01:13 +00001280 // If we still couldn't decide a type, we probably have something that
1281 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001282 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001284 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001285 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001287
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001288 if (ResultVal.getBitWidth() != Width)
1289 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001291 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001293
Chris Lattner5d661452007-08-26 03:42:43 +00001294 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1295 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001296 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001297 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001298
1299 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001300}
1301
Sebastian Redlcd965b92009-01-18 18:53:16 +00001302Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1303 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001304 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001305 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001306 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001307}
1308
1309/// The UsualUnaryConversions() function is *not* called by this routine.
1310/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001311bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001312 SourceLocation OpLoc,
1313 const SourceRange &ExprRange,
1314 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001315 if (exprType->isDependentType())
1316 return false;
1317
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001319 if (isa<FunctionType>(exprType)) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001320 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001321 if (isSizeof)
1322 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1323 return false;
1324 }
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Chris Lattner1efaa952009-04-24 00:30:45 +00001326 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001327 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001328 Diag(OpLoc, diag::ext_sizeof_void_type)
1329 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001330 return false;
1331 }
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Chris Lattner1efaa952009-04-24 00:30:45 +00001333 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001334 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001335 PDiag(diag::err_alignof_incomplete_type)
1336 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001337 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Chris Lattner1efaa952009-04-24 00:30:45 +00001339 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001340 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001341 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001342 << exprType << isSizeof << ExprRange;
1343 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001344 }
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Chris Lattner1efaa952009-04-24 00:30:45 +00001346 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001347}
1348
Chris Lattner31e21e02009-01-24 20:17:12 +00001349bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1350 const SourceRange &ExprRange) {
1351 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001352
Mike Stump1eb44332009-09-09 15:08:12 +00001353 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001354 if (isa<DeclRefExpr>(E))
1355 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001356
1357 // Cannot know anything else if the expression is dependent.
1358 if (E->isTypeDependent())
1359 return false;
1360
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001361 if (E->getBitField()) {
1362 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1363 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001364 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001365
1366 // Alignment of a field access is always okay, so long as it isn't a
1367 // bit-field.
1368 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001369 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001370 return false;
1371
Chris Lattner31e21e02009-01-24 20:17:12 +00001372 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1373}
1374
Douglas Gregorba498172009-03-13 21:01:28 +00001375/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001376Action::OwningExprResult
1377Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001378 bool isSizeOf, SourceRange R) {
1379 if (T.isNull())
1380 return ExprError();
1381
1382 if (!T->isDependentType() &&
1383 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1384 return ExprError();
1385
1386 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1387 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1388 Context.getSizeType(), OpLoc,
1389 R.getEnd()));
1390}
1391
1392/// \brief Build a sizeof or alignof expression given an expression
1393/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001394Action::OwningExprResult
1395Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001396 bool isSizeOf, SourceRange R) {
1397 // Verify that the operand is valid.
1398 bool isInvalid = false;
1399 if (E->isTypeDependent()) {
1400 // Delay type-checking for type-dependent expressions.
1401 } else if (!isSizeOf) {
1402 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001403 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001404 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1405 isInvalid = true;
1406 } else {
1407 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1408 }
1409
1410 if (isInvalid)
1411 return ExprError();
1412
1413 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1414 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1415 Context.getSizeType(), OpLoc,
1416 R.getEnd()));
1417}
1418
Sebastian Redl05189992008-11-11 17:56:53 +00001419/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1420/// the same for @c alignof and @c __alignof
1421/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001422Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001423Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1424 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001426 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001427
Sebastian Redl05189992008-11-11 17:56:53 +00001428 if (isType) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001429 // FIXME: Preserve type source info.
1430 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregorba498172009-03-13 21:01:28 +00001431 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001432 }
Sebastian Redl05189992008-11-11 17:56:53 +00001433
Douglas Gregorba498172009-03-13 21:01:28 +00001434 // Get the end location.
1435 Expr *ArgEx = (Expr *)TyOrEx;
1436 Action::OwningExprResult Result
1437 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1438
1439 if (Result.isInvalid())
1440 DeleteExpr(ArgEx);
1441
1442 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001443}
1444
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001445QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001446 if (V->isTypeDependent())
1447 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Chris Lattnercc26ed72007-08-26 05:39:26 +00001449 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001450 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001451 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Chris Lattnercc26ed72007-08-26 05:39:26 +00001453 // Otherwise they pass through real integer and floating point types here.
1454 if (V->getType()->isArithmeticType())
1455 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Chris Lattnercc26ed72007-08-26 05:39:26 +00001457 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001458 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1459 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001460 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001461}
1462
1463
Reid Spencer5f016e22007-07-11 17:01:13 +00001464
Sebastian Redl0eb23302009-01-19 00:08:26 +00001465Action::OwningExprResult
1466Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1467 tok::TokenKind Kind, ExprArg Input) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001468 // Since this might be a postfix expression, get rid of ParenListExprs.
1469 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001470 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001471
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 UnaryOperator::Opcode Opc;
1473 switch (Kind) {
1474 default: assert(0 && "Unknown unary op!");
1475 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1476 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1477 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001478
Douglas Gregor74253732008-11-19 15:42:04 +00001479 if (getLangOptions().CPlusPlus &&
1480 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1481 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001482 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001483 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1484
1485 // C++ [over.inc]p1:
1486 //
1487 // [...] If the function is a member function with one
1488 // parameter (which shall be of type int) or a non-member
1489 // function with two parameters (the second of which shall be
1490 // of type int), it defines the postfix increment operator ++
1491 // for objects of that type. When the postfix increment is
1492 // called as a result of using the ++ operator, the int
1493 // argument will have value zero.
Mike Stump1eb44332009-09-09 15:08:12 +00001494 Expr *Args[2] = {
1495 Arg,
1496 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001497 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001498 };
1499
1500 // Build the candidate set for overloading
1501 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00001502 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor74253732008-11-19 15:42:04 +00001503
1504 // Perform overload resolution.
1505 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001506 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor74253732008-11-19 15:42:04 +00001507 case OR_Success: {
1508 // We found a built-in operator or an overloaded operator.
1509 FunctionDecl *FnDecl = Best->Function;
1510
1511 if (FnDecl) {
1512 // We matched an overloaded operator. Build a call to that
1513 // operator.
1514
1515 // Convert the arguments.
1516 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1517 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001518 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001519 } else {
1520 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001521 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001522 FnDecl->getParamDecl(0)->getType(),
1523 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001524 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001525 }
1526
1527 // Determine the result type
Anders Carlsson07d68f12009-10-13 21:49:31 +00001528 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001529
Douglas Gregor74253732008-11-19 15:42:04 +00001530 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001531 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump488e25b2009-02-19 02:54:59 +00001532 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00001533 UsualUnaryConversions(FnExpr);
1534
Sebastian Redl0eb23302009-01-19 00:08:26 +00001535 Input.release();
Douglas Gregor7ff69262009-05-27 05:00:47 +00001536 Args[0] = Arg;
Anders Carlsson07d68f12009-10-13 21:49:31 +00001537
1538 ExprOwningPtr<CXXOperatorCallExpr>
1539 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OverOp,
1540 FnExpr, Args, 2,
1541 ResultTy, OpLoc));
1542
1543 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
1544 FnDecl))
1545 return ExprError();
Anders Carlsson3a9439f2009-10-13 22:22:09 +00001546 return Owned(TheCall.release());
1547
Douglas Gregor74253732008-11-19 15:42:04 +00001548 } else {
1549 // We matched a built-in operator. Convert the arguments, then
1550 // break out so that we will build the appropriate built-in
1551 // operator node.
1552 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1553 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001554 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001555
1556 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001557 }
Douglas Gregor74253732008-11-19 15:42:04 +00001558 }
1559
Douglas Gregor33074752009-09-30 21:46:01 +00001560 case OR_No_Viable_Function: {
1561 // No viable function; try checking this as a built-in operator, which
1562 // will fail and provide a diagnostic. Then, print the overload
1563 // candidates.
1564 OwningExprResult Result = CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1565 assert(Result.isInvalid() &&
1566 "C++ postfix-unary operator overloading is missing candidates!");
1567 if (Result.isInvalid())
1568 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1569
1570 return move(Result);
1571 }
1572
Douglas Gregor74253732008-11-19 15:42:04 +00001573 case OR_Ambiguous:
1574 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1575 << UnaryOperator::getOpcodeStr(Opc)
1576 << Arg->getSourceRange();
1577 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001578 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001579
1580 case OR_Deleted:
1581 Diag(OpLoc, diag::err_ovl_deleted_oper)
1582 << Best->Function->isDeleted()
1583 << UnaryOperator::getOpcodeStr(Opc)
1584 << Arg->getSourceRange();
1585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1586 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001587 }
1588
1589 // Either we found no viable overloaded operator or we matched a
1590 // built-in operator. In either case, fall through to trying to
1591 // build a built-in operation.
1592 }
1593
Eli Friedman6016cb22009-07-22 23:24:42 +00001594 Input.release();
1595 Input = Arg;
Eli Friedmande99a452009-07-22 22:25:00 +00001596 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001597}
1598
Sebastian Redl0eb23302009-01-19 00:08:26 +00001599Action::OwningExprResult
1600Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1601 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001602 // Since this might be a postfix expression, get rid of ParenListExprs.
1603 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1604
Sebastian Redl0eb23302009-01-19 00:08:26 +00001605 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1606 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Douglas Gregor337c6b92008-11-19 17:17:41 +00001608 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001609 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1610 Base.release();
1611 Idx.release();
1612 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1613 Context.DependentTy, RLoc));
1614 }
1615
Mike Stump1eb44332009-09-09 15:08:12 +00001616 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001617 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001618 LHSExp->getType()->isEnumeralType() ||
1619 RHSExp->getType()->isRecordType() ||
1620 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001621 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001622 }
1623
Sebastian Redlf322ed62009-10-29 20:17:01 +00001624 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1625}
1626
1627
1628Action::OwningExprResult
1629Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1630 ExprArg Idx, SourceLocation RLoc) {
1631 Expr *LHSExp = static_cast<Expr*>(Base.get());
1632 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1633
Chris Lattner12d9ff62007-07-16 00:14:47 +00001634 // Perform default conversions.
1635 DefaultFunctionArrayConversion(LHSExp);
1636 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001637
Chris Lattner12d9ff62007-07-16 00:14:47 +00001638 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001639
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001641 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001642 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001644 Expr *BaseExpr, *IndexExpr;
1645 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001646 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1647 BaseExpr = LHSExp;
1648 IndexExpr = RHSExp;
1649 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001650 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001651 BaseExpr = LHSExp;
1652 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001653 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001654 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001655 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001656 BaseExpr = RHSExp;
1657 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001658 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001659 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001660 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001661 BaseExpr = LHSExp;
1662 IndexExpr = RHSExp;
1663 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001664 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001665 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001666 // Handle the uncommon case of "123[Ptr]".
1667 BaseExpr = RHSExp;
1668 IndexExpr = LHSExp;
1669 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001670 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001671 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001672 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001673
Chris Lattner12d9ff62007-07-16 00:14:47 +00001674 // FIXME: need to deal with const...
1675 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001676 } else if (LHSTy->isArrayType()) {
1677 // If we see an array that wasn't promoted by
1678 // DefaultFunctionArrayConversion, it must be an array that
1679 // wasn't promoted because of the C90 rule that doesn't
1680 // allow promoting non-lvalue arrays. Warn, then
1681 // force the promotion here.
1682 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1683 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001684 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1685 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001686 LHSTy = LHSExp->getType();
1687
1688 BaseExpr = LHSExp;
1689 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001690 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001691 } else if (RHSTy->isArrayType()) {
1692 // Same as previous, except for 123[f().a] case
1693 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1694 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001695 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1696 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001697 RHSTy = RHSExp->getType();
1698
1699 BaseExpr = RHSExp;
1700 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001701 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001703 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1704 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001705 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001707 if (!(IndexExpr->getType()->isIntegerType() &&
1708 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001709 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1710 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001711
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001712 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001713 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1714 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001715 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1716
Douglas Gregore7450f52009-03-24 19:52:54 +00001717 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001718 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1719 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001720 // incomplete types are not object types.
1721 if (ResultType->isFunctionType()) {
1722 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1723 << ResultType << BaseExpr->getSourceRange();
1724 return ExprError();
1725 }
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Douglas Gregore7450f52009-03-24 19:52:54 +00001727 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001728 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001729 PDiag(diag::err_subscript_incomplete_type)
1730 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001731 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Chris Lattner1efaa952009-04-24 00:30:45 +00001733 // Diagnose bad cases where we step over interface counts.
1734 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1735 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1736 << ResultType << BaseExpr->getSourceRange();
1737 return ExprError();
1738 }
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Sebastian Redl0eb23302009-01-19 00:08:26 +00001740 Base.release();
1741 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001742 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001743 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001744}
1745
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001746QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001747CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001748 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001749 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001750 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1751 // see FIXME there.
1752 //
1753 // FIXME: This logic can be greatly simplified by splitting it along
1754 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001755 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001756
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001757 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001758 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001759
Mike Stumpeed9cac2009-02-19 03:04:26 +00001760 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001761 // special names that indicate a subset of exactly half the elements are
1762 // to be selected.
1763 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001764
Nate Begeman353417a2009-01-18 01:47:54 +00001765 // This flag determines whether or not CompName has an 's' char prefix,
1766 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001767 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001768
1769 // Check that we've found one of the special components, or that the component
1770 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001771 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001772 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1773 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001774 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001775 do
1776 compStr++;
1777 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001778 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001779 do
1780 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001781 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001782 }
Nate Begeman353417a2009-01-18 01:47:54 +00001783
Mike Stumpeed9cac2009-02-19 03:04:26 +00001784 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001785 // We didn't get to the end of the string. This means the component names
1786 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001787 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1788 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001789 return QualType();
1790 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001791
Nate Begeman353417a2009-01-18 01:47:54 +00001792 // Ensure no component accessor exceeds the width of the vector type it
1793 // operates on.
1794 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00001795 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001796
1797 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001798 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001799
1800 while (*compStr) {
1801 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1802 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1803 << baseType << SourceRange(CompLoc);
1804 return QualType();
1805 }
1806 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001807 }
Nate Begeman8a997642008-05-09 06:41:27 +00001808
Nate Begeman353417a2009-01-18 01:47:54 +00001809 // If this is a halving swizzle, verify that the base type has an even
1810 // number of elements.
1811 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001812 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001813 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001814 return QualType();
1815 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001816
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001817 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001818 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001819 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001820 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001821 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001822 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00001823 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00001824 if (HexSwizzle)
1825 CompSize--;
1826
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001827 if (CompSize == 1)
1828 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001829
Nate Begeman213541a2008-04-18 23:10:10 +00001830 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001831 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001832 // diagostics look bad. We want extended vector types to appear built-in.
1833 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1834 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1835 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001836 }
1837 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001838}
1839
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001840static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001841 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001842 const Selector &Sel,
1843 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Anders Carlsson8f28f992009-08-26 18:25:21 +00001845 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001846 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001847 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001848 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001850 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1851 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001852 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001853 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001854 return D;
1855 }
1856 return 0;
1857}
1858
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001859static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001860 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001861 const Selector &Sel,
1862 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001863 // Check protocols on qualified interfaces.
1864 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001865 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001866 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001867 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001868 GDecl = PD;
1869 break;
1870 }
1871 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001872 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001873 GDecl = OMD;
1874 break;
1875 }
1876 }
1877 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001878 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001879 E = QIdTy->qual_end(); I != E; ++I) {
1880 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001881 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001882 if (GDecl)
1883 return GDecl;
1884 }
1885 }
1886 return GDecl;
1887}
Chris Lattner76a642f2009-02-15 22:43:40 +00001888
Mike Stump1eb44332009-09-09 15:08:12 +00001889Action::OwningExprResult
Anders Carlsson8f28f992009-08-26 18:25:21 +00001890Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001891 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001892 DeclarationName MemberName,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001893 bool HasExplicitTemplateArgs,
1894 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001895 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001896 unsigned NumExplicitTemplateArgs,
1897 SourceLocation RAngleLoc,
Douglas Gregorc68afe22009-09-03 21:38:09 +00001898 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1899 NamedDecl *FirstQualifierInScope) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001900 if (SS && SS->isInvalid())
1901 return ExprError();
1902
Nate Begeman2ef13e52009-08-10 23:49:36 +00001903 // Since this might be a postfix expression, get rid of ParenListExprs.
1904 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1905
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001906 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregora71d8192009-09-04 17:36:40 +00001907 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Steve Naroff3cc4af82007-12-16 21:42:28 +00001909 // Perform default conversions.
1910 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001911
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001912 QualType BaseType = BaseExpr->getType();
David Chisnall0f436562009-08-17 16:35:33 +00001913 // If this is an Objective-C pseudo-builtin and a definition is provided then
1914 // use that.
1915 if (BaseType->isObjCIdType()) {
1916 // We have an 'id' type. Rather than fall through, we check if this
1917 // is a reference to 'isa'.
1918 if (BaseType != Context.ObjCIdRedefinitionType) {
1919 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001920 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00001921 }
David Chisnall0f436562009-08-17 16:35:33 +00001922 }
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001923 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001924
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001925 // Handle properties on ObjC 'Class' types.
1926 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1927 // Also must look for a getter name which uses property syntax.
1928 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1929 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1930 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1931 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1932 ObjCMethodDecl *Getter;
1933 // FIXME: need to also look locally in the implementation.
1934 if ((Getter = IFace->lookupClassMethod(Sel))) {
1935 // Check the use of this method.
1936 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1937 return ExprError();
1938 }
1939 // If we found a getter then this may be a valid dot-reference, we
1940 // will look for the matching setter, in case it is needed.
1941 Selector SetterSel =
1942 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1943 PP.getSelectorTable(), Member);
1944 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1945 if (!Setter) {
1946 // If this reference is in an @implementation, also check for 'private'
1947 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00001948 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001949 }
1950 // Look through local category implementations associated with the class.
1951 if (!Setter)
1952 Setter = IFace->getCategoryClassMethod(SetterSel);
1953
1954 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1955 return ExprError();
1956
1957 if (Getter || Setter) {
1958 QualType PType;
1959
1960 if (Getter)
1961 PType = Getter->getResultType();
1962 else
1963 // Get the expression type from Setter's incoming parameter.
1964 PType = (*(Setter->param_end() -1))->getType();
1965 // FIXME: we must check that the setter has property type.
1966 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
1967 PType,
1968 Setter, MemberLoc, BaseExpr));
1969 }
1970 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1971 << MemberName << BaseType);
1972 }
1973 }
1974
1975 if (BaseType->isObjCClassType() &&
1976 BaseType != Context.ObjCClassRedefinitionType) {
1977 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001978 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001979 }
1980
Chris Lattner68a057b2008-07-21 04:36:39 +00001981 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1982 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 if (OpKind == tok::arrow) {
Douglas Gregorc68afe22009-09-03 21:38:09 +00001984 if (BaseType->isDependentType()) {
1985 NestedNameSpecifier *Qualifier = 0;
1986 if (SS) {
1987 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1988 if (!FirstQualifierInScope)
1989 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
1990 }
Mike Stump1eb44332009-09-09 15:08:12 +00001991
1992 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001993 OpLoc, Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00001994 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001995 FirstQualifierInScope,
1996 MemberName,
1997 MemberLoc,
1998 HasExplicitTemplateArgs,
1999 LAngleLoc,
2000 ExplicitTemplateArgs,
2001 NumExplicitTemplateArgs,
2002 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002003 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002004 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002005 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002006 else if (BaseType->isObjCObjectPointerType())
2007 ;
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002008 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00002009 return ExprError(Diag(MemberLoc,
2010 diag::err_typecheck_member_reference_arrow)
2011 << BaseType << BaseExpr->getSourceRange());
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002012 } else if (BaseType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002013 // Require that the base type isn't a pointer type
Anders Carlsson4ef27702009-05-16 20:31:20 +00002014 // (so we'll report an error for)
2015 // T* t;
2016 // t.f;
Mike Stump1eb44332009-09-09 15:08:12 +00002017 //
Anders Carlsson4ef27702009-05-16 20:31:20 +00002018 // In Obj-C++, however, the above expression is valid, since it could be
2019 // accessing the 'f' property if T is an Obj-C interface. The extra check
2020 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenek6217b802009-07-29 21:53:49 +00002021 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002022
Mike Stump1eb44332009-09-09 15:08:12 +00002023 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorc68afe22009-09-03 21:38:09 +00002024 !PT->getPointeeType()->isRecordType())) {
2025 NestedNameSpecifier *Qualifier = 0;
2026 if (SS) {
2027 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2028 if (!FirstQualifierInScope)
2029 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2030 }
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002032 return Owned(CXXUnresolvedMemberExpr::Create(Context,
Mike Stump1eb44332009-09-09 15:08:12 +00002033 BaseExpr, false,
2034 OpLoc,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002035 Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002036 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002037 FirstQualifierInScope,
2038 MemberName,
2039 MemberLoc,
2040 HasExplicitTemplateArgs,
2041 LAngleLoc,
2042 ExplicitTemplateArgs,
2043 NumExplicitTemplateArgs,
2044 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002045 }
Anders Carlsson4ef27702009-05-16 20:31:20 +00002046 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002047
Chris Lattner68a057b2008-07-21 04:36:39 +00002048 // Handle field access to simple records. This also handles access to fields
2049 // of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002050 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002051 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00002052 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002053 PDiag(diag::err_typecheck_incomplete_tag)
2054 << BaseExpr->getSourceRange()))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002055 return ExprError();
2056
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002057 DeclContext *DC = RDecl;
2058 if (SS && SS->isSet()) {
2059 // If the member name was a qualified-id, look into the
2060 // nested-name-specifier.
2061 DC = computeDeclContext(*SS, false);
Douglas Gregor8d1c9ae2009-10-17 22:37:54 +00002062
2063 if (!isa<TypeDecl>(DC)) {
2064 Diag(MemberLoc, diag::err_qualified_member_nonclass)
2065 << DC << SS->getRange();
2066 return ExprError();
2067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068
2069 // FIXME: If DC is not computable, we should build a
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002070 // CXXUnresolvedMemberExpr.
2071 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2072 }
2073
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002074 // The record definition is complete, now make sure the member is valid.
John McCallf36e02d2009-10-09 21:13:30 +00002075 LookupResult Result;
2076 LookupQualifiedName(Result, DC, MemberName, LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00002077
John McCallf36e02d2009-10-09 21:13:30 +00002078 if (Result.empty())
Douglas Gregor3f093272009-10-13 21:16:44 +00002079 return ExprError(Diag(MemberLoc, diag::err_no_member)
2080 << MemberName << DC << BaseExpr->getSourceRange());
Chris Lattnera3d25242009-03-31 08:18:48 +00002081 if (Result.isAmbiguous()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002082 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2083 BaseExpr->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002084 return ExprError();
Chris Lattnera3d25242009-03-31 08:18:48 +00002085 }
Mike Stump1eb44332009-09-09 15:08:12 +00002086
John McCallf36e02d2009-10-09 21:13:30 +00002087 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2088
Douglas Gregora38c6872009-09-03 16:14:30 +00002089 if (SS && SS->isSet()) {
John McCallf36e02d2009-10-09 21:13:30 +00002090 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002091 QualType BaseTypeCanon
Douglas Gregora38c6872009-09-03 16:14:30 +00002092 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002093 QualType MemberTypeCanon
John McCallf36e02d2009-10-09 21:13:30 +00002094 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Douglas Gregora38c6872009-09-03 16:14:30 +00002096 if (BaseTypeCanon != MemberTypeCanon &&
2097 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2098 return ExprError(Diag(SS->getBeginLoc(),
2099 diag::err_not_direct_base_or_virtual)
2100 << MemberTypeCanon << BaseTypeCanon);
2101 }
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Chris Lattner56cd21b2009-02-13 22:08:30 +00002103 // If the decl being referenced had an error, return an error for this
2104 // sub-expr without emitting another error, in order to avoid cascading
2105 // error cases.
2106 if (MemberDecl->isInvalidDecl())
2107 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002108
Anders Carlsson0f728562009-09-10 20:48:14 +00002109 bool ShouldCheckUse = true;
2110 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2111 // Don't diagnose the use of a virtual member function unless it's
2112 // explicitly qualified.
2113 if (MD->isVirtual() && (!SS || !SS->isSet()))
2114 ShouldCheckUse = false;
2115 }
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002116
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002117 // Check the use of this field
Anders Carlsson0f728562009-09-10 20:48:14 +00002118 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002119 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00002120
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002121 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002122 // We may have found a field within an anonymous union or struct
2123 // (C++ [class.union]).
2124 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002125 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002126 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002127
Douglas Gregor86f19402008-12-20 23:49:58 +00002128 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002129 QualType MemberType = FD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002130 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor86f19402008-12-20 23:49:58 +00002131 MemberType = Ref->getPointeeType();
2132 else {
John McCall0953e762009-09-24 19:53:00 +00002133 Qualifiers BaseQuals = BaseType.getQualifiers();
2134 BaseQuals.removeObjCGCAttr();
2135 if (FD->isMutable()) BaseQuals.removeConst();
2136
2137 Qualifiers MemberQuals
2138 = Context.getCanonicalType(MemberType).getQualifiers();
2139
2140 Qualifiers Combined = BaseQuals + MemberQuals;
2141 if (Combined != MemberQuals)
2142 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor86f19402008-12-20 23:49:58 +00002143 }
Eli Friedman51019072008-02-06 22:48:16 +00002144
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002145 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002146 if (PerformObjectMemberConversion(BaseExpr, FD))
2147 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002148 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002149 FD, MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002150 }
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002152 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2153 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002154 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2155 Var, MemberLoc,
2156 Var->getType().getNonReferenceType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002157 }
2158 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2159 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002160 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2161 MemberFn, MemberLoc,
2162 MemberFn->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002163 }
Mike Stump1eb44332009-09-09 15:08:12 +00002164 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +00002165 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2166 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002168 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002169 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2170 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002171 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002172 FunTmpl, MemberLoc, true,
2173 LAngleLoc, ExplicitTemplateArgs,
2174 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002175 Context.OverloadTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002177 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2178 FunTmpl, MemberLoc,
2179 Context.OverloadTy));
Douglas Gregor6b906862009-08-21 00:16:32 +00002180 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002181 if (OverloadedFunctionDecl *Ovl
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002182 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2183 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002184 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2185 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002186 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002187 Ovl, MemberLoc, true,
2188 LAngleLoc, ExplicitTemplateArgs,
2189 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002190 Context.OverloadTy));
2191
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002192 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2193 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002194 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002195 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2196 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002197 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2198 Enum, MemberLoc, Enum->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002199 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002200 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002201 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002202 << MemberName << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002203
Douglas Gregor86f19402008-12-20 23:49:58 +00002204 // We found a declaration kind that we didn't expect. This is a
2205 // generic error message that tells the user that she can't refer
2206 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002207 return ExprError(Diag(MemberLoc,
2208 diag::err_typecheck_member_reference_unknown)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002209 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002210 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002211
Douglas Gregora71d8192009-09-04 17:36:40 +00002212 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2213 // into a record type was handled above, any destructor we see here is a
2214 // pseudo-destructor.
2215 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2216 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002217 // The left hand side of the dot operator shall be of scalar type. The
2218 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002219 // type.
2220 if (!BaseType->isScalarType())
2221 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2222 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Douglas Gregora71d8192009-09-04 17:36:40 +00002224 // [...] The type designated by the pseudo-destructor-name shall be the
2225 // same as the object type.
2226 if (!MemberName.getCXXNameType()->isDependentType() &&
2227 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2228 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2229 << BaseType << MemberName.getCXXNameType()
2230 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002231
2232 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002233 // the form
2234 //
Mike Stump1eb44332009-09-09 15:08:12 +00002235 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2236 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002237 // shall designate the same scalar type.
2238 //
2239 // FIXME: DPG can't see any way to trigger this particular clause, so it
2240 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Douglas Gregora71d8192009-09-04 17:36:40 +00002242 // FIXME: We've lost the precise spelling of the type by going through
2243 // DeclarationName. Can we do better?
2244 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002245 OpKind == tok::arrow,
Douglas Gregora71d8192009-09-04 17:36:40 +00002246 OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002247 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregora71d8192009-09-04 17:36:40 +00002248 SS? SS->getRange() : SourceRange(),
2249 MemberName.getCXXNameType(),
2250 MemberLoc));
2251 }
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Chris Lattnera38e6b12008-07-21 04:59:05 +00002253 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2254 // (*Obj).ivar.
Steve Naroff14108da2009-07-10 23:34:53 +00002255 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2256 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002257 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002258 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002259 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002260 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002261 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2262
Steve Naroffc70e8d92009-07-16 00:25:06 +00002263 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2264 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002265 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Steve Naroffc70e8d92009-07-16 00:25:06 +00002267 if (IV) {
2268 // If the decl being referenced had an error, return an error for this
2269 // sub-expr without emitting another error, in order to avoid cascading
2270 // error cases.
2271 if (IV->isInvalidDecl())
2272 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002273
Steve Naroffc70e8d92009-07-16 00:25:06 +00002274 // Check whether we can reference this field.
2275 if (DiagnoseUseOfDecl(IV, MemberLoc))
2276 return ExprError();
2277 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2278 IV->getAccessControl() != ObjCIvarDecl::Package) {
2279 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2280 if (ObjCMethodDecl *MD = getCurMethodDecl())
2281 ClassOfMethodDecl = MD->getClassInterface();
2282 else if (ObjCImpDecl && getCurFunctionDecl()) {
2283 // Case of a c-function declared inside an objc implementation.
2284 // FIXME: For a c-style function nested inside an objc implementation
2285 // class, there is no implementation context available, so we pass
2286 // down the context as argument to this routine. Ideally, this context
2287 // need be passed down in the AST node and somehow calculated from the
2288 // AST for a function decl.
2289 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002290 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002291 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2292 ClassOfMethodDecl = IMPD->getClassInterface();
2293 else if (ObjCCategoryImplDecl* CatImplClass =
2294 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2295 ClassOfMethodDecl = CatImplClass->getClassInterface();
2296 }
Mike Stump1eb44332009-09-09 15:08:12 +00002297
2298 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2299 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002300 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002301 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002302 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002303 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2304 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002305 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002306 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002307 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002308
2309 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2310 MemberLoc, BaseExpr,
2311 OpKind == tok::arrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002312 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002313 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002314 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002315 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002316 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002317 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002318 // Handle properties on 'id' and qualified "id".
Mike Stump1eb44332009-09-09 15:08:12 +00002319 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroffde2e22d2009-07-15 18:40:39 +00002320 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002321 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002322 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Steve Naroff14108da2009-07-10 23:34:53 +00002324 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002325 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002326 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2327 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2328 // Check the use of this declaration
2329 if (DiagnoseUseOfDecl(PD, MemberLoc))
2330 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Steve Naroff14108da2009-07-10 23:34:53 +00002332 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2333 MemberLoc, BaseExpr));
2334 }
2335 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2336 // Check the use of this method.
2337 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2338 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Steve Naroff14108da2009-07-10 23:34:53 +00002340 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002341 OMD->getResultType(),
2342 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002343 NULL, 0));
2344 }
2345 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002346
Steve Naroff14108da2009-07-10 23:34:53 +00002347 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002348 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002349 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002350 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2351 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002352 const ObjCObjectPointerType *OPT;
Mike Stump1eb44332009-09-09 15:08:12 +00002353 if (OpKind == tok::period &&
Steve Naroff14108da2009-07-10 23:34:53 +00002354 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2355 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2356 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002357 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Daniel Dunbar2307d312008-09-03 01:05:41 +00002359 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002360 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002361 // Check whether we can reference this property.
2362 if (DiagnoseUseOfDecl(PD, MemberLoc))
2363 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002364 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002365 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002366 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002367 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2368 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002369 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002370 MemberLoc, BaseExpr));
2371 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002372 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002373 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2374 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002375 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002376 // Check whether we can reference this property.
2377 if (DiagnoseUseOfDecl(PD, MemberLoc))
2378 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002379
Steve Naroff6ece14c2009-01-21 00:14:39 +00002380 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002381 MemberLoc, BaseExpr));
2382 }
Steve Naroff14108da2009-07-10 23:34:53 +00002383 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2384 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002385 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff14108da2009-07-10 23:34:53 +00002386 // Check whether we can reference this property.
2387 if (DiagnoseUseOfDecl(PD, MemberLoc))
2388 return ExprError();
Daniel Dunbar2307d312008-09-03 01:05:41 +00002389
Steve Naroff14108da2009-07-10 23:34:53 +00002390 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2391 MemberLoc, BaseExpr));
2392 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002393 // If that failed, look for an "implicit" property by seeing if the nullary
2394 // selector is implemented.
2395
2396 // FIXME: The logic for looking up nullary and unary selectors should be
2397 // shared with the code in ActOnInstanceMessage.
2398
Anders Carlsson8f28f992009-08-26 18:25:21 +00002399 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002400 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002401
Daniel Dunbar2307d312008-09-03 01:05:41 +00002402 // If this reference is in an @implementation, check for 'private' methods.
2403 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002404 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002405
Steve Naroff7692ed62008-10-22 19:16:27 +00002406 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002407 if (!Getter)
2408 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002409 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002410 // Check if we can reference this property.
2411 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2412 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002413 }
2414 // If we found a getter then this may be a valid dot-reference, we
2415 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002416 Selector SetterSel =
2417 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002418 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002419 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002420 if (!Setter) {
2421 // If this reference is in an @implementation, also check for 'private'
2422 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002423 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002424 }
2425 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002426 if (!Setter)
2427 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002428
Steve Naroff1ca66942009-03-11 13:48:17 +00002429 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2430 return ExprError();
2431
2432 if (Getter || Setter) {
2433 QualType PType;
2434
2435 if (Getter)
2436 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002437 else
2438 // Get the expression type from Setter's incoming parameter.
2439 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002440 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002441 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002442 Setter, MemberLoc, BaseExpr));
2443 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002444 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002445 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002446 }
Mike Stump1eb44332009-09-09 15:08:12 +00002447
Steve Narofff242b1b2009-07-24 17:54:45 +00002448 // Handle the following exceptional case (*Obj).isa.
Mike Stump1eb44332009-09-09 15:08:12 +00002449 if (OpKind == tok::period &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002450 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002451 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002452 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2453 Context.getObjCIdType()));
2454
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002455 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002456 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002457 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002458 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2459 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002460 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002461 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002462 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002463 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002464
Douglas Gregor214f31a2009-03-27 06:00:30 +00002465 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2466 << BaseType << BaseExpr->getSourceRange();
2467
2468 // If the user is trying to apply -> or . to a function or function
2469 // pointer, it's probably because they forgot parentheses to call
2470 // the function. Suggest the addition of those parentheses.
Mike Stump1eb44332009-09-09 15:08:12 +00002471 if (BaseType == Context.OverloadTy ||
Douglas Gregor214f31a2009-03-27 06:00:30 +00002472 BaseType->isFunctionType() ||
Mike Stump1eb44332009-09-09 15:08:12 +00002473 (BaseType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002474 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor214f31a2009-03-27 06:00:30 +00002475 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2476 Diag(Loc, diag::note_member_reference_needs_call)
2477 << CodeModificationHint::CreateInsertion(Loc, "()");
2478 }
2479
2480 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002481}
2482
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002483Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2484 SourceLocation OpLoc,
2485 tok::TokenKind OpKind,
2486 const CXXScopeSpec &SS,
2487 UnqualifiedId &Member,
2488 DeclPtrTy ObjCImpDecl,
2489 bool HasTrailingLParen) {
2490 if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2491 TemplateName Template
2492 = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2493
2494 // FIXME: We're going to end up looking up the template based on its name,
2495 // twice!
2496 DeclarationName Name;
2497 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2498 Name = ActualTemplate->getDeclName();
2499 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2500 Name = Ovl->getDeclName();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002501 else {
2502 DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2503 if (DTN->isIdentifier())
2504 Name = DTN->getIdentifier();
2505 else
2506 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2507 }
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002508
2509 // Translate the parser's template argument list in our AST format.
2510 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2511 Member.TemplateId->getTemplateArgs(),
2512 Member.TemplateId->getTemplateArgIsType(),
2513 Member.TemplateId->NumArgs);
2514
2515 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
2516 translateTemplateArguments(TemplateArgsPtr,
2517 Member.TemplateId->getTemplateArgLocations(),
2518 TemplateArgs);
2519 TemplateArgsPtr.release();
2520
2521 // Do we have the save the actual template name? We might need it...
2522 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2523 Member.TemplateId->TemplateNameLoc,
2524 Name, true, Member.TemplateId->LAngleLoc,
2525 TemplateArgs.data(), TemplateArgs.size(),
2526 Member.TemplateId->RAngleLoc, DeclPtrTy(),
2527 &SS);
2528 }
2529
2530 // FIXME: We lose a lot of source information by mapping directly to the
2531 // DeclarationName.
2532 OwningExprResult Result
2533 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2534 Member.getSourceRange().getBegin(),
2535 GetNameFromUnqualifiedId(Member),
2536 ObjCImpDecl, &SS);
2537
2538 if (Result.isInvalid() || HasTrailingLParen ||
2539 Member.getKind() != UnqualifiedId::IK_DestructorName)
2540 return move(Result);
2541
2542 // The only way a reference to a destructor can be used is to
2543 // immediately call them. Since the next token is not a '(', produce a
2544 // diagnostic and build the call now.
2545 Expr *E = (Expr *)Result.get();
2546 SourceLocation ExpectedLParenLoc
2547 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2548 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2549 << isa<CXXPseudoDestructorExpr>(E)
2550 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2551
2552 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2553 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002554}
2555
Anders Carlsson56c5e332009-08-25 03:49:14 +00002556Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2557 FunctionDecl *FD,
2558 ParmVarDecl *Param) {
2559 if (Param->hasUnparsedDefaultArg()) {
2560 Diag (CallLoc,
2561 diag::err_use_of_default_argument_to_function_declared_later) <<
2562 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002563 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002564 diag::note_default_argument_declared_here);
2565 } else {
2566 if (Param->hasUninstantiatedDefaultArg()) {
2567 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2568
2569 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002570 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002571
Mike Stump1eb44332009-09-09 15:08:12 +00002572 InstantiatingTemplate Inst(*this, CallLoc, Param,
2573 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002574 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002575
John McCallce3ff2b2009-08-25 22:02:44 +00002576 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002577 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002578 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002579
2580 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002581 /*FIXME:EqualLoc*/
2582 UninstExpr->getSourceRange().getBegin()))
2583 return ExprError();
2584 }
Mike Stump1eb44332009-09-09 15:08:12 +00002585
Anders Carlsson56c5e332009-08-25 03:49:14 +00002586 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Anders Carlsson56c5e332009-08-25 03:49:14 +00002588 // If the default expression creates temporaries, we need to
2589 // push them to the current stack of expression temporaries so they'll
2590 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002591 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002592 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002593 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002594 "Can't destroy temporaries in a default argument expr!");
2595 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2596 ExprTemporaries.push_back(E->getTemporary(I));
2597 }
2598 }
2599
2600 // We already type-checked the argument, so we know it works.
2601 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2602}
2603
Douglas Gregor88a35142008-12-22 05:46:06 +00002604/// ConvertArgumentsForCall - Converts the arguments specified in
2605/// Args/NumArgs to the parameter types of the function FDecl with
2606/// function prototype Proto. Call is the call expression itself, and
2607/// Fn is the function expression. For a C++ member function, this
2608/// routine does not attempt to convert the object argument. Returns
2609/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002610bool
2611Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002612 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002613 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002614 Expr **Args, unsigned NumArgs,
2615 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002616 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002617 // assignment, to the types of the corresponding parameter, ...
2618 unsigned NumArgsInProto = Proto->getNumArgs();
2619 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002620 bool Invalid = false;
2621
Douglas Gregor88a35142008-12-22 05:46:06 +00002622 // If too few arguments are available (and we don't have default
2623 // arguments for the remaining parameters), don't make the call.
2624 if (NumArgs < NumArgsInProto) {
2625 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2626 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2627 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2628 // Use default arguments for missing arguments
2629 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002630 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002631 }
2632
2633 // If too many are passed and not variadic, error on the extras and drop
2634 // them.
2635 if (NumArgs > NumArgsInProto) {
2636 if (!Proto->isVariadic()) {
2637 Diag(Args[NumArgsInProto]->getLocStart(),
2638 diag::err_typecheck_call_too_many_args)
2639 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2640 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2641 Args[NumArgs-1]->getLocEnd());
2642 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002643 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002644 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002645 }
2646 NumArgsToCheck = NumArgsInProto;
2647 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002648
Douglas Gregor88a35142008-12-22 05:46:06 +00002649 // Continue to check argument types (even if we have too few/many args).
2650 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2651 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002652
Douglas Gregor88a35142008-12-22 05:46:06 +00002653 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002654 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002655 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002656
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002657 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2658 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002659 PDiag(diag::err_call_incomplete_argument)
2660 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002661 return true;
2662
Douglas Gregor61366e92008-12-24 00:01:03 +00002663 // Pass the argument.
2664 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2665 return true;
Anders Carlsson5e300d12009-06-12 16:51:40 +00002666 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00002667 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump1eb44332009-09-09 15:08:12 +00002668
2669 OwningExprResult ArgExpr =
Anders Carlsson56c5e332009-08-25 03:49:14 +00002670 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2671 FDecl, Param);
2672 if (ArgExpr.isInvalid())
2673 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Anders Carlsson56c5e332009-08-25 03:49:14 +00002675 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002676 }
Mike Stump1eb44332009-09-09 15:08:12 +00002677
Douglas Gregor88a35142008-12-22 05:46:06 +00002678 Call->setArg(i, Arg);
2679 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002680
Douglas Gregor88a35142008-12-22 05:46:06 +00002681 // If this is a variadic call, handle args passed through "...".
2682 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002683 VariadicCallType CallType = VariadicFunction;
2684 if (Fn->getType()->isBlockPointerType())
2685 CallType = VariadicBlock; // Block
2686 else if (isa<MemberExpr>(Fn))
2687 CallType = VariadicMethod;
2688
Douglas Gregor88a35142008-12-22 05:46:06 +00002689 // Promote the arguments (C99 6.5.2.2p7).
2690 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2691 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002692 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002693 Call->setArg(i, Arg);
2694 }
2695 }
2696
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002697 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002698}
2699
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002700/// \brief "Deconstruct" the function argument of a call expression to find
2701/// the underlying declaration (if any), the name of the called function,
2702/// whether argument-dependent lookup is available, whether it has explicit
2703/// template arguments, etc.
2704void Sema::DeconstructCallFunction(Expr *FnExpr,
2705 NamedDecl *&Function,
2706 DeclarationName &Name,
2707 NestedNameSpecifier *&Qualifier,
2708 SourceRange &QualifierRange,
2709 bool &ArgumentDependentLookup,
2710 bool &HasExplicitTemplateArguments,
John McCall833ca992009-10-29 08:12:44 +00002711 const TemplateArgumentLoc *&ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002712 unsigned &NumExplicitTemplateArgs) {
2713 // Set defaults for all of the output parameters.
2714 Function = 0;
2715 Name = DeclarationName();
2716 Qualifier = 0;
2717 QualifierRange = SourceRange();
2718 ArgumentDependentLookup = getLangOptions().CPlusPlus;
2719 HasExplicitTemplateArguments = false;
2720
2721 // If we're directly calling a function, get the appropriate declaration.
2722 // Also, in C++, keep track of whether we should perform argument-dependent
2723 // lookup and whether there were any explicitly-specified template arguments.
2724 while (true) {
2725 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2726 FnExpr = IcExpr->getSubExpr();
2727 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2728 // Parentheses around a function disable ADL
2729 // (C++0x [basic.lookup.argdep]p1).
2730 ArgumentDependentLookup = false;
2731 FnExpr = PExpr->getSubExpr();
2732 } else if (isa<UnaryOperator>(FnExpr) &&
2733 cast<UnaryOperator>(FnExpr)->getOpcode()
2734 == UnaryOperator::AddrOf) {
2735 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002736 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2737 Function = dyn_cast<NamedDecl>(DRExpr->getDecl());
Douglas Gregora2813ce2009-10-23 18:54:35 +00002738 if ((Qualifier = DRExpr->getQualifier())) {
2739 ArgumentDependentLookup = false;
2740 QualifierRange = DRExpr->getQualifierRange();
2741 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002742 break;
2743 } else if (UnresolvedFunctionNameExpr *DepName
2744 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2745 Name = DepName->getName();
2746 break;
2747 } else if (TemplateIdRefExpr *TemplateIdRef
2748 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2749 Function = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2750 if (!Function)
2751 Function = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2752 HasExplicitTemplateArguments = true;
2753 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2754 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2755
2756 // C++ [temp.arg.explicit]p6:
2757 // [Note: For simple function names, argument dependent lookup (3.4.2)
2758 // applies even when the function name is not visible within the
2759 // scope of the call. This is because the call still has the syntactic
2760 // form of a function call (3.4.1). But when a function template with
2761 // explicit template arguments is used, the call does not have the
2762 // correct syntactic form unless there is a function template with
2763 // that name visible at the point of the call. If no such name is
2764 // visible, the call is not syntactically well-formed and
2765 // argument-dependent lookup does not apply. If some such name is
2766 // visible, argument dependent lookup applies and additional function
2767 // templates may be found in other namespaces.
2768 //
2769 // The summary of this paragraph is that, if we get to this point and the
2770 // template-id was not a qualified name, then argument-dependent lookup
2771 // is still possible.
2772 if ((Qualifier = TemplateIdRef->getQualifier())) {
2773 ArgumentDependentLookup = false;
2774 QualifierRange = TemplateIdRef->getQualifierRange();
2775 }
2776 break;
2777 } else {
2778 // Any kind of name that does not refer to a declaration (or
2779 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2780 ArgumentDependentLookup = false;
2781 break;
2782 }
2783 }
2784}
2785
Steve Narofff69936d2007-09-16 03:34:24 +00002786/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002787/// This provides the location of the left/right parens and a list of comma
2788/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002789Action::OwningExprResult
2790Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2791 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002792 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002793 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002794
2795 // Since this might be a postfix expression, get rid of ParenListExprs.
2796 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002798 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002799 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002800 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002801 FunctionDecl *FDecl = NULL;
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002802 NamedDecl *NDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002803 DeclarationName UnqualifiedName;
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Douglas Gregor88a35142008-12-22 05:46:06 +00002805 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002806 // If this is a pseudo-destructor expression, build the call immediately.
2807 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2808 if (NumArgs > 0) {
2809 // Pseudo-destructor calls should not have any arguments.
2810 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2811 << CodeModificationHint::CreateRemoval(
2812 SourceRange(Args[0]->getLocStart(),
2813 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Douglas Gregora71d8192009-09-04 17:36:40 +00002815 for (unsigned I = 0; I != NumArgs; ++I)
2816 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Douglas Gregora71d8192009-09-04 17:36:40 +00002818 NumArgs = 0;
2819 }
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Douglas Gregora71d8192009-09-04 17:36:40 +00002821 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2822 RParenLoc));
2823 }
Mike Stump1eb44332009-09-09 15:08:12 +00002824
Douglas Gregor17330012009-02-04 15:01:18 +00002825 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002826 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002827 // FIXME: Will need to cache the results of name lookup (including ADL) in
2828 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002829 bool Dependent = false;
2830 if (Fn->isTypeDependent())
2831 Dependent = true;
2832 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2833 Dependent = true;
2834
2835 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002836 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002837 Context.DependentTy, RParenLoc));
2838
2839 // Determine whether this is a call to an object (C++ [over.call.object]).
2840 if (Fn->getType()->isRecordType())
2841 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2842 CommaLocs, RParenLoc));
2843
Douglas Gregorfa047642009-02-04 00:32:51 +00002844 // Determine whether this is a call to a member function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002845 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2846 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2847 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2848 isa<CXXMethodDecl>(MemDecl) ||
2849 (isa<FunctionTemplateDecl>(MemDecl) &&
2850 isa<CXXMethodDecl>(
2851 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002852 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2853 CommaLocs, RParenLoc));
Douglas Gregore53060f2009-06-25 22:08:12 +00002854 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002855
2856 // Determine whether this is a call to a pointer-to-member function.
2857 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2858 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2859 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002860 if (const FunctionProtoType *FPT =
2861 dyn_cast<FunctionProtoType>(BO->getType())) {
2862 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002863
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002864 ExprOwningPtr<CXXMemberCallExpr>
2865 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2866 NumArgs, ResultTy,
2867 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002868
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002869 if (CheckCallReturnType(FPT->getResultType(),
2870 BO->getRHS()->getSourceRange().getBegin(),
2871 TheCall.get(), 0))
2872 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00002873
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002874 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2875 RParenLoc))
2876 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002877
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002878 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2879 }
2880 return ExprError(Diag(Fn->getLocStart(),
2881 diag::err_typecheck_call_not_function)
2882 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002883 }
2884 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002885 }
2886
Douglas Gregorfa047642009-02-04 00:32:51 +00002887 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002888 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002889 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregorfa047642009-02-04 00:32:51 +00002890 bool ADL = true;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002891 bool HasExplicitTemplateArgs = 0;
John McCall833ca992009-10-29 08:12:44 +00002892 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002893 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002894 NestedNameSpecifier *Qualifier = 0;
2895 SourceRange QualifierRange;
2896 DeconstructCallFunction(Fn, NDecl, UnqualifiedName, Qualifier, QualifierRange,
2897 ADL,HasExplicitTemplateArgs, ExplicitTemplateArgs,
2898 NumExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002899
Douglas Gregor17330012009-02-04 15:01:18 +00002900 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregore53060f2009-06-25 22:08:12 +00002901 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002902 if (NDecl) {
2903 FDecl = dyn_cast<FunctionDecl>(NDecl);
2904 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregore53060f2009-06-25 22:08:12 +00002905 FDecl = FunctionTemplate->getTemplatedDecl();
2906 else
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002907 FDecl = dyn_cast<FunctionDecl>(NDecl);
2908 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor17330012009-02-04 15:01:18 +00002909 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002910
Mike Stump1eb44332009-09-09 15:08:12 +00002911 if (Ovl || FunctionTemplate ||
Douglas Gregore53060f2009-06-25 22:08:12 +00002912 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002913 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00002914 if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002915 ADL = false;
2916
Douglas Gregorf9201e02009-02-11 23:02:49 +00002917 // We don't perform ADL in C.
2918 if (!getLangOptions().CPlusPlus)
2919 ADL = false;
2920
Douglas Gregore53060f2009-06-25 22:08:12 +00002921 if (Ovl || FunctionTemplate || ADL) {
Mike Stump1eb44332009-09-09 15:08:12 +00002922 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002923 HasExplicitTemplateArgs,
2924 ExplicitTemplateArgs,
2925 NumExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002926 LParenLoc, Args, NumArgs, CommaLocs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002927 RParenLoc, ADL);
Douglas Gregorfa047642009-02-04 00:32:51 +00002928 if (!FDecl)
2929 return ExprError();
2930
Douglas Gregor097bfb12009-10-23 22:18:25 +00002931 Fn = FixOverloadedFunctionReference(Fn, FDecl);
Douglas Gregorfa047642009-02-04 00:32:51 +00002932 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002933 }
Chris Lattner04421082008-04-08 04:40:51 +00002934
2935 // Promote the function operand.
2936 UsualUnaryConversions(Fn);
2937
Chris Lattner925e60d2007-12-28 05:29:59 +00002938 // Make the call expr early, before semantic checks. This guarantees cleanup
2939 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002940 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2941 Args, NumArgs,
2942 Context.BoolTy,
2943 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002944
Steve Naroffdd972f22008-09-05 22:11:13 +00002945 const FunctionType *FuncT;
2946 if (!Fn->getType()->isBlockPointerType()) {
2947 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2948 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00002949 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002950 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002951 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2952 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00002953 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002954 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00002955 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00002956 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002957 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002958 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002959 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2960 << Fn->getType() << Fn->getSourceRange());
2961
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002962 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002963 if (CheckCallReturnType(FuncT->getResultType(),
2964 Fn->getSourceRange().getBegin(), TheCall.get(),
2965 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002966 return ExprError();
2967
Chris Lattner925e60d2007-12-28 05:29:59 +00002968 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002969 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002970
Douglas Gregor72564e72009-02-26 23:50:07 +00002971 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002972 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002973 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002974 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002975 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002976 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002977
Douglas Gregor74734d52009-04-02 15:37:10 +00002978 if (FDecl) {
2979 // Check if we have too few/too many template arguments, based
2980 // on our knowledge of the function definition.
2981 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002982 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002983 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00002984 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002985 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2986 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2987 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2988 }
2989 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002990 }
2991
Steve Naroffb291ab62007-08-28 23:30:39 +00002992 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002993 for (unsigned i = 0; i != NumArgs; i++) {
2994 Expr *Arg = Args[i];
2995 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002996 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2997 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002998 PDiag(diag::err_call_incomplete_argument)
2999 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003000 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003001 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003002 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003003 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003004
Douglas Gregor88a35142008-12-22 05:46:06 +00003005 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3006 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003007 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3008 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003009
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003010 // Check for sentinels
3011 if (NDecl)
3012 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Chris Lattner59907c42007-08-10 20:18:51 +00003014 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003015 if (FDecl) {
3016 if (CheckFunctionCall(FDecl, TheCall.get()))
3017 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003019 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003020 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3021 } else if (NDecl) {
3022 if (CheckBlockCall(NDecl, TheCall.get()))
3023 return ExprError();
3024 }
Chris Lattner59907c42007-08-10 20:18:51 +00003025
Anders Carlssonec74c592009-08-16 03:06:32 +00003026 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003027}
3028
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003029Action::OwningExprResult
3030Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3031 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003032 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003033 //FIXME: Preserve type source info.
3034 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003035 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003036 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003037 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003038
Eli Friedman6223c222008-05-20 05:22:08 +00003039 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003040 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003041 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3042 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003043 } else if (!literalType->isDependentType() &&
3044 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003045 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003046 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003047 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003048 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003049
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003050 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003051 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003052 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003053
Chris Lattner371f2582008-12-04 23:50:19 +00003054 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003055 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003056 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003057 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003058 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003059 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003060 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003061 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003062}
3063
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003064Action::OwningExprResult
3065Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003066 SourceLocation RBraceLoc) {
3067 unsigned NumInit = initlist.size();
3068 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003069
Steve Naroff08d92e42007-09-15 18:49:24 +00003070 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003071 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003072
Mike Stumpeed9cac2009-02-19 03:04:26 +00003073 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003074 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003075 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003076 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003077}
3078
Anders Carlsson82debc72009-10-18 18:12:03 +00003079static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3080 QualType SrcTy, QualType DestTy) {
3081 if (Context.getCanonicalType(SrcTy).getUnqualifiedType() ==
3082 Context.getCanonicalType(DestTy).getUnqualifiedType())
3083 return CastExpr::CK_NoOp;
3084
3085 if (SrcTy->hasPointerRepresentation()) {
3086 if (DestTy->hasPointerRepresentation())
3087 return CastExpr::CK_BitCast;
3088 if (DestTy->isIntegerType())
3089 return CastExpr::CK_PointerToIntegral;
3090 }
3091
3092 if (SrcTy->isIntegerType()) {
3093 if (DestTy->isIntegerType())
3094 return CastExpr::CK_IntegralCast;
3095 if (DestTy->hasPointerRepresentation())
3096 return CastExpr::CK_IntegralToPointer;
3097 if (DestTy->isRealFloatingType())
3098 return CastExpr::CK_IntegralToFloating;
3099 }
3100
3101 if (SrcTy->isRealFloatingType()) {
3102 if (DestTy->isRealFloatingType())
3103 return CastExpr::CK_FloatingCast;
3104 if (DestTy->isIntegerType())
3105 return CastExpr::CK_FloatingToIntegral;
3106 }
3107
3108 // FIXME: Assert here.
3109 // assert(false && "Unhandled cast combination!");
3110 return CastExpr::CK_Unknown;
3111}
3112
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003113/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003114bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003115 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003116 CXXMethodDecl *& ConversionDecl,
3117 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003118 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003119 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3120 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003121
Eli Friedman199ea952009-08-15 19:02:19 +00003122 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003123
3124 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3125 // type needs to be scalar.
3126 if (castType->isVoidType()) {
3127 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003128 Kind = CastExpr::CK_ToVoid;
3129 return false;
3130 }
3131
3132 if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003133 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3134 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3135 (castType->isStructureType() || castType->isUnionType())) {
3136 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003137 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003138 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3139 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003140 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003141 return false;
3142 }
3143
3144 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003145 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003146 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003147 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003148 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003149 Field != FieldEnd; ++Field) {
3150 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3151 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3152 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3153 << castExpr->getSourceRange();
3154 break;
3155 }
3156 }
3157 if (Field == FieldEnd)
3158 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3159 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003160 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003161 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003162 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003163
3164 // Reject any other conversions to non-scalar types.
3165 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3166 << castType << castExpr->getSourceRange();
3167 }
3168
3169 if (!castExpr->getType()->isScalarType() &&
3170 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003171 return Diag(castExpr->getLocStart(),
3172 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003173 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003174 }
3175
Anders Carlsson16a89042009-10-16 05:23:41 +00003176 if (castType->isExtVectorType())
3177 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3178
Anders Carlssonc3516322009-10-16 02:48:28 +00003179 if (castType->isVectorType())
3180 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3181 if (castExpr->getType()->isVectorType())
3182 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3183
3184 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003185 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003186
Anders Carlsson16a89042009-10-16 05:23:41 +00003187 if (isa<ObjCSelectorExpr>(castExpr))
3188 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3189
Anders Carlssonc3516322009-10-16 02:48:28 +00003190 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003191 QualType castExprType = castExpr->getType();
3192 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3193 return Diag(castExpr->getLocStart(),
3194 diag::err_cast_pointer_from_non_pointer_int)
3195 << castExprType << castExpr->getSourceRange();
3196 } else if (!castExpr->getType()->isArithmeticType()) {
3197 if (!castType->isIntegralType() && castType->isArithmeticType())
3198 return Diag(castExpr->getLocStart(),
3199 diag::err_cast_pointer_to_non_pointer_int)
3200 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003201 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003202
3203 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003204 return false;
3205}
3206
Anders Carlssonc3516322009-10-16 02:48:28 +00003207bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3208 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003209 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003210
Anders Carlssona64db8f2007-11-27 05:51:55 +00003211 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003212 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003213 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003214 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003215 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003216 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003217 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003218 } else
3219 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003220 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003221 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003222
Anders Carlssonc3516322009-10-16 02:48:28 +00003223 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003224 return false;
3225}
3226
Anders Carlsson16a89042009-10-16 05:23:41 +00003227bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3228 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003229 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003230
3231 QualType SrcTy = CastExpr->getType();
3232
Nate Begeman9b10da62009-06-27 22:05:55 +00003233 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3234 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003235 if (SrcTy->isVectorType()) {
3236 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3237 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3238 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003239 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003240 return false;
3241 }
3242
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003243 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003244 // conversion will take place first from scalar to elt type, and then
3245 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003246 if (SrcTy->isPointerType())
3247 return Diag(R.getBegin(),
3248 diag::err_invalid_conversion_between_vector_and_scalar)
3249 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003250
3251 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3252 ImpCastExprToType(CastExpr, DestElemTy,
3253 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003254
3255 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003256 return false;
3257}
3258
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003259Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003260Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003261 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003262 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003264 assert((Ty != 0) && (Op.get() != 0) &&
3265 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003266
Nate Begeman2ef13e52009-08-10 23:49:36 +00003267 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003268 //FIXME: Preserve type source info.
3269 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003270
Nate Begeman2ef13e52009-08-10 23:49:36 +00003271 // If the Expr being casted is a ParenListExpr, handle it specially.
3272 if (isa<ParenListExpr>(castExpr))
3273 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003274 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003275 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003276 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003277 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003278
3279 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003280 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003281 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003282
Anders Carlsson0aebc812009-09-09 21:33:21 +00003283 if (CastArg.isInvalid())
3284 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003285
Anders Carlsson0aebc812009-09-09 21:33:21 +00003286 castExpr = CastArg.takeAs<Expr>();
3287 } else {
3288 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003289 }
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003291 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003292 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003293 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003294}
3295
Nate Begeman2ef13e52009-08-10 23:49:36 +00003296/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3297/// of comma binary operators.
3298Action::OwningExprResult
3299Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3300 Expr *expr = EA.takeAs<Expr>();
3301 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3302 if (!E)
3303 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003304
Nate Begeman2ef13e52009-08-10 23:49:36 +00003305 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003306
Nate Begeman2ef13e52009-08-10 23:49:36 +00003307 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3308 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3309 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Nate Begeman2ef13e52009-08-10 23:49:36 +00003311 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3312}
3313
3314Action::OwningExprResult
3315Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3316 SourceLocation RParenLoc, ExprArg Op,
3317 QualType Ty) {
3318 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003319
3320 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003321 // then handle it as such.
3322 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3323 if (PE->getNumExprs() == 0) {
3324 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3325 return ExprError();
3326 }
3327
3328 llvm::SmallVector<Expr *, 8> initExprs;
3329 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3330 initExprs.push_back(PE->getExpr(i));
3331
3332 // FIXME: This means that pretty-printing the final AST will produce curly
3333 // braces instead of the original commas.
3334 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003335 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003336 initExprs.size(), RParenLoc);
3337 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003338 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003339 Owned(E));
3340 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003341 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003342 // sequence of BinOp comma operators.
3343 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3344 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3345 }
3346}
3347
3348Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3349 SourceLocation R,
3350 MultiExprArg Val) {
3351 unsigned nexprs = Val.size();
3352 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3353 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3354 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3355 return Owned(expr);
3356}
3357
Sebastian Redl28507842009-02-26 14:39:58 +00003358/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3359/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003360/// C99 6.5.15
3361QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3362 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003363 // C++ is sufficiently different to merit its own checker.
3364 if (getLangOptions().CPlusPlus)
3365 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3366
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003367 UsualUnaryConversions(Cond);
3368 UsualUnaryConversions(LHS);
3369 UsualUnaryConversions(RHS);
3370 QualType CondTy = Cond->getType();
3371 QualType LHSTy = LHS->getType();
3372 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003373
Reid Spencer5f016e22007-07-11 17:01:13 +00003374 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003375 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3376 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3377 << CondTy;
3378 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003379 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003380
Chris Lattner70d67a92008-01-06 22:42:25 +00003381 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003382 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3383 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003384
Chris Lattner70d67a92008-01-06 22:42:25 +00003385 // If both operands have arithmetic type, do the usual arithmetic conversions
3386 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003387 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3388 UsualArithmeticConversions(LHS, RHS);
3389 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003390 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003391
Chris Lattner70d67a92008-01-06 22:42:25 +00003392 // If both operands are the same structure or union type, the result is that
3393 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003394 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3395 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003396 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003397 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003398 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003399 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003400 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003401 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003402
Chris Lattner70d67a92008-01-06 22:42:25 +00003403 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003404 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003405 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3406 if (!LHSTy->isVoidType())
3407 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3408 << RHS->getSourceRange();
3409 if (!RHSTy->isVoidType())
3410 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3411 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003412 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3413 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003414 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003415 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003416 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3417 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003418 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003419 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003420 // promote the null to a pointer.
3421 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003422 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003423 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003424 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003425 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003426 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003427 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003428 }
David Chisnall0f436562009-08-17 16:35:33 +00003429 // Handle things like Class and struct objc_class*. Here we case the result
3430 // to the pseudo-builtin, because that will be implicitly cast back to the
3431 // redefinition type if an attempt is made to access its fields.
3432 if (LHSTy->isObjCClassType() &&
3433 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003434 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003435 return LHSTy;
3436 }
3437 if (RHSTy->isObjCClassType() &&
3438 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003439 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003440 return RHSTy;
3441 }
3442 // And the same for struct objc_object* / id
3443 if (LHSTy->isObjCIdType() &&
3444 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003445 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003446 return LHSTy;
3447 }
3448 if (RHSTy->isObjCIdType() &&
3449 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003450 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003451 return RHSTy;
3452 }
Steve Naroff7154a772009-07-01 14:36:47 +00003453 // Handle block pointer types.
3454 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3455 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3456 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3457 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003458 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3459 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003460 return destType;
3461 }
3462 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3463 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3464 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003465 }
Steve Naroff7154a772009-07-01 14:36:47 +00003466 // We have 2 block pointer types.
3467 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3468 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003469 return LHSTy;
3470 }
Steve Naroff7154a772009-07-01 14:36:47 +00003471 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003472 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3473 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003474
Steve Naroff7154a772009-07-01 14:36:47 +00003475 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3476 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003477 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3478 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3479 // In this situation, we assume void* type. No especially good
3480 // reason, but this is what gcc does, and we do have to pick
3481 // to get a consistent AST.
3482 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003483 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3484 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003485 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003486 }
Steve Naroff7154a772009-07-01 14:36:47 +00003487 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003488 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3489 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003490 return LHSTy;
3491 }
Steve Naroff7154a772009-07-01 14:36:47 +00003492 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003493 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003494
Steve Naroff7154a772009-07-01 14:36:47 +00003495 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3496 // Two identical object pointer types are always compatible.
3497 return LHSTy;
3498 }
John McCall183700f2009-09-21 23:43:11 +00003499 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3500 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003501 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Steve Naroff7154a772009-07-01 14:36:47 +00003503 // If both operands are interfaces and either operand can be
3504 // assigned to the other, use that type as the composite
3505 // type. This allows
3506 // xxx ? (A*) a : (B*) b
3507 // where B is a subclass of A.
3508 //
3509 // Additionally, as for assignment, if either type is 'id'
3510 // allow silent coercion. Finally, if the types are
3511 // incompatible then make sure to use 'id' as the composite
3512 // type so the result is acceptable for sending messages to.
3513
3514 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3515 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003516 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003517 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003518 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003519 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003520 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003521 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003522 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003523 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003524 // GCC allows qualified id and any Objective-C type to devolve to
3525 // id. Currently localizing to here until clear this should be
3526 // part of ObjCQualifiedIdTypesAreCompatible.
3527 compositeType = Context.getObjCIdType();
3528 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003529 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003530 } else if (!(compositeType =
3531 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3532 ;
3533 else {
Steve Naroff7154a772009-07-01 14:36:47 +00003534 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3535 << LHSTy << RHSTy
3536 << LHS->getSourceRange() << RHS->getSourceRange();
3537 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003538 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3539 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003540 return incompatTy;
3541 }
3542 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003543 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3544 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003545 return compositeType;
3546 }
Steve Naroffc715e782009-07-29 15:09:39 +00003547 // Check Objective-C object pointer types and 'void *'
3548 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003549 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003550 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003551 QualType destPointee
3552 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003553 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003554 // Add qualifiers if necessary.
3555 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3556 // Promote to void*.
3557 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003558 return destType;
3559 }
3560 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00003561 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003562 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003563 QualType destPointee
3564 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003565 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003566 // Add qualifiers if necessary.
3567 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3568 // Promote to void*.
3569 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003570 return destType;
3571 }
Steve Naroff7154a772009-07-01 14:36:47 +00003572 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3573 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3574 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003575 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3576 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003577
3578 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3579 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3580 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00003581 QualType destPointee
3582 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003583 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003584 // Add qualifiers if necessary.
3585 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3586 // Promote to void*.
3587 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003588 return destType;
3589 }
3590 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00003591 QualType destPointee
3592 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003593 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003594 // Add qualifiers if necessary.
3595 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3596 // Promote to void*.
3597 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003598 return destType;
3599 }
3600
3601 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3602 // Two identical pointer types are always compatible.
3603 return LHSTy;
3604 }
3605 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3606 rhptee.getUnqualifiedType())) {
3607 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3608 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3609 // In this situation, we assume void* type. No especially good
3610 // reason, but this is what gcc does, and we do have to pick
3611 // to get a consistent AST.
3612 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003613 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3614 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003615 return incompatTy;
3616 }
3617 // The pointer types are compatible.
3618 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3619 // differently qualified versions of compatible types, the result type is
3620 // a pointer to an appropriately qualified version of the *composite*
3621 // type.
3622 // FIXME: Need to calculate the composite type.
3623 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00003624 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3625 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003626 return LHSTy;
3627 }
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Steve Naroff7154a772009-07-01 14:36:47 +00003629 // GCC compatibility: soften pointer/integer mismatch.
3630 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3631 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3632 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003633 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003634 return RHSTy;
3635 }
3636 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3637 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3638 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003639 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003640 return LHSTy;
3641 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003642
Chris Lattner70d67a92008-01-06 22:42:25 +00003643 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003644 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3645 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003646 return QualType();
3647}
3648
Steve Narofff69936d2007-09-16 03:34:24 +00003649/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003650/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003651Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3652 SourceLocation ColonLoc,
3653 ExprArg Cond, ExprArg LHS,
3654 ExprArg RHS) {
3655 Expr *CondExpr = (Expr *) Cond.get();
3656 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003657
3658 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3659 // was the condition.
3660 bool isLHSNull = LHSExpr == 0;
3661 if (isLHSNull)
3662 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003663
3664 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003665 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003666 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003667 return ExprError();
3668
3669 Cond.release();
3670 LHS.release();
3671 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003672 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003673 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003674 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003675}
3676
Reid Spencer5f016e22007-07-11 17:01:13 +00003677// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003678// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003679// routine is it effectively iqnores the qualifiers on the top level pointee.
3680// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3681// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003682Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003683Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3684 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003685
David Chisnall0f436562009-08-17 16:35:33 +00003686 if ((lhsType->isObjCClassType() &&
3687 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3688 (rhsType->isObjCClassType() &&
3689 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3690 return Compatible;
3691 }
3692
Reid Spencer5f016e22007-07-11 17:01:13 +00003693 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003694 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3695 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003696
Reid Spencer5f016e22007-07-11 17:01:13 +00003697 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003698 lhptee = Context.getCanonicalType(lhptee);
3699 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003700
Chris Lattner5cf216b2008-01-04 18:04:52 +00003701 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003702
3703 // C99 6.5.16.1p1: This following citation is common to constraints
3704 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3705 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003706 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003707 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003708 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003709
Mike Stumpeed9cac2009-02-19 03:04:26 +00003710 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3711 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003712 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003713 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003714 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003715 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003716
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003717 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003718 assert(rhptee->isFunctionType());
3719 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003720 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003721
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003722 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003723 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003724 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003725
3726 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003727 assert(lhptee->isFunctionType());
3728 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003729 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003730 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003731 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003732 lhptee = lhptee.getUnqualifiedType();
3733 rhptee = rhptee.getUnqualifiedType();
3734 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3735 // Check if the pointee types are compatible ignoring the sign.
3736 // We explicitly check for char so that we catch "char" vs
3737 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00003738 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003739 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003740 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003741 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003742
3743 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003744 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003745 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003746 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003747
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003748 if (lhptee == rhptee) {
3749 // Types are compatible ignoring the sign. Qualifier incompatibility
3750 // takes priority over sign incompatibility because the sign
3751 // warning can be disabled.
3752 if (ConvTy != Compatible)
3753 return ConvTy;
3754 return IncompatiblePointerSign;
3755 }
3756 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00003757 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003758 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003759 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003760}
3761
Steve Naroff1c7d0672008-09-04 15:10:53 +00003762/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3763/// block pointer types are compatible or whether a block and normal pointer
3764/// are compatible. It is more restrict than comparing two function pointer
3765// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003766Sema::AssignConvertType
3767Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003768 QualType rhsType) {
3769 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003770
Steve Naroff1c7d0672008-09-04 15:10:53 +00003771 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003772 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3773 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003774
Steve Naroff1c7d0672008-09-04 15:10:53 +00003775 // make sure we operate on the canonical type
3776 lhptee = Context.getCanonicalType(lhptee);
3777 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003778
Steve Naroff1c7d0672008-09-04 15:10:53 +00003779 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003780
Steve Naroff1c7d0672008-09-04 15:10:53 +00003781 // For blocks we enforce that qualifiers are identical.
3782 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3783 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003784
Eli Friedman26784c12009-06-08 05:08:54 +00003785 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003786 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003787 return ConvTy;
3788}
3789
Mike Stumpeed9cac2009-02-19 03:04:26 +00003790/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3791/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003792/// pointers. Here are some objectionable examples that GCC considers warnings:
3793///
3794/// int a, *pint;
3795/// short *pshort;
3796/// struct foo *pfoo;
3797///
3798/// pint = pshort; // warning: assignment from incompatible pointer type
3799/// a = pint; // warning: assignment makes integer from pointer without a cast
3800/// pint = a; // warning: assignment makes pointer from integer without a cast
3801/// pint = pfoo; // warning: assignment from incompatible pointer type
3802///
3803/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003804/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003805///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003806Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003807Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003808 // Get canonical types. We're not formatting these types, just comparing
3809 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003810 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3811 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003812
3813 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003814 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003815
David Chisnall0f436562009-08-17 16:35:33 +00003816 if ((lhsType->isObjCClassType() &&
3817 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3818 (rhsType->isObjCClassType() &&
3819 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3820 return Compatible;
3821 }
3822
Douglas Gregor9d293df2008-10-28 00:22:11 +00003823 // If the left-hand side is a reference type, then we are in a
3824 // (rare!) case where we've allowed the use of references in C,
3825 // e.g., as a parameter type in a built-in function. In this case,
3826 // just make sure that the type referenced is compatible with the
3827 // right-hand side type. The caller is responsible for adjusting
3828 // lhsType so that the resulting expression does not have reference
3829 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003830 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00003831 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003832 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003833 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003834 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003835 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3836 // to the same ExtVector type.
3837 if (lhsType->isExtVectorType()) {
3838 if (rhsType->isExtVectorType())
3839 return lhsType == rhsType ? Compatible : Incompatible;
3840 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3841 return Compatible;
3842 }
Mike Stump1eb44332009-09-09 15:08:12 +00003843
Nate Begemanbe2341d2008-07-14 18:02:46 +00003844 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003845 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003846 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003847 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003848 if (getLangOptions().LaxVectorConversions &&
3849 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003850 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003851 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003852 }
3853 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003854 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003855
Chris Lattnere8b3e962008-01-04 23:32:24 +00003856 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003857 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003858
Chris Lattner78eca282008-04-07 06:49:41 +00003859 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003860 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003861 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003862
Chris Lattner78eca282008-04-07 06:49:41 +00003863 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003864 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003865
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003866 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003867 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003868 if (lhsType->isVoidPointerType()) // an exception to the rule.
3869 return Compatible;
3870 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003871 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003872 if (rhsType->getAs<BlockPointerType>()) {
3873 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003874 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003875
3876 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003877 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003878 return Compatible;
3879 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003880 return Incompatible;
3881 }
3882
3883 if (isa<BlockPointerType>(lhsType)) {
3884 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003885 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003886
Steve Naroffb4406862008-09-29 18:10:17 +00003887 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003888 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003889 return Compatible;
3890
Steve Naroff1c7d0672008-09-04 15:10:53 +00003891 if (rhsType->isBlockPointerType())
3892 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003893
Ted Kremenek6217b802009-07-29 21:53:49 +00003894 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003895 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003896 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003897 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003898 return Incompatible;
3899 }
3900
Steve Naroff14108da2009-07-10 23:34:53 +00003901 if (isa<ObjCObjectPointerType>(lhsType)) {
3902 if (rhsType->isIntegerType())
3903 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003905 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003906 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003907 if (rhsType->isVoidPointerType()) // an exception to the rule.
3908 return Compatible;
3909 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003910 }
3911 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003912 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3913 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003914 if (Context.typesAreCompatible(lhsType, rhsType))
3915 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00003916 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3917 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003918 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003919 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003920 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003921 if (RHSPT->getPointeeType()->isVoidType())
3922 return Compatible;
3923 }
3924 // Treat block pointers as objects.
3925 if (rhsType->isBlockPointerType())
3926 return Compatible;
3927 return Incompatible;
3928 }
Chris Lattner78eca282008-04-07 06:49:41 +00003929 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003930 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003931 if (lhsType == Context.BoolTy)
3932 return Compatible;
3933
3934 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003935 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003936
Mike Stumpeed9cac2009-02-19 03:04:26 +00003937 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003938 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003939
3940 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003941 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003942 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003943 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003944 }
Steve Naroff14108da2009-07-10 23:34:53 +00003945 if (isa<ObjCObjectPointerType>(rhsType)) {
3946 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3947 if (lhsType == Context.BoolTy)
3948 return Compatible;
3949
3950 if (lhsType->isIntegerType())
3951 return PointerToInt;
3952
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003953 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003954 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003955 if (lhsType->isVoidPointerType()) // an exception to the rule.
3956 return Compatible;
3957 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003958 }
3959 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003960 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00003961 return Compatible;
3962 return Incompatible;
3963 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003964
Chris Lattnerfc144e22008-01-04 23:18:45 +00003965 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003966 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003967 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003968 }
3969 return Incompatible;
3970}
3971
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003972/// \brief Constructs a transparent union from an expression that is
3973/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00003974static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003975 QualType UnionType, FieldDecl *Field) {
3976 // Build an initializer list that designates the appropriate member
3977 // of the transparent union.
3978 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3979 &E, 1,
3980 SourceLocation());
3981 Initializer->setType(UnionType);
3982 Initializer->setInitializedFieldInUnion(Field);
3983
3984 // Build a compound literal constructing a value of the transparent
3985 // union type from this initializer list.
3986 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3987 false);
3988}
3989
3990Sema::AssignConvertType
3991Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3992 QualType FromType = rExpr->getType();
3993
Mike Stump1eb44332009-09-09 15:08:12 +00003994 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003995 // transparent_union GCC extension.
3996 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003997 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003998 return Incompatible;
3999
4000 // The field to initialize within the transparent union.
4001 RecordDecl *UD = UT->getDecl();
4002 FieldDecl *InitField = 0;
4003 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004004 for (RecordDecl::field_iterator it = UD->field_begin(),
4005 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004006 it != itend; ++it) {
4007 if (it->getType()->isPointerType()) {
4008 // If the transparent union contains a pointer type, we allow:
4009 // 1) void pointer
4010 // 2) null pointer constant
4011 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004012 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004013 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004014 InitField = *it;
4015 break;
4016 }
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Douglas Gregorce940492009-09-25 04:25:58 +00004018 if (rExpr->isNullPointerConstant(Context,
4019 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004020 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004021 InitField = *it;
4022 break;
4023 }
4024 }
4025
4026 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4027 == Compatible) {
4028 InitField = *it;
4029 break;
4030 }
4031 }
4032
4033 if (!InitField)
4034 return Incompatible;
4035
4036 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4037 return Compatible;
4038}
4039
Chris Lattner5cf216b2008-01-04 18:04:52 +00004040Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004041Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004042 if (getLangOptions().CPlusPlus) {
4043 if (!lhsType->isRecordType()) {
4044 // C++ 5.17p3: If the left operand is not of class type, the
4045 // expression is implicitly converted (C++ 4) to the
4046 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004047 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4048 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004049 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004050 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004051 }
4052
4053 // FIXME: Currently, we fall through and treat C++ classes like C
4054 // structures.
4055 }
4056
Steve Naroff529a4ad2007-11-27 17:58:44 +00004057 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4058 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004059 if ((lhsType->isPointerType() ||
4060 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004061 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004062 && rExpr->isNullPointerConstant(Context,
4063 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004064 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004065 return Compatible;
4066 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004067
Chris Lattner943140e2007-10-16 02:55:40 +00004068 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004069 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004070 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004071 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004072 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004073 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004074 if (!lhsType->isReferenceType())
4075 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004076
Chris Lattner5cf216b2008-01-04 18:04:52 +00004077 Sema::AssignConvertType result =
4078 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004079
Steve Narofff1120de2007-08-24 22:33:52 +00004080 // C99 6.5.16.1p2: The value of the right operand is converted to the
4081 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004082 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4083 // so that we can use references in built-in functions even in C.
4084 // The getNonReferenceType() call makes sure that the resulting expression
4085 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004086 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004087 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4088 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004089 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004090}
4091
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004092QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004093 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004094 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004095 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004096 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004097}
4098
Mike Stumpeed9cac2009-02-19 03:04:26 +00004099inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004100 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004101 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004102 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004103 QualType lhsType =
4104 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4105 QualType rhsType =
4106 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004107
Nate Begemanbe2341d2008-07-14 18:02:46 +00004108 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004109 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004110 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004111
Nate Begemanbe2341d2008-07-14 18:02:46 +00004112 // Handle the case of a vector & extvector type of the same size and element
4113 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004114 if (getLangOptions().LaxVectorConversions) {
4115 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004116 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4117 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004118 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004119 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004120 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004121 }
4122 }
4123 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004124
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004125 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4126 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4127 bool swapped = false;
4128 if (rhsType->isExtVectorType()) {
4129 swapped = true;
4130 std::swap(rex, lex);
4131 std::swap(rhsType, lhsType);
4132 }
Mike Stump1eb44332009-09-09 15:08:12 +00004133
Nate Begemandde25982009-06-28 19:12:57 +00004134 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004135 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004136 QualType EltTy = LV->getElementType();
4137 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4138 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004139 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004140 if (swapped) std::swap(rex, lex);
4141 return lhsType;
4142 }
4143 }
4144 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4145 rhsType->isRealFloatingType()) {
4146 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004147 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004148 if (swapped) std::swap(rex, lex);
4149 return lhsType;
4150 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004151 }
4152 }
Mike Stump1eb44332009-09-09 15:08:12 +00004153
Nate Begemandde25982009-06-28 19:12:57 +00004154 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004155 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004156 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004157 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004158 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004159}
4160
Reid Spencer5f016e22007-07-11 17:01:13 +00004161inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004162 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004163 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004164 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004165
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004166 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004167
Steve Naroffa4332e22007-07-17 00:58:39 +00004168 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004169 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004170 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004171}
4172
4173inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004174 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004175 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4176 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4177 return CheckVectorOperands(Loc, lex, rex);
4178 return InvalidOperands(Loc, lex, rex);
4179 }
Steve Naroff90045e82007-07-13 23:32:42 +00004180
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004181 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004182
Steve Naroffa4332e22007-07-17 00:58:39 +00004183 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004184 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004185 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004186}
4187
4188inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004189 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004190 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4191 QualType compType = CheckVectorOperands(Loc, lex, rex);
4192 if (CompLHSTy) *CompLHSTy = compType;
4193 return compType;
4194 }
Steve Naroff49b45262007-07-13 16:58:59 +00004195
Eli Friedmanab3a8522009-03-28 01:22:36 +00004196 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004197
Reid Spencer5f016e22007-07-11 17:01:13 +00004198 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004199 if (lex->getType()->isArithmeticType() &&
4200 rex->getType()->isArithmeticType()) {
4201 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004202 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004203 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004204
Eli Friedmand72d16e2008-05-18 18:08:51 +00004205 // Put any potential pointer into PExp
4206 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004207 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004208 std::swap(PExp, IExp);
4209
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004210 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004211
Eli Friedmand72d16e2008-05-18 18:08:51 +00004212 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004213 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004214
Chris Lattnerb5f15622009-04-24 23:50:08 +00004215 // Check for arithmetic on pointers to incomplete types.
4216 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004217 if (getLangOptions().CPlusPlus) {
4218 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004219 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004220 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004221 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004222
4223 // GNU extension: arithmetic on pointer to void
4224 Diag(Loc, diag::ext_gnu_void_ptr)
4225 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004226 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004227 if (getLangOptions().CPlusPlus) {
4228 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4229 << lex->getType() << lex->getSourceRange();
4230 return QualType();
4231 }
4232
4233 // GNU extension: arithmetic on pointer to function
4234 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4235 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004236 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004237 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004238 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004239 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004240 PExp->getType()->isObjCObjectPointerType()) &&
4241 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004242 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4243 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004244 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004245 return QualType();
4246 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004247 // Diagnose bad cases where we step over interface counts.
4248 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4249 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4250 << PointeeTy << PExp->getSourceRange();
4251 return QualType();
4252 }
Mike Stump1eb44332009-09-09 15:08:12 +00004253
Eli Friedmanab3a8522009-03-28 01:22:36 +00004254 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004255 QualType LHSTy = Context.isPromotableBitField(lex);
4256 if (LHSTy.isNull()) {
4257 LHSTy = lex->getType();
4258 if (LHSTy->isPromotableIntegerType())
4259 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004260 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004261 *CompLHSTy = LHSTy;
4262 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004263 return PExp->getType();
4264 }
4265 }
4266
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004267 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004268}
4269
Chris Lattnereca7be62008-04-07 05:30:13 +00004270// C99 6.5.6
4271QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004272 SourceLocation Loc, QualType* CompLHSTy) {
4273 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4274 QualType compType = CheckVectorOperands(Loc, lex, rex);
4275 if (CompLHSTy) *CompLHSTy = compType;
4276 return compType;
4277 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004278
Eli Friedmanab3a8522009-03-28 01:22:36 +00004279 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004280
Chris Lattner6e4ab612007-12-09 21:53:25 +00004281 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004282
Chris Lattner6e4ab612007-12-09 21:53:25 +00004283 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004284 if (lex->getType()->isArithmeticType()
4285 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004286 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004287 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004288 }
Mike Stump1eb44332009-09-09 15:08:12 +00004289
Chris Lattner6e4ab612007-12-09 21:53:25 +00004290 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004291 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004292 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004293
Douglas Gregore7450f52009-03-24 19:52:54 +00004294 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004295
Douglas Gregore7450f52009-03-24 19:52:54 +00004296 bool ComplainAboutVoid = false;
4297 Expr *ComplainAboutFunc = 0;
4298 if (lpointee->isVoidType()) {
4299 if (getLangOptions().CPlusPlus) {
4300 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4301 << lex->getSourceRange() << rex->getSourceRange();
4302 return QualType();
4303 }
4304
4305 // GNU C extension: arithmetic on pointer to void
4306 ComplainAboutVoid = true;
4307 } else if (lpointee->isFunctionType()) {
4308 if (getLangOptions().CPlusPlus) {
4309 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004310 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004311 return QualType();
4312 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004313
4314 // GNU C extension: arithmetic on pointer to function
4315 ComplainAboutFunc = lex;
4316 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004317 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004318 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004319 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004320 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004321 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004322
Chris Lattnerb5f15622009-04-24 23:50:08 +00004323 // Diagnose bad cases where we step over interface counts.
4324 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4325 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4326 << lpointee << lex->getSourceRange();
4327 return QualType();
4328 }
Mike Stump1eb44332009-09-09 15:08:12 +00004329
Chris Lattner6e4ab612007-12-09 21:53:25 +00004330 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004331 if (rex->getType()->isIntegerType()) {
4332 if (ComplainAboutVoid)
4333 Diag(Loc, diag::ext_gnu_void_ptr)
4334 << lex->getSourceRange() << rex->getSourceRange();
4335 if (ComplainAboutFunc)
4336 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004337 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004338 << ComplainAboutFunc->getSourceRange();
4339
Eli Friedmanab3a8522009-03-28 01:22:36 +00004340 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004341 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004342 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004343
Chris Lattner6e4ab612007-12-09 21:53:25 +00004344 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004345 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004346 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004347
Douglas Gregore7450f52009-03-24 19:52:54 +00004348 // RHS must be a completely-type object type.
4349 // Handle the GNU void* extension.
4350 if (rpointee->isVoidType()) {
4351 if (getLangOptions().CPlusPlus) {
4352 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4353 << lex->getSourceRange() << rex->getSourceRange();
4354 return QualType();
4355 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004356
Douglas Gregore7450f52009-03-24 19:52:54 +00004357 ComplainAboutVoid = true;
4358 } else if (rpointee->isFunctionType()) {
4359 if (getLangOptions().CPlusPlus) {
4360 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004361 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004362 return QualType();
4363 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004364
4365 // GNU extension: arithmetic on pointer to function
4366 if (!ComplainAboutFunc)
4367 ComplainAboutFunc = rex;
4368 } else if (!rpointee->isDependentType() &&
4369 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004370 PDiag(diag::err_typecheck_sub_ptr_object)
4371 << rex->getSourceRange()
4372 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004373 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004374
Eli Friedman88d936b2009-05-16 13:54:38 +00004375 if (getLangOptions().CPlusPlus) {
4376 // Pointee types must be the same: C++ [expr.add]
4377 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4378 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4379 << lex->getType() << rex->getType()
4380 << lex->getSourceRange() << rex->getSourceRange();
4381 return QualType();
4382 }
4383 } else {
4384 // Pointee types must be compatible C99 6.5.6p3
4385 if (!Context.typesAreCompatible(
4386 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4387 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4388 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4389 << lex->getType() << rex->getType()
4390 << lex->getSourceRange() << rex->getSourceRange();
4391 return QualType();
4392 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004393 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004394
Douglas Gregore7450f52009-03-24 19:52:54 +00004395 if (ComplainAboutVoid)
4396 Diag(Loc, diag::ext_gnu_void_ptr)
4397 << lex->getSourceRange() << rex->getSourceRange();
4398 if (ComplainAboutFunc)
4399 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004400 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004401 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004402
4403 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004404 return Context.getPointerDiffType();
4405 }
4406 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004407
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004408 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004409}
4410
Chris Lattnereca7be62008-04-07 05:30:13 +00004411// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004412QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004413 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004414 // C99 6.5.7p2: Each of the operands shall have integer type.
4415 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004416 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004417
Nate Begeman2207d792009-10-25 02:26:48 +00004418 // Vector shifts promote their scalar inputs to vector type.
4419 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4420 return CheckVectorOperands(Loc, lex, rex);
4421
Chris Lattnerca5eede2007-12-12 05:47:28 +00004422 // Shifts don't perform usual arithmetic conversions, they just do integer
4423 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004424 QualType LHSTy = Context.isPromotableBitField(lex);
4425 if (LHSTy.isNull()) {
4426 LHSTy = lex->getType();
4427 if (LHSTy->isPromotableIntegerType())
4428 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004429 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004430 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004431 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004432
Chris Lattnerca5eede2007-12-12 05:47:28 +00004433 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004434
Ryan Flynnd0439682009-08-07 16:20:20 +00004435 // Sanity-check shift operands
4436 llvm::APSInt Right;
4437 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004438 if (!rex->isValueDependent() &&
4439 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004440 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004441 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4442 else {
4443 llvm::APInt LeftBits(Right.getBitWidth(),
4444 Context.getTypeSize(lex->getType()));
4445 if (Right.uge(LeftBits))
4446 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4447 }
4448 }
4449
Chris Lattnerca5eede2007-12-12 05:47:28 +00004450 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004451 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004452}
4453
Douglas Gregor0c6db942009-05-04 06:07:12 +00004454// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004455QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004456 unsigned OpaqueOpc, bool isRelational) {
4457 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4458
Nate Begemanbe2341d2008-07-14 18:02:46 +00004459 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004460 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004461
Chris Lattnera5937dd2007-08-26 01:18:55 +00004462 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00004463 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4464 UsualArithmeticConversions(lex, rex);
4465 else {
4466 UsualUnaryConversions(lex);
4467 UsualUnaryConversions(rex);
4468 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004469 QualType lType = lex->getType();
4470 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004471
Mike Stumpaf199f32009-05-07 18:43:07 +00004472 if (!lType->isFloatingType()
4473 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00004474 // For non-floating point types, check for self-comparisons of the form
4475 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4476 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00004477 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00004478 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00004479 Expr *LHSStripped = lex->IgnoreParens();
4480 Expr *RHSStripped = rex->IgnoreParens();
4481 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4482 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00004483 if (DRL->getDecl() == DRR->getDecl() &&
4484 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004485 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00004486
Chris Lattner55660a72009-03-08 19:39:53 +00004487 if (isa<CastExpr>(LHSStripped))
4488 LHSStripped = LHSStripped->IgnoreParenCasts();
4489 if (isa<CastExpr>(RHSStripped))
4490 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00004491
Chris Lattner55660a72009-03-08 19:39:53 +00004492 // Warn about comparisons against a string constant (unless the other
4493 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00004494 Expr *literalString = 0;
4495 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00004496 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004497 !RHSStripped->isNullPointerConstant(Context,
4498 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004499 literalString = lex;
4500 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004501 } else if ((isa<StringLiteral>(RHSStripped) ||
4502 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004503 !LHSStripped->isNullPointerConstant(Context,
4504 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004505 literalString = rex;
4506 literalStringStripped = RHSStripped;
4507 }
4508
4509 if (literalString) {
4510 std::string resultComparison;
4511 switch (Opc) {
4512 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4513 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4514 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4515 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4516 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4517 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4518 default: assert(false && "Invalid comparison operator");
4519 }
4520 Diag(Loc, diag::warn_stringcompare)
4521 << isa<ObjCEncodeExpr>(literalStringStripped)
4522 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00004523 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4524 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4525 "strcmp(")
4526 << CodeModificationHint::CreateInsertion(
4527 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00004528 resultComparison);
4529 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00004530 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004531
Douglas Gregor447b69e2008-11-19 03:25:36 +00004532 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00004533 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00004534
Chris Lattnera5937dd2007-08-26 01:18:55 +00004535 if (isRelational) {
4536 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004537 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004538 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004539 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004540 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00004541 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004542 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00004543 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004544
Chris Lattnera5937dd2007-08-26 01:18:55 +00004545 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004546 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004547 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004548
Douglas Gregorce940492009-09-25 04:25:58 +00004549 bool LHSIsNull = lex->isNullPointerConstant(Context,
4550 Expr::NPC_ValueDependentIsNull);
4551 bool RHSIsNull = rex->isNullPointerConstant(Context,
4552 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004553
Chris Lattnera5937dd2007-08-26 01:18:55 +00004554 // All of the following pointer related warnings are GCC extensions, except
4555 // when handling null pointer constants. One day, we can consider making them
4556 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00004557 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00004558 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004559 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00004560 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004561 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004562
Douglas Gregor0c6db942009-05-04 06:07:12 +00004563 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00004564 if (LCanPointeeTy == RCanPointeeTy)
4565 return ResultTy;
4566
Douglas Gregor0c6db942009-05-04 06:07:12 +00004567 // C++ [expr.rel]p2:
4568 // [...] Pointer conversions (4.10) and qualification
4569 // conversions (4.4) are performed on pointer operands (or on
4570 // a pointer operand and a null pointer constant) to bring
4571 // them to their composite pointer type. [...]
4572 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00004573 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00004574 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00004575 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004576 if (T.isNull()) {
4577 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4578 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4579 return QualType();
4580 }
4581
Eli Friedman73c39ab2009-10-20 08:27:19 +00004582 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4583 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004584 return ResultTy;
4585 }
Eli Friedman3075e762009-08-23 00:27:47 +00004586 // C99 6.5.9p2 and C99 6.5.8p2
4587 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4588 RCanPointeeTy.getUnqualifiedType())) {
4589 // Valid unless a relational comparison of function pointers
4590 if (isRelational && LCanPointeeTy->isFunctionType()) {
4591 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4592 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4593 }
4594 } else if (!isRelational &&
4595 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4596 // Valid unless comparison between non-null pointer and function pointer
4597 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4598 && !LHSIsNull && !RHSIsNull) {
4599 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4600 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4601 }
4602 } else {
4603 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004604 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004605 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004606 }
Eli Friedman3075e762009-08-23 00:27:47 +00004607 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004608 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004609 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004610 }
Mike Stump1eb44332009-09-09 15:08:12 +00004611
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004612 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00004613 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00004614 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00004615 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004616 (lType->isPointerType() ||
4617 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004618 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004619 return ResultTy;
4620 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004621 if (LHSIsNull &&
4622 (rType->isPointerType() ||
4623 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004624 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004625 return ResultTy;
4626 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004627
4628 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00004629 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004630 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4631 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004632 // In addition, pointers to members can be compared, or a pointer to
4633 // member and a null pointer constant. Pointer to member conversions
4634 // (4.11) and qualification conversions (4.4) are performed to bring
4635 // them to a common type. If one operand is a null pointer constant,
4636 // the common type is the type of the other operand. Otherwise, the
4637 // common type is a pointer to member type similar (4.4) to the type
4638 // of one of the operands, with a cv-qualification signature (4.4)
4639 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00004640 // types.
4641 QualType T = FindCompositePointerType(lex, rex);
4642 if (T.isNull()) {
4643 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4644 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4645 return QualType();
4646 }
Mike Stump1eb44332009-09-09 15:08:12 +00004647
Eli Friedman73c39ab2009-10-20 08:27:19 +00004648 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4649 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004650 return ResultTy;
4651 }
Mike Stump1eb44332009-09-09 15:08:12 +00004652
Douglas Gregor20b3e992009-08-24 17:42:35 +00004653 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004654 if (lType->isNullPtrType() && rType->isNullPtrType())
4655 return ResultTy;
4656 }
Mike Stump1eb44332009-09-09 15:08:12 +00004657
Steve Naroff1c7d0672008-09-04 15:10:53 +00004658 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004659 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004660 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4661 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004662
Steve Naroff1c7d0672008-09-04 15:10:53 +00004663 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00004664 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004665 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00004666 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00004667 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004668 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004669 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004670 }
Steve Naroff59f53942008-09-28 01:11:11 +00004671 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004672 if (!isRelational
4673 && ((lType->isBlockPointerType() && rType->isPointerType())
4674 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00004675 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004676 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004677 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004678 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004679 ->getPointeeType()->isVoidType())))
4680 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4681 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004682 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004683 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004684 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004685 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004686
Steve Naroff14108da2009-07-10 23:34:53 +00004687 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004688 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004689 const PointerType *LPT = lType->getAs<PointerType>();
4690 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004691 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004692 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004693 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004694 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004695
Steve Naroffa8069f12008-11-17 19:49:16 +00004696 if (!LPtrToVoid && !RPtrToVoid &&
4697 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004698 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004699 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004700 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004701 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004702 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004703 }
Steve Naroff14108da2009-07-10 23:34:53 +00004704 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004705 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00004706 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4707 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004708 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004709 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00004710 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004711 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004712 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004713 unsigned DiagID = 0;
4714 if (RHSIsNull) {
4715 if (isRelational)
4716 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4717 } else if (isRelational)
4718 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4719 else
4720 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004721
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004722 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004723 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004724 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004725 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004726 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004727 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004728 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004729 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004730 unsigned DiagID = 0;
4731 if (LHSIsNull) {
4732 if (isRelational)
4733 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4734 } else if (isRelational)
4735 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4736 else
4737 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004739 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004740 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004741 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004742 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004743 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004744 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004745 }
Steve Naroff39218df2008-09-04 16:56:14 +00004746 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004747 if (!isRelational && RHSIsNull
4748 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004749 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004750 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004751 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004752 if (!isRelational && LHSIsNull
4753 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004754 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004755 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004756 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004757 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004758}
4759
Nate Begemanbe2341d2008-07-14 18:02:46 +00004760/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004761/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004762/// like a scalar comparison, a vector comparison produces a vector of integer
4763/// types.
4764QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004765 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004766 bool isRelational) {
4767 // Check to make sure we're operating on vectors of the same type and width,
4768 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004769 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004770 if (vType.isNull())
4771 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004772
Nate Begemanbe2341d2008-07-14 18:02:46 +00004773 QualType lType = lex->getType();
4774 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004775
Nate Begemanbe2341d2008-07-14 18:02:46 +00004776 // For non-floating point types, check for self-comparisons of the form
4777 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4778 // often indicate logic errors in the program.
4779 if (!lType->isFloatingType()) {
4780 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4781 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4782 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004783 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004784 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004785
Nate Begemanbe2341d2008-07-14 18:02:46 +00004786 // Check for comparisons of floating point operands using != and ==.
4787 if (!isRelational && lType->isFloatingType()) {
4788 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004789 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004790 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004791
Nate Begemanbe2341d2008-07-14 18:02:46 +00004792 // Return the type for the comparison, which is the same as vector type for
4793 // integer vectors, or an integer type of identical size and number of
4794 // elements for floating point vectors.
4795 if (lType->isIntegerType())
4796 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004797
John McCall183700f2009-09-21 23:43:11 +00004798 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004799 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004800 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004801 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004802 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004803 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4804
Mike Stumpeed9cac2009-02-19 03:04:26 +00004805 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004806 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004807 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4808}
4809
Reid Spencer5f016e22007-07-11 17:01:13 +00004810inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004811 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00004812 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004813 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004814
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004815 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004816
Steve Naroffa4332e22007-07-17 00:58:39 +00004817 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004818 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004819 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004820}
4821
4822inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00004823 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004824 UsualUnaryConversions(lex);
4825 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004826
Anders Carlsson04905012009-10-16 01:44:21 +00004827 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4828 return InvalidOperands(Loc, lex, rex);
4829
4830 if (Context.getLangOptions().CPlusPlus) {
4831 // C++ [expr.log.and]p2
4832 // C++ [expr.log.or]p2
4833 return Context.BoolTy;
4834 }
4835
4836 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004837}
4838
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004839/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4840/// is a read-only property; return true if so. A readonly property expression
4841/// depends on various declarations and thus must be treated specially.
4842///
Mike Stump1eb44332009-09-09 15:08:12 +00004843static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004844 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4845 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4846 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4847 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004848 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00004849 BaseType->getAsObjCInterfacePointerType())
4850 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4851 if (S.isPropertyReadonly(PDecl, IFace))
4852 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004853 }
4854 }
4855 return false;
4856}
4857
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004858/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4859/// emit an error and return true. If so, return false.
4860static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004861 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00004862 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004863 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004864 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4865 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004866 if (IsLV == Expr::MLV_Valid)
4867 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004868
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004869 unsigned Diag = 0;
4870 bool NeedType = false;
4871 switch (IsLV) { // C99 6.5.16p2
4872 default: assert(0 && "Unknown result from isModifiableLvalue!");
4873 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004874 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004875 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4876 NeedType = true;
4877 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004878 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004879 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4880 NeedType = true;
4881 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00004882 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004883 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4884 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004885 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004886 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4887 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004888 case Expr::MLV_IncompleteType:
4889 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00004890 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00004891 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4892 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00004893 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004894 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4895 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00004896 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004897 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4898 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00004899 case Expr::MLV_ReadonlyProperty:
4900 Diag = diag::error_readonly_property_assignment;
4901 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00004902 case Expr::MLV_NoSetterProperty:
4903 Diag = diag::error_nosetter_property_assignment;
4904 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004905 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00004906
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004907 SourceRange Assign;
4908 if (Loc != OrigLoc)
4909 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004910 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004911 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004912 else
Mike Stump1eb44332009-09-09 15:08:12 +00004913 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004914 return true;
4915}
4916
4917
4918
4919// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004920QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4921 SourceLocation Loc,
4922 QualType CompoundType) {
4923 // Verify that LHS is a modifiable lvalue, and emit error if not.
4924 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004925 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004926
4927 QualType LHSType = LHS->getType();
4928 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004929
Chris Lattner5cf216b2008-01-04 18:04:52 +00004930 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004931 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00004932 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004933 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004934 // Special case of NSObject attributes on c-style pointer types.
4935 if (ConvTy == IncompatiblePointer &&
4936 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00004937 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004938 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00004939 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004940 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004941
Chris Lattner2c156472008-08-21 18:04:13 +00004942 // If the RHS is a unary plus or minus, check to see if they = and + are
4943 // right next to each other. If so, the user may have typo'd "x =+ 4"
4944 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004945 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00004946 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4947 RHSCheck = ICE->getSubExpr();
4948 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4949 if ((UO->getOpcode() == UnaryOperator::Plus ||
4950 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004951 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00004952 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00004953 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4954 // And there is a space or other character before the subexpr of the
4955 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00004956 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4957 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004958 Diag(Loc, diag::warn_not_compound_assign)
4959 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4960 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00004961 }
Chris Lattner2c156472008-08-21 18:04:13 +00004962 }
4963 } else {
4964 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00004965 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00004966 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004967
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004968 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4969 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004970 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004971
Reid Spencer5f016e22007-07-11 17:01:13 +00004972 // C99 6.5.16p3: The type of an assignment expression is the type of the
4973 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00004974 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00004975 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4976 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004977 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00004978 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004979 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004980}
4981
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004982// C99 6.5.17
4983QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00004984 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004985 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004986
4987 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4988 // incomplete in C++).
4989
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004990 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004991}
4992
Steve Naroff49b45262007-07-13 16:58:59 +00004993/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4994/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004995QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4996 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00004997 if (Op->isTypeDependent())
4998 return Context.DependentTy;
4999
Chris Lattner3528d352008-11-21 07:05:48 +00005000 QualType ResType = Op->getType();
5001 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005002
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005003 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5004 // Decrement of bool is not allowed.
5005 if (!isInc) {
5006 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5007 return QualType();
5008 }
5009 // Increment of bool sets it to true, but is deprecated.
5010 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5011 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005012 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005013 } else if (ResType->isAnyPointerType()) {
5014 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005015
Chris Lattner3528d352008-11-21 07:05:48 +00005016 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005017 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005018 if (getLangOptions().CPlusPlus) {
5019 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5020 << Op->getSourceRange();
5021 return QualType();
5022 }
5023
5024 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005025 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005026 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005027 if (getLangOptions().CPlusPlus) {
5028 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5029 << Op->getType() << Op->getSourceRange();
5030 return QualType();
5031 }
5032
5033 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005034 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005035 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005036 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005037 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005038 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005039 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005040 // Diagnose bad cases where we step over interface counts.
5041 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5042 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5043 << PointeeTy << Op->getSourceRange();
5044 return QualType();
5045 }
Chris Lattner3528d352008-11-21 07:05:48 +00005046 } else if (ResType->isComplexType()) {
5047 // C99 does not support ++/-- on complex types, we allow as an extension.
5048 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005049 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005050 } else {
5051 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005052 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005053 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005054 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005055 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005056 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005057 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005058 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005059 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005060}
5061
Anders Carlsson369dee42008-02-01 07:15:58 +00005062/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005063/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005064/// where the declaration is needed for type checking. We only need to
5065/// handle cases when the expression references a function designator
5066/// or is an lvalue. Here are some examples:
5067/// - &(x) => x
5068/// - &*****f => f for f a function designator.
5069/// - &s.xx => s
5070/// - &s.zz[1].yy -> s, if zz is an array
5071/// - *(x + 1) -> x, if x is an array
5072/// - &"123"[2] -> 0
5073/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005074static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005075 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005076 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005077 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005078 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005079 // If this is an arrow operator, the address is an offset from
5080 // the base's value, so the object the base refers to is
5081 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005082 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005083 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005084 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005085 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005086 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005087 // FIXME: This code shouldn't be necessary! We should catch the implicit
5088 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005089 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5090 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5091 if (ICE->getSubExpr()->getType()->isArrayType())
5092 return getPrimaryDecl(ICE->getSubExpr());
5093 }
5094 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005095 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005096 case Stmt::UnaryOperatorClass: {
5097 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005098
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005099 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005100 case UnaryOperator::Real:
5101 case UnaryOperator::Imag:
5102 case UnaryOperator::Extension:
5103 return getPrimaryDecl(UO->getSubExpr());
5104 default:
5105 return 0;
5106 }
5107 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005108 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005109 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005110 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005111 // If the result of an implicit cast is an l-value, we care about
5112 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005113 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005114 default:
5115 return 0;
5116 }
5117}
5118
5119/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005120/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005121/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005122/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005123/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005124/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005125/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005126QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005127 // Make sure to ignore parentheses in subsequent checks
5128 op = op->IgnoreParens();
5129
Douglas Gregor9103bb22008-12-17 22:52:20 +00005130 if (op->isTypeDependent())
5131 return Context.DependentTy;
5132
Steve Naroff08f19672008-01-13 17:10:08 +00005133 if (getLangOptions().C99) {
5134 // Implement C99-only parts of addressof rules.
5135 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5136 if (uOp->getOpcode() == UnaryOperator::Deref)
5137 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5138 // (assuming the deref expression is valid).
5139 return uOp->getSubExpr()->getType();
5140 }
5141 // Technically, there should be a check for array subscript
5142 // expressions here, but the result of one is always an lvalue anyway.
5143 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005144 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005145 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005146
Eli Friedman441cf102009-05-16 23:27:50 +00005147 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5148 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005149 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005150 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005151 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005152 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5153 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005154 return QualType();
5155 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005156 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005157 // The operand cannot be a bit-field
5158 Diag(OpLoc, diag::err_typecheck_address_of)
5159 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005160 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005161 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5162 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005163 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005164 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005165 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005166 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005167 } else if (isa<ObjCPropertyRefExpr>(op)) {
5168 // cannot take address of a property expression.
5169 Diag(OpLoc, diag::err_typecheck_address_of)
5170 << "property expression" << op->getSourceRange();
5171 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005172 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5173 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005174 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5175 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Steve Naroffbcb2b612008-02-29 23:30:25 +00005176 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005177 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005178 // with the register storage-class specifier.
5179 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5180 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005181 Diag(OpLoc, diag::err_typecheck_address_of)
5182 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005183 return QualType();
5184 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00005185 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5186 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005187 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005188 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005189 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005190 // Could be a pointer to member, though, if there is an explicit
5191 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005192 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005193 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005194 if (Ctx && Ctx->isRecord()) {
5195 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005196 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005197 diag::err_cannot_form_pointer_to_member_of_reference_type)
5198 << FD->getDeclName() << FD->getType();
5199 return QualType();
5200 }
Mike Stump1eb44332009-09-09 15:08:12 +00005201
Sebastian Redlebc07d52009-02-03 20:19:35 +00005202 return Context.getMemberPointerType(op->getType(),
5203 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005204 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005205 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005206 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005207 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005208 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005209 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5210 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005211 return Context.getMemberPointerType(op->getType(),
5212 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5213 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005214 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005215 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005216
Eli Friedman441cf102009-05-16 23:27:50 +00005217 if (lval == Expr::LV_IncompleteVoidType) {
5218 // Taking the address of a void variable is technically illegal, but we
5219 // allow it in cases which are otherwise valid.
5220 // Example: "extern void x; void* y = &x;".
5221 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5222 }
5223
Reid Spencer5f016e22007-07-11 17:01:13 +00005224 // If the operand has type "type", the result has type "pointer to type".
5225 return Context.getPointerType(op->getType());
5226}
5227
Chris Lattner22caddc2008-11-23 09:13:29 +00005228QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005229 if (Op->isTypeDependent())
5230 return Context.DependentTy;
5231
Chris Lattner22caddc2008-11-23 09:13:29 +00005232 UsualUnaryConversions(Op);
5233 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005234
Chris Lattner22caddc2008-11-23 09:13:29 +00005235 // Note that per both C89 and C99, this is always legal, even if ptype is an
5236 // incomplete type or void. It would be possible to warn about dereferencing
5237 // a void pointer, but it's completely well-defined, and such a warning is
5238 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005239 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005240 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005241
John McCall183700f2009-09-21 23:43:11 +00005242 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005243 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005244
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005245 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005246 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005247 return QualType();
5248}
5249
5250static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5251 tok::TokenKind Kind) {
5252 BinaryOperator::Opcode Opc;
5253 switch (Kind) {
5254 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005255 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5256 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005257 case tok::star: Opc = BinaryOperator::Mul; break;
5258 case tok::slash: Opc = BinaryOperator::Div; break;
5259 case tok::percent: Opc = BinaryOperator::Rem; break;
5260 case tok::plus: Opc = BinaryOperator::Add; break;
5261 case tok::minus: Opc = BinaryOperator::Sub; break;
5262 case tok::lessless: Opc = BinaryOperator::Shl; break;
5263 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5264 case tok::lessequal: Opc = BinaryOperator::LE; break;
5265 case tok::less: Opc = BinaryOperator::LT; break;
5266 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5267 case tok::greater: Opc = BinaryOperator::GT; break;
5268 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5269 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5270 case tok::amp: Opc = BinaryOperator::And; break;
5271 case tok::caret: Opc = BinaryOperator::Xor; break;
5272 case tok::pipe: Opc = BinaryOperator::Or; break;
5273 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5274 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5275 case tok::equal: Opc = BinaryOperator::Assign; break;
5276 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5277 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5278 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5279 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5280 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5281 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5282 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5283 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5284 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5285 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5286 case tok::comma: Opc = BinaryOperator::Comma; break;
5287 }
5288 return Opc;
5289}
5290
5291static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5292 tok::TokenKind Kind) {
5293 UnaryOperator::Opcode Opc;
5294 switch (Kind) {
5295 default: assert(0 && "Unknown unary op!");
5296 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5297 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5298 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5299 case tok::star: Opc = UnaryOperator::Deref; break;
5300 case tok::plus: Opc = UnaryOperator::Plus; break;
5301 case tok::minus: Opc = UnaryOperator::Minus; break;
5302 case tok::tilde: Opc = UnaryOperator::Not; break;
5303 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005304 case tok::kw___real: Opc = UnaryOperator::Real; break;
5305 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5306 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5307 }
5308 return Opc;
5309}
5310
Douglas Gregoreaebc752008-11-06 23:29:22 +00005311/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5312/// operator @p Opc at location @c TokLoc. This routine only supports
5313/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005314Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5315 unsigned Op,
5316 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005317 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005318 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005319 // The following two variables are used for compound assignment operators
5320 QualType CompLHSTy; // Type of LHS after promotions for computation
5321 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005322
5323 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005324 case BinaryOperator::Assign:
5325 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5326 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005327 case BinaryOperator::PtrMemD:
5328 case BinaryOperator::PtrMemI:
5329 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5330 Opc == BinaryOperator::PtrMemI);
5331 break;
5332 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005333 case BinaryOperator::Div:
5334 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5335 break;
5336 case BinaryOperator::Rem:
5337 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5338 break;
5339 case BinaryOperator::Add:
5340 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5341 break;
5342 case BinaryOperator::Sub:
5343 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5344 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005345 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005346 case BinaryOperator::Shr:
5347 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5348 break;
5349 case BinaryOperator::LE:
5350 case BinaryOperator::LT:
5351 case BinaryOperator::GE:
5352 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005353 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005354 break;
5355 case BinaryOperator::EQ:
5356 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005357 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005358 break;
5359 case BinaryOperator::And:
5360 case BinaryOperator::Xor:
5361 case BinaryOperator::Or:
5362 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5363 break;
5364 case BinaryOperator::LAnd:
5365 case BinaryOperator::LOr:
5366 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5367 break;
5368 case BinaryOperator::MulAssign:
5369 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005370 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5371 CompLHSTy = CompResultTy;
5372 if (!CompResultTy.isNull())
5373 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005374 break;
5375 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005376 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5377 CompLHSTy = CompResultTy;
5378 if (!CompResultTy.isNull())
5379 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005380 break;
5381 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005382 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5383 if (!CompResultTy.isNull())
5384 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005385 break;
5386 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005387 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5388 if (!CompResultTy.isNull())
5389 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005390 break;
5391 case BinaryOperator::ShlAssign:
5392 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005393 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5394 CompLHSTy = CompResultTy;
5395 if (!CompResultTy.isNull())
5396 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005397 break;
5398 case BinaryOperator::AndAssign:
5399 case BinaryOperator::XorAssign:
5400 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005401 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5402 CompLHSTy = CompResultTy;
5403 if (!CompResultTy.isNull())
5404 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005405 break;
5406 case BinaryOperator::Comma:
5407 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5408 break;
5409 }
5410 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005411 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005412 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005413 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5414 else
5415 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005416 CompLHSTy, CompResultTy,
5417 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005418}
5419
Sebastian Redlaee3c932009-10-27 12:10:02 +00005420/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5421/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005422static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5423 const PartialDiagnostic &PD,
5424 SourceRange ParenRange)
5425{
5426 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5427 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5428 // We can't display the parentheses, so just dig the
5429 // warning/error and return.
5430 Self.Diag(Loc, PD);
5431 return;
5432 }
5433
5434 Self.Diag(Loc, PD)
5435 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5436 << CodeModificationHint::CreateInsertion(EndLoc, ")");
5437}
5438
Sebastian Redlaee3c932009-10-27 12:10:02 +00005439/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5440/// operators are mixed in a way that suggests that the programmer forgot that
5441/// comparison operators have higher precedence. The most typical example of
5442/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005443static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5444 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005445 typedef BinaryOperator BinOp;
5446 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5447 rhsopc = static_cast<BinOp::Opcode>(-1);
5448 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005449 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00005450 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005451 rhsopc = BO->getOpcode();
5452
5453 // Subs are not binary operators.
5454 if (lhsopc == -1 && rhsopc == -1)
5455 return;
5456
5457 // Bitwise operations are sometimes used as eager logical ops.
5458 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00005459 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5460 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005461 return;
5462
Sebastian Redlaee3c932009-10-27 12:10:02 +00005463 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005464 SuggestParentheses(Self, OpLoc,
5465 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005466 << SourceRange(lhs->getLocStart(), OpLoc)
5467 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5468 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5469 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005470 SuggestParentheses(Self, OpLoc,
5471 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005472 << SourceRange(OpLoc, rhs->getLocEnd())
5473 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5474 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005475}
5476
5477/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5478/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5479/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5480static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5481 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005482 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005483 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5484}
5485
Reid Spencer5f016e22007-07-11 17:01:13 +00005486// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005487Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5488 tok::TokenKind Kind,
5489 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005490 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00005491 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00005492
Steve Narofff69936d2007-09-16 03:34:24 +00005493 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5494 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005495
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005496 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5497 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5498
Douglas Gregor063daf62009-03-13 18:40:31 +00005499 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00005500 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00005501 rhs->getType()->isOverloadableType())) {
5502 // Find all of the overloaded operators visible from this
5503 // point. We perform both an operator-name lookup from the local
5504 // scope and an argument-dependent lookup based on the types of
5505 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005506 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00005507 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5508 if (OverOp != OO_None) {
5509 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5510 Functions);
5511 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00005512 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00005513 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005514 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005515 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005516
Douglas Gregor063daf62009-03-13 18:40:31 +00005517 // Build the (potentially-overloaded, potentially-dependent)
5518 // binary operation.
5519 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005520 }
5521
Douglas Gregoreaebc752008-11-06 23:29:22 +00005522 // Build a built-in binary operation.
5523 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00005524}
5525
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005526Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005527 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005528 ExprArg InputArg) {
5529 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00005530
Mike Stump390b4cc2009-05-16 07:39:55 +00005531 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005532 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00005533 QualType resultType;
5534 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005535 case UnaryOperator::OffsetOf:
5536 assert(false && "Invalid unary operator");
5537 break;
5538
Reid Spencer5f016e22007-07-11 17:01:13 +00005539 case UnaryOperator::PreInc:
5540 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00005541 case UnaryOperator::PostInc:
5542 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005543 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00005544 Opc == UnaryOperator::PreInc ||
5545 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005546 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005547 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00005548 resultType = CheckAddressOfOperand(Input, OpLoc);
5549 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005550 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00005551 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00005552 resultType = CheckIndirectionOperand(Input, OpLoc);
5553 break;
5554 case UnaryOperator::Plus:
5555 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005556 UsualUnaryConversions(Input);
5557 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005558 if (resultType->isDependentType())
5559 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005560 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5561 break;
5562 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5563 resultType->isEnumeralType())
5564 break;
5565 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5566 Opc == UnaryOperator::Plus &&
5567 resultType->isPointerType())
5568 break;
5569
Sebastian Redl0eb23302009-01-19 00:08:26 +00005570 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5571 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005572 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005573 UsualUnaryConversions(Input);
5574 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005575 if (resultType->isDependentType())
5576 break;
Chris Lattner02a65142008-07-25 23:52:49 +00005577 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5578 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5579 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005580 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005581 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00005582 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005583 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5584 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005585 break;
5586 case UnaryOperator::LNot: // logical negation
5587 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005588 DefaultFunctionArrayConversion(Input);
5589 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005590 if (resultType->isDependentType())
5591 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005592 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00005593 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5594 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005595 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00005596 // In C++, it's bool. C++ 5.3.1p8
5597 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005598 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00005599 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00005600 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00005601 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00005602 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005603 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00005604 resultType = Input->getType();
5605 break;
5606 }
5607 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005608 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005609
5610 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00005611 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005612}
5613
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005614// Unary Operators. 'Tok' is the token for the operator.
5615Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5616 tok::TokenKind Op, ExprArg input) {
5617 Expr *Input = (Expr*)input.get();
5618 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5619
5620 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5621 // Find all of the overloaded operators visible from this
5622 // point. We perform both an operator-name lookup from the local
5623 // scope and an argument-dependent lookup based on the types of
5624 // the arguments.
5625 FunctionSet Functions;
5626 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5627 if (OverOp != OO_None) {
5628 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5629 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00005630 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005631 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005632 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005633 }
5634
5635 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5636 }
5637
5638 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5639}
5640
Steve Naroff1b273c42007-09-16 14:56:35 +00005641/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00005642Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5643 SourceLocation LabLoc,
5644 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005645 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00005646 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00005647
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00005648 // If we haven't seen this label yet, create a forward reference. It
5649 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00005650 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00005651 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005652
Reid Spencer5f016e22007-07-11 17:01:13 +00005653 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00005654 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5655 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00005656}
5657
Sebastian Redlf53597f2009-03-15 17:47:39 +00005658Sema::OwningExprResult
5659Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5660 SourceLocation RPLoc) { // "({..})"
5661 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005662 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5663 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5664
Eli Friedmandca2b732009-01-24 23:09:00 +00005665 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00005666 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005667 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00005668
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005669 // FIXME: there are a variety of strange constraints to enforce here, for
5670 // example, it is not possible to goto into a stmt expression apparently.
5671 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005672
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005673 // If there are sub stmts in the compound stmt, take the type of the last one
5674 // as the type of the stmtexpr.
5675 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005676
Chris Lattner611b2ec2008-07-26 19:51:01 +00005677 if (!Compound->body_empty()) {
5678 Stmt *LastStmt = Compound->body_back();
5679 // If LastStmt is a label, skip down through into the body.
5680 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5681 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005682
Chris Lattner611b2ec2008-07-26 19:51:01 +00005683 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005684 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00005685 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005686
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005687 // FIXME: Check that expression type is complete/non-abstract; statement
5688 // expressions are not lvalues.
5689
Sebastian Redlf53597f2009-03-15 17:47:39 +00005690 substmt.release();
5691 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005692}
Steve Naroffd34e9152007-08-01 22:05:33 +00005693
Sebastian Redlf53597f2009-03-15 17:47:39 +00005694Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5695 SourceLocation BuiltinLoc,
5696 SourceLocation TypeLoc,
5697 TypeTy *argty,
5698 OffsetOfComponent *CompPtr,
5699 unsigned NumComponents,
5700 SourceLocation RPLoc) {
5701 // FIXME: This function leaks all expressions in the offset components on
5702 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005703 // FIXME: Preserve type source info.
5704 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005705 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005706
Sebastian Redl28507842009-02-26 14:39:58 +00005707 bool Dependent = ArgTy->isDependentType();
5708
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005709 // We must have at least one component that refers to the type, and the first
5710 // one is known to be a field designator. Verify that the ArgTy represents
5711 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00005712 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005713 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005714
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005715 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5716 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00005717
Eli Friedman35183ac2009-02-27 06:44:11 +00005718 // Otherwise, create a null pointer as the base, and iteratively process
5719 // the offsetof designators.
5720 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5721 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005722 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00005723 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00005724
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005725 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5726 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00005727 // FIXME: This diagnostic isn't actually visible because the location is in
5728 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005729 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005730 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5731 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005732
Sebastian Redl28507842009-02-26 14:39:58 +00005733 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00005734 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005735
Sebastian Redl28507842009-02-26 14:39:58 +00005736 // FIXME: Dependent case loses a lot of information here. And probably
5737 // leaks like a sieve.
5738 for (unsigned i = 0; i != NumComponents; ++i) {
5739 const OffsetOfComponent &OC = CompPtr[i];
5740 if (OC.isBrackets) {
5741 // Offset of an array sub-field. TODO: Should we allow vector elements?
5742 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5743 if (!AT) {
5744 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005745 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5746 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005747 }
5748
5749 // FIXME: C++: Verify that operator[] isn't overloaded.
5750
Eli Friedman35183ac2009-02-27 06:44:11 +00005751 // Promote the array so it looks more like a normal array subscript
5752 // expression.
5753 DefaultFunctionArrayConversion(Res);
5754
Sebastian Redl28507842009-02-26 14:39:58 +00005755 // C99 6.5.2.1p1
5756 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005757 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005758 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005759 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00005760 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005761 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00005762
5763 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5764 OC.LocEnd);
5765 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005766 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005767
Ted Kremenek6217b802009-07-29 21:53:49 +00005768 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00005769 if (!RC) {
5770 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005771 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5772 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005773 }
Chris Lattner704fe352007-08-30 17:59:59 +00005774
Sebastian Redl28507842009-02-26 14:39:58 +00005775 // Get the decl corresponding to this.
5776 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005777 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005778 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00005779 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5780 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5781 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005782 DidWarnAboutNonPOD = true;
5783 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005784 }
Mike Stump1eb44332009-09-09 15:08:12 +00005785
John McCallf36e02d2009-10-09 21:13:30 +00005786 LookupResult R;
5787 LookupQualifiedName(R, RD, OC.U.IdentInfo, LookupMemberName);
5788
Sebastian Redl28507842009-02-26 14:39:58 +00005789 FieldDecl *MemberDecl
John McCallf36e02d2009-10-09 21:13:30 +00005790 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redlf53597f2009-03-15 17:47:39 +00005791 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005792 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00005793 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5794 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005795
Sebastian Redl28507842009-02-26 14:39:58 +00005796 // FIXME: C++: Verify that MemberDecl isn't a static field.
5797 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005798 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005799 Res = BuildAnonymousStructUnionMemberReference(
5800 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005801 } else {
5802 // MemberDecl->getType() doesn't get the right qualifiers, but it
5803 // doesn't matter here.
5804 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5805 MemberDecl->getType().getNonReferenceType());
5806 }
Sebastian Redl28507842009-02-26 14:39:58 +00005807 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005808 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005809
Sebastian Redlf53597f2009-03-15 17:47:39 +00005810 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5811 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005812}
5813
5814
Sebastian Redlf53597f2009-03-15 17:47:39 +00005815Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5816 TypeTy *arg1,TypeTy *arg2,
5817 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005818 // FIXME: Preserve type source info.
5819 QualType argT1 = GetTypeFromParser(arg1);
5820 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005821
Steve Naroffd34e9152007-08-01 22:05:33 +00005822 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005823
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005824 if (getLangOptions().CPlusPlus) {
5825 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5826 << SourceRange(BuiltinLoc, RPLoc);
5827 return ExprError();
5828 }
5829
Sebastian Redlf53597f2009-03-15 17:47:39 +00005830 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5831 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005832}
5833
Sebastian Redlf53597f2009-03-15 17:47:39 +00005834Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5835 ExprArg cond,
5836 ExprArg expr1, ExprArg expr2,
5837 SourceLocation RPLoc) {
5838 Expr *CondExpr = static_cast<Expr*>(cond.get());
5839 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5840 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005841
Steve Naroffd04fdd52007-08-03 21:21:27 +00005842 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5843
Sebastian Redl28507842009-02-26 14:39:58 +00005844 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00005845 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005846 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005847 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00005848 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00005849 } else {
5850 // The conditional expression is required to be a constant expression.
5851 llvm::APSInt condEval(32);
5852 SourceLocation ExpLoc;
5853 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00005854 return ExprError(Diag(ExpLoc,
5855 diag::err_typecheck_choose_expr_requires_constant)
5856 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00005857
Sebastian Redl28507842009-02-26 14:39:58 +00005858 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5859 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00005860 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5861 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00005862 }
5863
Sebastian Redlf53597f2009-03-15 17:47:39 +00005864 cond.release(); expr1.release(); expr2.release();
5865 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00005866 resType, RPLoc,
5867 resType->isDependentType(),
5868 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00005869}
5870
Steve Naroff4eb206b2008-09-03 18:15:37 +00005871//===----------------------------------------------------------------------===//
5872// Clang Extensions.
5873//===----------------------------------------------------------------------===//
5874
5875/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00005876void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005877 // Analyze block parameters.
5878 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005879
Steve Naroff4eb206b2008-09-03 18:15:37 +00005880 // Add BSI to CurBlock.
5881 BSI->PrevBlockInfo = CurBlock;
5882 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005883
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005884 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005885 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00005886 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00005887 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00005888 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5889 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005890
Steve Naroff090276f2008-10-10 01:28:17 +00005891 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00005892 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00005893}
5894
Mike Stump98eb8a72009-02-04 22:31:32 +00005895void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00005896 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00005897
5898 if (ParamInfo.getNumTypeObjects() == 0
5899 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005900 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00005901 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5902
Mike Stump4eeab842009-04-28 01:10:27 +00005903 if (T->isArrayType()) {
5904 Diag(ParamInfo.getSourceRange().getBegin(),
5905 diag::err_block_returns_array);
5906 return;
5907 }
5908
Mike Stump98eb8a72009-02-04 22:31:32 +00005909 // The parameter list is optional, if there was none, assume ().
5910 if (!T->isFunctionType())
5911 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5912
5913 CurBlock->hasPrototype = true;
5914 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005915 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005916 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005917 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005918 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005919 // FIXME: remove the attribute.
5920 }
John McCall183700f2009-09-21 23:43:11 +00005921 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00005922
Chris Lattner9097af12009-04-11 19:27:54 +00005923 // Do not allow returning a objc interface by-value.
5924 if (RetTy->isObjCInterfaceType()) {
5925 Diag(ParamInfo.getSourceRange().getBegin(),
5926 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5927 return;
5928 }
Mike Stump98eb8a72009-02-04 22:31:32 +00005929 return;
5930 }
5931
Steve Naroff4eb206b2008-09-03 18:15:37 +00005932 // Analyze arguments to block.
5933 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5934 "Not a function declarator!");
5935 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005936
Steve Naroff090276f2008-10-10 01:28:17 +00005937 CurBlock->hasPrototype = FTI.hasPrototype;
5938 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005939
Steve Naroff4eb206b2008-09-03 18:15:37 +00005940 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5941 // no arguments, not a function that takes a single void argument.
5942 if (FTI.hasPrototype &&
5943 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00005944 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5945 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005946 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00005947 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005948 } else if (FTI.hasPrototype) {
5949 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00005950 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00005951 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005952 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00005953 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00005954 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00005955 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005956 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00005957 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5958 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5959 // If this has an identifier, add it to the scope stack.
5960 if ((*AI)->getIdentifier())
5961 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00005962
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005963 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00005964 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005965 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005966 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005967 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005968 // FIXME: remove the attribute.
5969 }
Mike Stump1eb44332009-09-09 15:08:12 +00005970
Chris Lattner9097af12009-04-11 19:27:54 +00005971 // Analyze the return type.
5972 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00005973 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00005974
Chris Lattner9097af12009-04-11 19:27:54 +00005975 // Do not allow returning a objc interface by-value.
5976 if (RetTy->isObjCInterfaceType()) {
5977 Diag(ParamInfo.getSourceRange().getBegin(),
5978 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5979 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005980 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005981}
5982
5983/// ActOnBlockError - If there is an error parsing a block, this callback
5984/// is invoked to pop the information about the block from the action impl.
5985void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5986 // Ensure that CurBlock is deleted.
5987 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005988
Chris Lattner17a78302009-04-19 05:28:12 +00005989 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5990
Steve Naroff4eb206b2008-09-03 18:15:37 +00005991 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00005992 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005993 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005994 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00005995}
5996
5997/// ActOnBlockStmtExpr - This is called when the body of a block statement
5998/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00005999Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6000 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006001 // If blocks are disabled, emit an error.
6002 if (!LangOpts.Blocks)
6003 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006004
Steve Naroff4eb206b2008-09-03 18:15:37 +00006005 // Ensure that CurBlock is deleted.
6006 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006007
Steve Naroff090276f2008-10-10 01:28:17 +00006008 PopDeclContext();
6009
Steve Naroff4eb206b2008-09-03 18:15:37 +00006010 // Pop off CurBlock, handle nested blocks.
6011 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006012
Steve Naroff4eb206b2008-09-03 18:15:37 +00006013 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006014 if (!BSI->ReturnType.isNull())
6015 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006016
Steve Naroff4eb206b2008-09-03 18:15:37 +00006017 llvm::SmallVector<QualType, 8> ArgTypes;
6018 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6019 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006020
Mike Stump56925862009-07-28 22:04:01 +00006021 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006022 QualType BlockTy;
6023 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006024 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6025 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006026 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006027 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006028 BSI->isVariadic, 0, false, false, 0, 0,
6029 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006030
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006031 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006032 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006033 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006034
Chris Lattner17a78302009-04-19 05:28:12 +00006035 // If needed, diagnose invalid gotos and switches in the block.
6036 if (CurFunctionNeedsScopeChecking)
6037 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6038 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006039
Anders Carlssone9146f22009-05-01 19:49:17 +00006040 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006041 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006042 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6043 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006044}
6045
Sebastian Redlf53597f2009-03-15 17:47:39 +00006046Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6047 ExprArg expr, TypeTy *type,
6048 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006049 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006050 Expr *E = static_cast<Expr*>(expr.get());
6051 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006052
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006053 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006054
6055 // Get the va_list type
6056 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006057 if (VaListType->isArrayType()) {
6058 // Deal with implicit array decay; for example, on x86-64,
6059 // va_list is an array, but it's supposed to decay to
6060 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006061 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006062 // Make sure the input expression also decays appropriately.
6063 UsualUnaryConversions(E);
6064 } else {
6065 // Otherwise, the va_list argument must be an l-value because
6066 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006067 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006068 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006069 return ExprError();
6070 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006071
Douglas Gregordd027302009-05-19 23:10:31 +00006072 if (!E->isTypeDependent() &&
6073 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006074 return ExprError(Diag(E->getLocStart(),
6075 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006076 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006077 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006078
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006079 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006080 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006081
Sebastian Redlf53597f2009-03-15 17:47:39 +00006082 expr.release();
6083 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6084 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006085}
6086
Sebastian Redlf53597f2009-03-15 17:47:39 +00006087Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006088 // The type of __null will be int or long, depending on the size of
6089 // pointers on the target.
6090 QualType Ty;
6091 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6092 Ty = Context.IntTy;
6093 else
6094 Ty = Context.LongTy;
6095
Sebastian Redlf53597f2009-03-15 17:47:39 +00006096 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006097}
6098
Chris Lattner5cf216b2008-01-04 18:04:52 +00006099bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6100 SourceLocation Loc,
6101 QualType DstType, QualType SrcType,
6102 Expr *SrcExpr, const char *Flavor) {
6103 // Decode the result (notice that AST's are still created for extensions).
6104 bool isInvalid = false;
6105 unsigned DiagKind;
6106 switch (ConvTy) {
6107 default: assert(0 && "Unknown conversion type");
6108 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006109 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006110 DiagKind = diag::ext_typecheck_convert_pointer_int;
6111 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006112 case IntToPointer:
6113 DiagKind = diag::ext_typecheck_convert_int_pointer;
6114 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006115 case IncompatiblePointer:
6116 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6117 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006118 case IncompatiblePointerSign:
6119 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6120 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006121 case FunctionVoidPointer:
6122 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6123 break;
6124 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006125 // If the qualifiers lost were because we were applying the
6126 // (deprecated) C++ conversion from a string literal to a char*
6127 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6128 // Ideally, this check would be performed in
6129 // CheckPointerTypesForAssignment. However, that would require a
6130 // bit of refactoring (so that the second argument is an
6131 // expression, rather than a type), which should be done as part
6132 // of a larger effort to fix CheckPointerTypesForAssignment for
6133 // C++ semantics.
6134 if (getLangOptions().CPlusPlus &&
6135 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6136 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006137 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6138 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006139 case IntToBlockPointer:
6140 DiagKind = diag::err_int_to_block_pointer;
6141 break;
6142 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006143 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006144 break;
Steve Naroff39579072008-10-14 22:18:38 +00006145 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006146 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006147 // it can give a more specific diagnostic.
6148 DiagKind = diag::warn_incompatible_qualified_id;
6149 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006150 case IncompatibleVectors:
6151 DiagKind = diag::warn_incompatible_vectors;
6152 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006153 case Incompatible:
6154 DiagKind = diag::err_typecheck_convert_incompatible;
6155 isInvalid = true;
6156 break;
6157 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006158
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006159 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
6160 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00006161 return isInvalid;
6162}
Anders Carlssone21555e2008-11-30 19:50:32 +00006163
Chris Lattner3bf68932009-04-25 21:59:05 +00006164bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006165 llvm::APSInt ICEResult;
6166 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6167 if (Result)
6168 *Result = ICEResult;
6169 return false;
6170 }
6171
Anders Carlssone21555e2008-11-30 19:50:32 +00006172 Expr::EvalResult EvalResult;
6173
Mike Stumpeed9cac2009-02-19 03:04:26 +00006174 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006175 EvalResult.HasSideEffects) {
6176 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6177
6178 if (EvalResult.Diag) {
6179 // We only show the note if it's not the usual "invalid subexpression"
6180 // or if it's actually in a subexpression.
6181 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6182 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6183 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6184 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006185
Anders Carlssone21555e2008-11-30 19:50:32 +00006186 return true;
6187 }
6188
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006189 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6190 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006191
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006192 if (EvalResult.Diag &&
6193 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6194 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006195
Anders Carlssone21555e2008-11-30 19:50:32 +00006196 if (Result)
6197 *Result = EvalResult.Val.getInt();
6198 return false;
6199}
Douglas Gregore0762c92009-06-19 23:52:42 +00006200
Mike Stump1eb44332009-09-09 15:08:12 +00006201Sema::ExpressionEvaluationContext
6202Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006203 // Introduce a new set of potentially referenced declarations to the stack.
6204 if (NewContext == PotentiallyPotentiallyEvaluated)
6205 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump1eb44332009-09-09 15:08:12 +00006206
Douglas Gregorac7610d2009-06-22 20:57:11 +00006207 std::swap(ExprEvalContext, NewContext);
6208 return NewContext;
6209}
6210
Mike Stump1eb44332009-09-09 15:08:12 +00006211void
Douglas Gregorac7610d2009-06-22 20:57:11 +00006212Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6213 ExpressionEvaluationContext NewContext) {
6214 ExprEvalContext = NewContext;
6215
6216 if (OldContext == PotentiallyPotentiallyEvaluated) {
6217 // Mark any remaining declarations in the current position of the stack
6218 // as "referenced". If they were not meant to be referenced, semantic
6219 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6220 PotentiallyReferencedDecls RemainingDecls;
6221 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6222 PotentiallyReferencedDeclStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00006223
Douglas Gregorac7610d2009-06-22 20:57:11 +00006224 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6225 IEnd = RemainingDecls.end();
6226 I != IEnd; ++I)
6227 MarkDeclarationReferenced(I->first, I->second);
6228 }
6229}
Douglas Gregore0762c92009-06-19 23:52:42 +00006230
6231/// \brief Note that the given declaration was referenced in the source code.
6232///
6233/// This routine should be invoke whenever a given declaration is referenced
6234/// in the source code, and where that reference occurred. If this declaration
6235/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6236/// C99 6.9p3), then the declaration will be marked as used.
6237///
6238/// \param Loc the location where the declaration was referenced.
6239///
6240/// \param D the declaration that has been referenced by the source code.
6241void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6242 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006243
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006244 if (D->isUsed())
6245 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006246
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006247 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6248 // template or not. The reason for this is that unevaluated expressions
6249 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6250 // -Wunused-parameters)
6251 if (isa<ParmVarDecl>(D) ||
6252 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006253 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006254
Douglas Gregore0762c92009-06-19 23:52:42 +00006255 // Do not mark anything as "used" within a dependent context; wait for
6256 // an instantiation.
6257 if (CurContext->isDependentContext())
6258 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006259
Douglas Gregorac7610d2009-06-22 20:57:11 +00006260 switch (ExprEvalContext) {
6261 case Unevaluated:
6262 // We are in an expression that is not potentially evaluated; do nothing.
6263 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006264
Douglas Gregorac7610d2009-06-22 20:57:11 +00006265 case PotentiallyEvaluated:
6266 // We are in a potentially-evaluated expression, so this declaration is
6267 // "used"; handle this below.
6268 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006269
Douglas Gregorac7610d2009-06-22 20:57:11 +00006270 case PotentiallyPotentiallyEvaluated:
6271 // We are in an expression that may be potentially evaluated; queue this
6272 // declaration reference until we know whether the expression is
6273 // potentially evaluated.
6274 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6275 return;
6276 }
Mike Stump1eb44332009-09-09 15:08:12 +00006277
Douglas Gregore0762c92009-06-19 23:52:42 +00006278 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006279 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006280 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006281 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6282 if (!Constructor->isUsed())
6283 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006284 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006285 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006286 if (!Constructor->isUsed())
6287 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6288 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006289 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6290 if (Destructor->isImplicit() && !Destructor->isUsed())
6291 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006292
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006293 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6294 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6295 MethodDecl->getOverloadedOperator() == OO_Equal) {
6296 if (!MethodDecl->isUsed())
6297 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6298 }
6299 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006300 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006301 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006302 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006303 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006304 bool AlreadyInstantiated = false;
6305 if (FunctionTemplateSpecializationInfo *SpecInfo
6306 = Function->getTemplateSpecializationInfo()) {
6307 if (SpecInfo->getPointOfInstantiation().isInvalid())
6308 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006309 else if (SpecInfo->getTemplateSpecializationKind()
6310 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006311 AlreadyInstantiated = true;
6312 } else if (MemberSpecializationInfo *MSInfo
6313 = Function->getMemberSpecializationInfo()) {
6314 if (MSInfo->getPointOfInstantiation().isInvalid())
6315 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006316 else if (MSInfo->getTemplateSpecializationKind()
6317 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006318 AlreadyInstantiated = true;
6319 }
6320
6321 if (!AlreadyInstantiated)
6322 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6323 }
6324
Douglas Gregore0762c92009-06-19 23:52:42 +00006325 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006326 Function->setUsed(true);
6327 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006328 }
Mike Stump1eb44332009-09-09 15:08:12 +00006329
Douglas Gregore0762c92009-06-19 23:52:42 +00006330 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006331 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006332 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006333 Var->getInstantiatedFromStaticDataMember()) {
6334 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6335 assert(MSInfo && "Missing member specialization information?");
6336 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6337 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6338 MSInfo->setPointOfInstantiation(Loc);
6339 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6340 }
6341 }
Mike Stump1eb44332009-09-09 15:08:12 +00006342
Douglas Gregore0762c92009-06-19 23:52:42 +00006343 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006344
Douglas Gregore0762c92009-06-19 23:52:42 +00006345 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006346 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006347 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006348}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006349
6350bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6351 CallExpr *CE, FunctionDecl *FD) {
6352 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6353 return false;
6354
6355 PartialDiagnostic Note =
6356 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6357 << FD->getDeclName() : PDiag();
6358 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6359
6360 if (RequireCompleteType(Loc, ReturnType,
6361 FD ?
6362 PDiag(diag::err_call_function_incomplete_return)
6363 << CE->getSourceRange() << FD->getDeclName() :
6364 PDiag(diag::err_call_incomplete_return)
6365 << CE->getSourceRange(),
6366 std::make_pair(NoteLoc, Note)))
6367 return true;
6368
6369 return false;
6370}
6371
John McCall5a881bb2009-10-12 21:59:07 +00006372// Diagnose the common s/=/==/ typo. Note that adding parentheses
6373// will prevent this condition from triggering, which is what we want.
6374void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6375 SourceLocation Loc;
6376
6377 if (isa<BinaryOperator>(E)) {
6378 BinaryOperator *Op = cast<BinaryOperator>(E);
6379 if (Op->getOpcode() != BinaryOperator::Assign)
6380 return;
6381
6382 Loc = Op->getOperatorLoc();
6383 } else if (isa<CXXOperatorCallExpr>(E)) {
6384 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6385 if (Op->getOperator() != OO_Equal)
6386 return;
6387
6388 Loc = Op->getOperatorLoc();
6389 } else {
6390 // Not an assignment.
6391 return;
6392 }
6393
John McCall5a881bb2009-10-12 21:59:07 +00006394 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00006395 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00006396
6397 Diag(Loc, diag::warn_condition_is_assignment)
6398 << E->getSourceRange()
6399 << CodeModificationHint::CreateInsertion(Open, "(")
6400 << CodeModificationHint::CreateInsertion(Close, ")");
6401}
6402
6403bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6404 DiagnoseAssignmentAsCondition(E);
6405
6406 if (!E->isTypeDependent()) {
6407 DefaultFunctionArrayConversion(E);
6408
6409 QualType T = E->getType();
6410
6411 if (getLangOptions().CPlusPlus) {
6412 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6413 return true;
6414 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6415 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6416 << T << E->getSourceRange();
6417 return true;
6418 }
6419 }
6420
6421 return false;
6422}