blob: 70e137462f46f1ba852d8babd27706b00160c075 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000028using namespace clang;
29
David Chisnall9f57c292009-08-17 16:35:33 +000030
Douglas Gregor171c45a2009-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///
40/// \returns true if there was an error (this declaration cannot be
41/// referenced), false otherwise.
42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000043 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000044 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000045 // Implementing deprecated stuff requires referencing deprecated
46 // stuff. Don't warn if we are implementing a deprecated
47 // construct.
Chris Lattner46d6b132009-02-16 19:35:30 +000048 bool isSilenced = false;
Mike Stump11289f42009-09-09 15:08:12 +000049
Chris Lattner46d6b132009-02-16 19:35:30 +000050 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
51 // If this reference happens *in* a deprecated function or method, don't
52 // warn.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000053 isSilenced = ND->getAttr<DeprecatedAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000054
Chris Lattner46d6b132009-02-16 19:35:30 +000055 // If this is an Objective-C method implementation, check to see if the
56 // method was deprecated on the declaration, not the definition.
57 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
58 // The semantic decl context of a ObjCMethodDecl is the
59 // ObjCImplementationDecl.
60 if (ObjCImplementationDecl *Impl
61 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
Mike Stump11289f42009-09-09 15:08:12 +000062
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000063 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattner46d6b132009-02-16 19:35:30 +000064 MD->isInstanceMethod());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000065 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattner46d6b132009-02-16 19:35:30 +000066 }
67 }
68 }
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattner46d6b132009-02-16 19:35:30 +000070 if (!isSilenced)
Chris Lattner4bf74fd2009-02-15 22:43:40 +000071 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
72 }
73
Douglas Gregor171c45a2009-02-18 21:56:37 +000074 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000075 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000076 if (FD->isDeleted()) {
77 Diag(Loc, diag::err_deleted_function_use);
78 Diag(D->getLocation(), diag::note_unavailable_here) << true;
79 return true;
80 }
Douglas Gregorde681d42009-02-24 04:26:15 +000081 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000082
83 // See if the decl is unavailable
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000084 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000085 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregor171c45a2009-02-18 21:56:37 +000086 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
87 }
88
Douglas Gregor171c45a2009-02-18 21:56:37 +000089 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000090}
91
Fariborz Jahanian027b8862009-05-13 18:09:35 +000092/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000093/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000094/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000097 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000099 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000100 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000103
Mike Stump87c57ac2009-05-16 07:39:55 +0000104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000107 bool warnNotEnoughArgs = false;
108 int isMethod = 0;
109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = MD->param_end();
112 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
119 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000120 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000121 // skip over named parameters.
122 ObjCMethodDecl::param_iterator P, E = FD->param_end();
123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124 if (nullPos)
125 --nullPos;
126 else
127 ++i;
128 }
129 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000130 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000131 // block or function pointer call.
132 QualType Ty = V->getType();
133 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000134 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000135 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000137 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138 unsigned NumArgsInProto = Proto->getNumArgs();
139 unsigned k;
140 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141 if (nullPos)
142 --nullPos;
143 else
144 ++i;
145 }
146 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147 }
148 if (Ty->isBlockPointerType())
149 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000150 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000151 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000152 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000153 return;
154
155 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000158 return;
159 }
160 int sentinel = i;
161 while (sentinelPos > 0 && i < NumArgs-1) {
162 --sentinelPos;
163 ++i;
164 }
165 if (sentinelPos > 0) {
166 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000168 return;
169 }
170 while (i < NumArgs-1) {
171 ++i;
172 ++sentinel;
173 }
174 Expr *sentinelExpr = Args[sentinel];
175 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000177 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000178 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000179 }
180 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000181}
182
Douglas Gregor87f95b02009-02-26 21:00:50 +0000183SourceRange Sema::getExprRange(ExprTy *E) const {
184 Expr *Ex = (Expr *)E;
185 return Ex? Ex->getSourceRange() : SourceRange();
186}
187
Chris Lattner513165e2008-07-25 21:10:04 +0000188//===----------------------------------------------------------------------===//
189// Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
Chris Lattner513165e2008-07-25 21:10:04 +0000192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194 QualType Ty = E->getType();
195 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
Chris Lattner513165e2008-07-25 21:10:04 +0000197 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000198 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000199 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000200 else if (Ty->isArrayType()) {
201 // In C90 mode, arrays only promote to pointers if the array expression is
202 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
203 // type 'array of type' is converted to an expression that has type 'pointer
204 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
205 // that has type 'array of type' ...". The relevant change is "an lvalue"
206 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000207 //
208 // C++ 4.2p1:
209 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
210 // T" can be converted to an rvalue of type "pointer to T".
211 //
212 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
213 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000214 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
215 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000216 }
Chris Lattner513165e2008-07-25 21:10:04 +0000217}
218
219/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000220/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000221/// sometimes surpressed. For example, the array->pointer conversion doesn't
222/// apply if the array is an argument to the sizeof or address (&) operators.
223/// In these instances, this routine should *not* be called.
224Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
225 QualType Ty = Expr->getType();
226 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000227
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000228 // C99 6.3.1.1p2:
229 //
230 // The following may be used in an expression wherever an int or
231 // unsigned int may be used:
232 // - an object or expression with an integer type whose integer
233 // conversion rank is less than or equal to the rank of int
234 // and unsigned int.
235 // - A bit-field of type _Bool, int, signed int, or unsigned int.
236 //
237 // If an int can represent all values of the original type, the
238 // value is converted to an int; otherwise, it is converted to an
239 // unsigned int. These are called the integer promotions. All
240 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000241 QualType PTy = Context.isPromotableBitField(Expr);
242 if (!PTy.isNull()) {
243 ImpCastExprToType(Expr, PTy);
244 return Expr;
245 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000246 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000247 QualType PT = Context.getPromotedIntegerType(Ty);
248 ImpCastExprToType(Expr, PT);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000249 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000250 }
251
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000252 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000253 return Expr;
254}
255
Chris Lattner2ce500f2008-07-25 22:25:12 +0000256/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000257/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000258/// double. All other argument types are converted by UsualUnaryConversions().
259void Sema::DefaultArgumentPromotion(Expr *&Expr) {
260 QualType Ty = Expr->getType();
261 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000262
Chris Lattner2ce500f2008-07-25 22:25:12 +0000263 // If this is a 'float' (CVR qualified or typedef) promote to double.
264 if (const BuiltinType *BT = Ty->getAsBuiltinType())
265 if (BT->getKind() == BuiltinType::Float)
266 return ImpCastExprToType(Expr, Context.DoubleTy);
Mike Stump11289f42009-09-09 15:08:12 +0000267
Chris Lattner2ce500f2008-07-25 22:25:12 +0000268 UsualUnaryConversions(Expr);
269}
270
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000271/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
272/// will warn if the resulting type is not a POD type, and rejects ObjC
273/// interfaces passed by value. This returns true if the argument type is
274/// completely illegal.
275bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000276 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000278 if (Expr->getType()->isObjCInterfaceType()) {
279 Diag(Expr->getLocStart(),
280 diag::err_cannot_pass_objc_interface_to_vararg)
281 << Expr->getType() << CT;
282 return true;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000283 }
Mike Stump11289f42009-09-09 15:08:12 +0000284
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000285 if (!Expr->getType()->isPODType())
286 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
287 << Expr->getType() << CT;
288
289 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000290}
291
292
Chris Lattner513165e2008-07-25 21:10:04 +0000293/// UsualArithmeticConversions - Performs various conversions that are common to
294/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000295/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000296/// responsible for emitting appropriate error diagnostics.
297/// FIXME: verify the conversion rules for "complex int" are consistent with
298/// GCC.
299QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
300 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000301 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000302 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000303
304 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000305
Mike Stump11289f42009-09-09 15:08:12 +0000306 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000307 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000308 QualType lhs =
309 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000310 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000311 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000312
313 // If both types are identical, no conversion is needed.
314 if (lhs == rhs)
315 return lhs;
316
317 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
318 // The caller can deal with this (e.g. pointer + int).
319 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
320 return lhs;
321
Douglas Gregord2c2d172009-05-02 00:36:19 +0000322 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000323 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000324 if (!LHSBitfieldPromoteTy.isNull())
325 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000326 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000327 if (!RHSBitfieldPromoteTy.isNull())
328 rhs = RHSBitfieldPromoteTy;
329
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000330 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000331 if (!isCompAssign)
Douglas Gregora11693b2008-11-12 17:17:38 +0000332 ImpCastExprToType(lhsExpr, destType);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000333 ImpCastExprToType(rhsExpr, destType);
Douglas Gregora11693b2008-11-12 17:17:38 +0000334 return destType;
335}
336
Chris Lattner513165e2008-07-25 21:10:04 +0000337//===----------------------------------------------------------------------===//
338// Semantic Analysis for various Expression Types
339//===----------------------------------------------------------------------===//
340
341
Steve Naroff83895f72007-09-16 03:34:24 +0000342/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000343/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
344/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
345/// multiple tokens. However, the common case is that StringToks points to one
346/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000347///
348Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000349Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000350 assert(NumStringToks && "Must have at least one string!");
351
Chris Lattner8a24e582009-01-16 18:51:42 +0000352 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000353 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000354 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000355
Chris Lattner23b7eb62007-06-15 23:05:46 +0000356 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000357 for (unsigned i = 0; i != NumStringToks; ++i)
358 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000359
Chris Lattner36fc8792008-02-11 00:02:17 +0000360 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000361 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000362 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000363
364 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
365 if (getLangOptions().CPlusPlus)
366 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000367
Chris Lattner36fc8792008-02-11 00:02:17 +0000368 // Get an array type for the string, according to C99 6.4.5. This includes
369 // the nul terminator character as well as the string length for pascal
370 // strings.
371 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000372 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000373 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000374
Chris Lattner5b183d82006-11-10 05:03:26 +0000375 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000376 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000377 Literal.GetStringLength(),
378 Literal.AnyWide, StrTy,
379 &StringTokLocs[0],
380 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000381}
382
Chris Lattner2a9d9892008-10-20 05:16:36 +0000383/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
384/// CurBlock to VD should cause it to be snapshotted (as we do for auto
385/// variables defined outside the block) or false if this is not needed (e.g.
386/// for values inside the block or for globals).
387///
Chris Lattner497d7b02009-04-21 22:26:47 +0000388/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
389/// up-to-date.
390///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000391static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
392 ValueDecl *VD) {
393 // If the value is defined inside the block, we couldn't snapshot it even if
394 // we wanted to.
395 if (CurBlock->TheDecl == VD->getDeclContext())
396 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000397
Chris Lattner2a9d9892008-10-20 05:16:36 +0000398 // If this is an enum constant or function, it is constant, don't snapshot.
399 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
400 return false;
401
402 // If this is a reference to an extern, static, or global variable, no need to
403 // snapshot it.
404 // FIXME: What about 'const' variables in C++?
405 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000406 if (!Var->hasLocalStorage())
407 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattner497d7b02009-04-21 22:26:47 +0000409 // Blocks that have these can't be constant.
410 CurBlock->hasBlockDeclRefExprs = true;
411
412 // If we have nested blocks, the decl may be declared in an outer block (in
413 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
414 // be defined outside all of the current blocks (in which case the blocks do
415 // all get the bit). Walk the nesting chain.
416 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
417 NextBlock = NextBlock->PrevBlockInfo) {
418 // If we found the defining block for the variable, don't mark the block as
419 // having a reference outside it.
420 if (NextBlock->TheDecl == VD->getDeclContext())
421 break;
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chris Lattner497d7b02009-04-21 22:26:47 +0000423 // Otherwise, the DeclRef from the inner block causes the outer one to need
424 // a snapshot as well.
425 NextBlock->hasBlockDeclRefExprs = true;
426 }
Mike Stump11289f42009-09-09 15:08:12 +0000427
Chris Lattner2a9d9892008-10-20 05:16:36 +0000428 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000429}
430
Chris Lattner2a9d9892008-10-20 05:16:36 +0000431
432
Steve Naroff30d242c2007-09-15 18:49:24 +0000433/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattnerac18be92006-11-20 06:49:47 +0000434/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff157c4032008-03-19 23:46:26 +0000435/// identifier is used in a function call context.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000436/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000437/// class or namespace that the identifier must be a member of.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000438Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
439 IdentifierInfo &II,
440 bool HasTrailingLParen,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000441 const CXXScopeSpec *SS,
442 bool isAddressOfOperand) {
443 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregorb8a9a412009-02-04 15:01:18 +0000444 isAddressOfOperand);
Douglas Gregor4ea80432008-11-18 15:03:34 +0000445}
446
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000447/// BuildDeclRefExpr - Build either a DeclRefExpr or a
448/// QualifiedDeclRefExpr based on whether or not SS is a
449/// nested-name-specifier.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000450Sema::OwningExprResult
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000451Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
452 bool TypeDependent, bool ValueDependent,
453 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000454 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
455 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000456 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000457 << D->getDeclName();
458 return ExprError();
459 }
Mike Stump11289f42009-09-09 15:08:12 +0000460
Anders Carlsson946b86d2009-06-24 00:10:43 +0000461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
462 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
463 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
464 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000465 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000466 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000467 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000468 << D->getIdentifier();
469 return ExprError();
470 }
471 }
472 }
473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000475 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000476
Anders Carlsson946b86d2009-06-24 00:10:43 +0000477 Expr *E;
Douglas Gregor18353912009-03-19 03:51:16 +0000478 if (SS && !SS->isEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +0000479 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Anders Carlsson946b86d2009-06-24 00:10:43 +0000480 ValueDependent, SS->getRange(),
Douglas Gregorc23500e2009-03-26 23:56:24 +0000481 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor18353912009-03-19 03:51:16 +0000482 } else
Anders Carlsson946b86d2009-06-24 00:10:43 +0000483 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Mike Stump11289f42009-09-09 15:08:12 +0000484
Anders Carlsson946b86d2009-06-24 00:10:43 +0000485 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000486}
487
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000488/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
489/// variable corresponding to the anonymous union or struct whose type
490/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000491static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
492 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000493 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000494 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000495
Mike Stump87c57ac2009-05-16 07:39:55 +0000496 // FIXME: Once Decls are directly linked together, this will be an O(1)
497 // operation rather than a slow walk through DeclContext's vector (which
498 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000499 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000500 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000501 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000502 D != DEnd; ++D) {
503 if (*D == Record) {
504 // The object for the anonymous struct/union directly
505 // follows its type in the list of declarations.
506 ++D;
507 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000508 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000509 return *D;
510 }
511 }
512
513 assert(false && "Missing object for anonymous record");
514 return 0;
515}
516
Douglas Gregord5846a12009-04-15 06:41:24 +0000517/// \brief Given a field that represents a member of an anonymous
518/// struct/union, build the path from that field's context to the
519/// actual member.
520///
521/// Construct the sequence of field member references we'll have to
522/// perform to get to the field in the anonymous union/struct. The
523/// list of members is built from the field outward, so traverse it
524/// backwards to go from an object in the current context to the field
525/// we found.
526///
527/// \returns The variable from which the field access should begin,
528/// for an anonymous struct/union that is not a member of another
529/// class. Otherwise, returns NULL.
530VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
531 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000532 assert(Field->getDeclContext()->isRecord() &&
533 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
534 && "Field must be stored inside an anonymous struct or union");
535
Douglas Gregord5846a12009-04-15 06:41:24 +0000536 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000537 VarDecl *BaseObject = 0;
538 DeclContext *Ctx = Field->getDeclContext();
539 do {
540 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000541 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000542 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000543 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000544 else {
545 BaseObject = cast<VarDecl>(AnonObject);
546 break;
547 }
548 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000549 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000550 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000551
552 return BaseObject;
553}
554
555Sema::OwningExprResult
556Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
557 FieldDecl *Field,
558 Expr *BaseObjectExpr,
559 SourceLocation OpLoc) {
560 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000561 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000562 AnonFields);
563
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000564 // Build the expression that refers to the base object, from
565 // which we will build a sequence of member references to each
566 // of the anonymous union objects and, eventually, the field we
567 // found via name lookup.
568 bool BaseObjectIsPointer = false;
569 unsigned ExtraQuals = 0;
570 if (BaseObject) {
571 // BaseObject is an anonymous struct/union variable (and is,
572 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000573 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000574 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000575 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000576 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000577 ExtraQuals
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000578 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
579 } else if (BaseObjectExpr) {
580 // The caller provided the base object expression. Determine
581 // whether its a pointer and whether it adds any qualifiers to the
582 // anonymous struct/union fields we're looking into.
583 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000584 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000585 BaseObjectIsPointer = true;
586 ObjectType = ObjectPtr->getPointeeType();
587 }
588 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
589 } else {
590 // We've found a member of an anonymous struct/union that is
591 // inside a non-anonymous struct/union, so in a well-formed
592 // program our base object expression is "this".
593 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
594 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000595 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000596 = Context.getTagDeclType(
597 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
598 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000599 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000600 == Context.getCanonicalType(ThisType)) ||
601 IsDerivedFrom(ThisType, AnonFieldType)) {
602 // Our base object expression is "this".
Steve Narofff6009ed2009-01-21 00:14:39 +0000603 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000604 MD->getThisType(Context));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000605 BaseObjectIsPointer = true;
606 }
607 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000608 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
609 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000610 }
611 ExtraQuals = MD->getTypeQualifiers();
612 }
613
Mike Stump11289f42009-09-09 15:08:12 +0000614 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000615 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
616 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000617 }
618
619 // Build the implicit member references to the field of the
620 // anonymous struct/union.
621 Expr *Result = BaseObjectExpr;
Mon P Wangacedf772009-07-22 03:08:17 +0000622 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000623 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
624 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
625 FI != FIEnd; ++FI) {
626 QualType MemberType = (*FI)->getType();
627 if (!(*FI)->isMutable()) {
Mike Stump11289f42009-09-09 15:08:12 +0000628 unsigned combinedQualifiers
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000629 = MemberType.getCVRQualifiers() | ExtraQuals;
630 MemberType = MemberType.getQualifiedType(combinedQualifiers);
631 }
Mon P Wangacedf772009-07-22 03:08:17 +0000632 if (BaseAddrSpace != MemberType.getAddressSpace())
633 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000634 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000635 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000636 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
637 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000638 BaseObjectIsPointer = false;
639 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000640 }
641
Sebastian Redlffbcf962009-01-18 18:53:16 +0000642 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000643}
644
Douglas Gregor4ea80432008-11-18 15:03:34 +0000645/// ActOnDeclarationNameExpr - The parser has read some kind of name
646/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
647/// performs lookup on that name and returns an expression that refers
648/// to that name. This routine isn't directly called from the parser,
649/// because the parser doesn't know about DeclarationName. Rather,
650/// this routine is called by ActOnIdentifierExpr,
651/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
652/// which form the DeclarationName from the corresponding syntactic
653/// forms.
654///
655/// HasTrailingLParen indicates whether this identifier is used in a
656/// function call context. LookupCtx is only used for a C++
657/// qualified-id (foo::bar) to indicate the class or namespace that
658/// the identifier must be a member of.
Douglas Gregorb0846b02008-12-06 00:22:45 +0000659///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000660/// isAddressOfOperand means that this expression is the direct operand
661/// of an address-of operator. This matters because this is the only
662/// situation where a qualified name referencing a non-static member may
663/// appear outside a member function of this class.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000664Sema::OwningExprResult
665Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
666 DeclarationName Name, bool HasTrailingLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000667 const CXXScopeSpec *SS,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000668 bool isAddressOfOperand) {
Chris Lattner59a25942008-03-31 00:36:02 +0000669 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregored8f2882009-01-30 01:04:22 +0000670 if (SS && SS->isInvalid())
671 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +0000672
673 // C++ [temp.dep.expr]p3:
674 // An id-expression is type-dependent if it contains:
675 // -- a nested-name-specifier that contains a class-name that
676 // names a dependent type.
Douglas Gregor82dbbd72009-05-29 14:49:33 +0000677 // FIXME: Member of the current instantiation.
Douglas Gregor90a1a652009-03-19 17:26:29 +0000678 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregorf21eb492009-03-26 23:50:42 +0000679 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
Mike Stump11289f42009-09-09 15:08:12 +0000680 Loc, SS->getRange(),
Anders Carlsson03f89b12009-07-09 00:05:08 +0000681 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
682 isAddressOfOperand));
Douglas Gregor90a1a652009-03-19 17:26:29 +0000683 }
684
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000685 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
686 false, true, Loc);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000687
Sebastian Redlffbcf962009-01-18 18:53:16 +0000688 if (Lookup.isAmbiguous()) {
689 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
690 SS && SS->isSet() ? SS->getRange()
691 : SourceRange());
692 return ExprError();
Chris Lattnercd2a8c52009-04-24 22:30:50 +0000693 }
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattnercd2a8c52009-04-24 22:30:50 +0000695 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregorb0846b02008-12-06 00:22:45 +0000696
Chris Lattner59a25942008-03-31 00:36:02 +0000697 // If this reference is in an Objective-C method, then ivar lookup happens as
698 // well.
Douglas Gregor4ea80432008-11-18 15:03:34 +0000699 IdentifierInfo *II = Name.getAsIdentifierInfo();
700 if (II && getCurMethodDecl()) {
Chris Lattner59a25942008-03-31 00:36:02 +0000701 // There are two cases to handle here. 1) scoped lookup could have failed,
702 // in which case we should look for an ivar. 2) scoped lookup could have
Mike Stump11289f42009-09-09 15:08:12 +0000703 // found a decl, but that decl is outside the current instance method (i.e.
704 // a global variable). In these two cases, we do a lookup for an ivar with
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000705 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000706 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000707 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000708 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000709 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner50afe312009-02-16 17:19:12 +0000710 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor171c45a2009-02-18 21:56:37 +0000711 if (DiagnoseUseOfDecl(IV, Loc))
712 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000713
Chris Lattnercd2a8c52009-04-24 22:30:50 +0000714 // If we're referencing an invalid decl, just return this as a silent
715 // error node. The error diagnostic was already emitted on the decl.
716 if (IV->isInvalidDecl())
717 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000718
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000719 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
720 // If a class method attemps to use a free standing ivar, this is
721 // an error.
722 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
723 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
724 << IV->getDeclName());
725 // If a class method uses a global variable, even if an ivar with
726 // same name exists, use the global.
727 if (!IsClsMethod) {
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000728 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
729 ClassDeclared != IFace)
730 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stump87c57ac2009-05-16 07:39:55 +0000731 // FIXME: This should use a new expr for a direct reference, don't
732 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000733 IdentifierInfo &II = Context.Idents.get("self");
Argyrios Kyrtzidise1a8c622009-07-18 08:49:37 +0000734 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
735 II, false);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000736 MarkDeclarationReferenced(Loc, IV);
Mike Stump11289f42009-09-09 15:08:12 +0000737 return Owned(new (Context)
738 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000739 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000740 }
Chris Lattner59a25942008-03-31 00:36:02 +0000741 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000742 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000743 // We should warn if a local variable hides an ivar.
744 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000745 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000746 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000747 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
748 IFace == ClassDeclared)
Chris Lattnercd2a8c52009-04-24 22:30:50 +0000749 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000750 }
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000751 }
Steve Naroff0d7c6db2008-08-10 19:10:41 +0000752 // Needed to implement property "super.method" notation.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000753 if (D == 0 && II->isStr("super")) {
Steve Naroffe29c4dd2009-03-05 20:12:00 +0000754 QualType T;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Steve Naroffe29c4dd2009-03-05 20:12:00 +0000756 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff7cae42b2009-07-10 23:34:53 +0000757 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
758 getCurMethodDecl()->getClassInterface()));
Steve Naroffe29c4dd2009-03-05 20:12:00 +0000759 else
760 T = Context.getObjCClassType();
Steve Narofff6009ed2009-01-21 00:14:39 +0000761 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffebf4cb42008-06-02 23:03:37 +0000762 }
Chris Lattner59a25942008-03-31 00:36:02 +0000763 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000764
Douglas Gregor171c45a2009-02-18 21:56:37 +0000765 // Determine whether this name might be a candidate for
766 // argument-dependent lookup.
Mike Stump11289f42009-09-09 15:08:12 +0000767 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor171c45a2009-02-18 21:56:37 +0000768 HasTrailingLParen;
769
770 if (ADL && D == 0) {
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000771 // We've seen something of the form
772 //
773 // identifier(
774 //
775 // and we did not find any entity by the name
776 // "identifier". However, this identifier is still subject to
777 // argument-dependent lookup, so keep track of the name.
778 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
779 Context.OverloadTy,
780 Loc));
781 }
782
Chris Lattner17ed4872006-11-20 04:58:19 +0000783 if (D == 0) {
Bill Wendling4073ed52007-02-13 01:51:42 +0000784 // Otherwise, this could be an implicitly declared function reference (legal
Chris Lattner9561a0b2007-01-28 08:20:04 +0000785 // in C90, extension in C99).
Douglas Gregor4ea80432008-11-18 15:03:34 +0000786 if (HasTrailingLParen && II &&
Chris Lattner59a25942008-03-31 00:36:02 +0000787 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor4ea80432008-11-18 15:03:34 +0000788 D = ImplicitlyDefineFunction(Loc, *II, S);
Steve Naroff92e30f82007-04-02 22:35:25 +0000789 else {
Chris Lattnerac18be92006-11-20 06:49:47 +0000790 // If this name wasn't predeclared and if this is not a function call,
791 // diagnose the problem.
Anders Carlsson896c2302009-08-30 00:54:35 +0000792 if (SS && !SS->isEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +0000793 DiagnoseMissingMember(Loc, Name,
Anders Carlsson896c2302009-08-30 00:54:35 +0000794 (NestedNameSpecifier *)SS->getScopeRep(),
795 SS->getRange());
796 return ExprError();
797 } else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregor4ea80432008-11-18 15:03:34 +0000798 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000799 return ExprError(Diag(Loc, diag::err_undeclared_use)
800 << Name.getAsString());
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000801 else
Sebastian Redlffbcf962009-01-18 18:53:16 +0000802 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Steve Naroff92e30f82007-04-02 22:35:25 +0000803 }
Chris Lattner17ed4872006-11-20 04:58:19 +0000804 }
Mike Stump11289f42009-09-09 15:08:12 +0000805
Douglas Gregor3256d042009-06-30 15:47:41 +0000806 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
807 // Warn about constructs like:
808 // if (void *X = foo()) { ... } else { X }.
809 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +0000810
Douglas Gregor3256d042009-06-30 15:47:41 +0000811 // FIXME: In a template instantiation, we don't have scope
812 // information to check this property.
813 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
814 Scope *CheckS = S;
815 while (CheckS) {
Mike Stump11289f42009-09-09 15:08:12 +0000816 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +0000817 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
818 if (Var->getType()->isBooleanType())
819 ExprError(Diag(Loc, diag::warn_value_always_false)
820 << Var->getDeclName());
821 else
822 ExprError(Diag(Loc, diag::warn_value_always_zero)
823 << Var->getDeclName());
824 break;
825 }
Mike Stump11289f42009-09-09 15:08:12 +0000826
Douglas Gregor3256d042009-06-30 15:47:41 +0000827 // Move up one more control parent to check again.
828 CheckS = CheckS->getControlParent();
829 if (CheckS)
830 CheckS = CheckS->getParent();
831 }
832 }
833 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
834 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
835 // C99 DR 316 says that, if a function type comes from a
836 // function definition (without a prototype), that type is only
837 // used for checking compatibility. Therefore, when referencing
838 // the function, we pretend that we don't have the full function
839 // type.
840 if (DiagnoseUseOfDecl(Func, Loc))
841 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000842
Douglas Gregor3256d042009-06-30 15:47:41 +0000843 QualType T = Func->getType();
844 QualType NoProtoType = T;
845 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
846 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
847 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
848 }
849 }
Mike Stump11289f42009-09-09 15:08:12 +0000850
Douglas Gregor3256d042009-06-30 15:47:41 +0000851 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
852}
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000853/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +0000854bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000855Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
856 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +0000857 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000858 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +0000859 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000860 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +0000861 if (DestType->isDependentType() || From->getType()->isDependentType())
862 return false;
863 QualType FromRecordType = From->getType();
864 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000865 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +0000866 DestType = Context.getPointerType(DestType);
867 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000868 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +0000869 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
870 CheckDerivedToBaseConversion(FromRecordType,
871 DestRecordType,
872 From->getSourceRange().getBegin(),
873 From->getSourceRange()))
874 return true;
Anders Carlssona076d142009-07-31 01:23:52 +0000875 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
876 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000877 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +0000878 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000879}
Douglas Gregor3256d042009-06-30 15:47:41 +0000880
Douglas Gregorf405d7e2009-08-31 23:41:50 +0000881/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +0000882static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
883 const CXXScopeSpec *SS, NamedDecl *Member,
Douglas Gregorc1905232009-08-26 22:36:53 +0000884 SourceLocation Loc, QualType Ty) {
885 if (SS && SS->isSet())
Mike Stump11289f42009-09-09 15:08:12 +0000886 return MemberExpr::Create(C, Base, isArrow,
Douglas Gregorf405d7e2009-08-31 23:41:50 +0000887 (NestedNameSpecifier *)SS->getScopeRep(),
Mike Stump11289f42009-09-09 15:08:12 +0000888 SS->getRange(), Member, Loc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +0000889 // FIXME: Explicit template argument lists
890 false, SourceLocation(), 0, 0, SourceLocation(),
891 Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000892
Douglas Gregorc1905232009-08-26 22:36:53 +0000893 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
894}
895
Douglas Gregor3256d042009-06-30 15:47:41 +0000896/// \brief Complete semantic analysis for a reference to the given declaration.
897Sema::OwningExprResult
898Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
899 bool HasTrailingLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000900 const CXXScopeSpec *SS,
Douglas Gregor3256d042009-06-30 15:47:41 +0000901 bool isAddressOfOperand) {
902 assert(D && "Cannot refer to a NULL declaration");
903 DeclarationName Name = D->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000904
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000905 // If this is an expression of the form &Class::member, don't build an
906 // implicit member ref, because we want a pointer to the member in general,
907 // not any specific instance's member.
908 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor52537682009-03-19 00:18:19 +0000909 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor2ada0482009-02-04 17:27:36 +0000910 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000911 QualType DType;
912 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
913 DType = FD->getType().getNonReferenceType();
914 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
915 DType = Method->getType();
916 } else if (isa<OverloadedFunctionDecl>(D)) {
917 DType = Context.OverloadTy;
918 }
919 // Could be an inner type. That's diagnosed below, so ignore it here.
920 if (!DType.isNull()) {
921 // The pointer is type- and value-dependent if it points into something
922 // dependent.
Douglas Gregor82dbbd72009-05-29 14:49:33 +0000923 bool Dependent = DC->isDependentContext();
Anders Carlsson946b86d2009-06-24 00:10:43 +0000924 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000925 }
926 }
927 }
928
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000929 // We may have found a field within an anonymous union or struct
930 // (C++ [class.union]).
931 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
932 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
933 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +0000934
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000935 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
936 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000937 // C++ [class.mfct.nonstatic]p2:
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000938 // [...] if name lookup (3.4.1) resolves the name in the
939 // id-expression to a nonstatic nontype member of class X or of
940 // a base class of X, the id-expression is transformed into a
941 // class member access expression (5.2.5) using (*this) (9.3.2)
942 // as the postfix-expression to the left of the '.' operator.
943 DeclContext *Ctx = 0;
944 QualType MemberType;
945 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
946 Ctx = FD->getDeclContext();
947 MemberType = FD->getType();
948
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000949 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000950 MemberType = RefType->getPointeeType();
951 else if (!FD->isMutable()) {
Mike Stump11289f42009-09-09 15:08:12 +0000952 unsigned combinedQualifiers
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000953 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
954 MemberType = MemberType.getQualifiedType(combinedQualifiers);
955 }
956 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
957 if (!Method->isStatic()) {
958 Ctx = Method->getParent();
959 MemberType = Method->getType();
960 }
Mike Stump11289f42009-09-09 15:08:12 +0000961 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor97628d62009-08-21 00:16:32 +0000962 = dyn_cast<FunctionTemplateDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +0000963 if (CXXMethodDecl *Method
Douglas Gregor97628d62009-08-21 00:16:32 +0000964 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +0000965 if (!Method->isStatic()) {
Douglas Gregor97628d62009-08-21 00:16:32 +0000966 Ctx = Method->getParent();
967 MemberType = Context.OverloadTy;
968 }
969 }
Mike Stump11289f42009-09-09 15:08:12 +0000970 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000971 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor97628d62009-08-21 00:16:32 +0000972 // FIXME: We need an abstraction for iterating over one or more function
973 // templates or functions. This code is far too repetitive!
Mike Stump11289f42009-09-09 15:08:12 +0000974 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000975 Func = Ovl->function_begin(),
976 FuncEnd = Ovl->function_end();
977 Func != FuncEnd; ++Func) {
Douglas Gregor97628d62009-08-21 00:16:32 +0000978 CXXMethodDecl *DMethod = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000979 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor97628d62009-08-21 00:16:32 +0000980 = dyn_cast<FunctionTemplateDecl>(*Func))
981 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
982 else
983 DMethod = dyn_cast<CXXMethodDecl>(*Func);
984
985 if (DMethod && !DMethod->isStatic()) {
986 Ctx = DMethod->getDeclContext();
987 MemberType = Context.OverloadTy;
988 break;
989 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000990 }
991 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000992
993 if (Ctx && Ctx->isRecord()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000994 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
995 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000996 if ((Context.getCanonicalType(CtxType)
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000997 == Context.getCanonicalType(ThisType)) ||
998 IsDerivedFrom(ThisType, CtxType)) {
999 // Build the implicit member access expression.
Steve Narofff6009ed2009-01-21 00:14:39 +00001000 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00001001 MD->getThisType(Context));
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001002 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001003 if (PerformObjectMemberConversion(This, D))
1004 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00001005
Anders Carlsson99056f22009-09-11 05:54:14 +00001006 bool ShouldCheckUse = true;
1007 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1008 // Don't diagnose the use of a virtual member function unless it's
1009 // explicitly qualified.
1010 if (MD->isVirtual() && (!SS || !SS->isSet()))
1011 ShouldCheckUse = false;
1012 }
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00001013
Anders Carlsson99056f22009-09-11 05:54:14 +00001014 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
Anders Carlsson21776b72009-08-08 16:55:18 +00001015 return ExprError();
Douglas Gregorc1905232009-08-26 22:36:53 +00001016 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1017 Loc, MemberType));
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001018 }
1019 }
1020 }
1021 }
1022
Douglas Gregor91f84212008-12-11 16:49:14 +00001023 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001024 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1025 if (MD->isStatic())
1026 // "invalid use of member 'x' in static member function"
Sebastian Redlffbcf962009-01-18 18:53:16 +00001027 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1028 << FD->getDeclName());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001029 }
1030
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001031 // Any other ways we could have found the field in a well-formed
1032 // program would have been turned into implicit member expressions
1033 // above.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001034 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1035 << FD->getDeclName());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001036 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001037
Steve Naroff46ba1eb2007-04-03 23:13:13 +00001038 if (isa<TypedefDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +00001039 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001040 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +00001041 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001042 if (isa<NamespaceDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +00001043 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Steve Narofff1e53692007-03-23 22:27:02 +00001044
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001045 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001046 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson946b86d2009-06-24 00:10:43 +00001047 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1048 false, false, SS);
Douglas Gregord32e0282009-02-09 23:23:08 +00001049 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson946b86d2009-06-24 00:10:43 +00001050 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1051 false, false, SS);
Anders Carlsson938b1002009-08-29 01:06:32 +00001052 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
Mike Stump11289f42009-09-09 15:08:12 +00001053 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1054 /*TypeDependent=*/true,
Anders Carlsson938b1002009-08-29 01:06:32 +00001055 /*ValueDependent=*/true, SS);
1056
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001057 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001058
Douglas Gregor171c45a2009-02-18 21:56:37 +00001059 // Check whether this declaration can be used. Note that we suppress
1060 // this check when we're going to perform argument-dependent lookup
1061 // on this function name, because this might not be the function
1062 // that overload resolution actually selects.
Mike Stump11289f42009-09-09 15:08:12 +00001063 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001064 HasTrailingLParen;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001065 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1066 return ExprError();
1067
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001068 // Only create DeclRefExpr's for valid Decl's.
1069 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001070 return ExprError();
1071
Chris Lattner2a9d9892008-10-20 05:16:36 +00001072 // If the identifier reference is inside a block, and it refers to a value
1073 // that is outside the block, create a BlockDeclRefExpr instead of a
1074 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1075 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001076 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001077 // We do not do this for things like enum constants, global variables, etc,
1078 // as they do not get snapshotted.
1079 //
1080 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001081 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001082 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001083 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001084 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001085 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001086 // This is to record that a 'const' was actually synthesize and added.
1087 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001088 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001089
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001090 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001091 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001092 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001093 }
1094 // If this reference is not in a block or if the referenced variable is
1095 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001096
Douglas Gregor4619e432008-12-05 23:32:09 +00001097 bool TypeDependent = false;
Douglas Gregor872ffce2008-12-10 20:57:37 +00001098 bool ValueDependent = false;
1099 if (getLangOptions().CPlusPlus) {
1100 // C++ [temp.dep.expr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001101 // An id-expression is type-dependent if it contains:
Douglas Gregor872ffce2008-12-10 20:57:37 +00001102 // - an identifier that was declared with a dependent type,
1103 if (VD->getType()->isDependentType())
1104 TypeDependent = true;
1105 // - FIXME: a template-id that is dependent,
1106 // - a conversion-function-id that specifies a dependent type,
1107 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1108 Name.getCXXNameType()->isDependentType())
1109 TypeDependent = true;
1110 // - a nested-name-specifier that contains a class-name that
1111 // names a dependent type.
1112 else if (SS && !SS->isEmpty()) {
Douglas Gregor52537682009-03-19 00:18:19 +00001113 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor872ffce2008-12-10 20:57:37 +00001114 DC; DC = DC->getParent()) {
1115 // FIXME: could stop early at namespace scope.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001116 if (DC->isRecord()) {
Douglas Gregor872ffce2008-12-10 20:57:37 +00001117 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1118 if (Context.getTypeDeclType(Record)->isDependentType()) {
1119 TypeDependent = true;
1120 break;
1121 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001122 }
1123 }
1124 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001125
Douglas Gregor872ffce2008-12-10 20:57:37 +00001126 // C++ [temp.dep.constexpr]p2:
1127 //
1128 // An identifier is value-dependent if it is:
1129 // - a name declared with a dependent type,
1130 if (TypeDependent)
1131 ValueDependent = true;
1132 // - the name of a non-type template parameter,
1133 else if (isa<NonTypeTemplateParmDecl>(VD))
1134 ValueDependent = true;
1135 // - a constant with integral or enumeration type and is
1136 // initialized with an expression that is value-dependent
Eli Friedmandd49ee32009-06-11 01:11:20 +00001137 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1138 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1139 Dcl->getInit()) {
1140 ValueDependent = Dcl->getInit()->isValueDependent();
1141 }
1142 }
Douglas Gregor872ffce2008-12-10 20:57:37 +00001143 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001144
Anders Carlsson946b86d2009-06-24 00:10:43 +00001145 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1146 TypeDependent, ValueDependent, SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001147}
Chris Lattnere168f762006-11-10 05:29:30 +00001148
Sebastian Redlffbcf962009-01-18 18:53:16 +00001149Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1150 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001151 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001152
Chris Lattnere168f762006-11-10 05:29:30 +00001153 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001154 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001155 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1156 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1157 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001158 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001159
Chris Lattnera81a0272008-01-12 08:14:25 +00001160 // Pre-defined identifiers are of type char[x], where x is the length of the
1161 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001162
Anders Carlsson2fb08242009-09-08 18:24:21 +00001163 Decl *currentDecl = getCurFunctionOrMethodDecl();
1164 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001165 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001166 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001167 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001168
Anders Carlsson0b209a82009-09-11 01:22:35 +00001169 QualType ResTy;
1170 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1171 ResTy = Context.DependentTy;
1172 } else {
1173 unsigned Length =
1174 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001175
Anders Carlsson0b209a82009-09-11 01:22:35 +00001176 llvm::APInt LengthI(32, Length + 1);
1177 ResTy = Context.CharTy.getQualifiedType(QualType::Const);
1178 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1179 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001180 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001181}
1182
Sebastian Redlffbcf962009-01-18 18:53:16 +00001183Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001184 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001185 CharBuffer.resize(Tok.getLength());
1186 const char *ThisTokBegin = &CharBuffer[0];
1187 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001188
Steve Naroffae4143e2007-04-26 20:39:23 +00001189 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1190 Tok.getLocation(), PP);
1191 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001192 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001193
1194 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1195
Sebastian Redl20614a72009-01-20 22:23:13 +00001196 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1197 Literal.isWide(),
1198 type, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001199}
1200
Sebastian Redlffbcf962009-01-18 18:53:16 +00001201Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1202 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001203 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1204 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001205 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001206 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001207 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001208 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001209 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001210
Chris Lattner23b7eb62007-06-15 23:05:46 +00001211 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001212 // Add padding so that NumericLiteralParser can overread by one character.
1213 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001214 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001215
Chris Lattner67ca9252007-05-21 01:08:44 +00001216 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001217 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001218
Mike Stump11289f42009-09-09 15:08:12 +00001219 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001220 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001221 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001222 return ExprError();
1223
Chris Lattner1c20a172007-08-26 03:42:43 +00001224 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001225
Chris Lattner1c20a172007-08-26 03:42:43 +00001226 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001227 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001228 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001229 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001230 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001231 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001232 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001233 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001234
1235 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1236
Ted Kremenek3a2c9502007-11-29 00:56:49 +00001237 // isExact will be set by GetFloatValue().
1238 bool isExact = false;
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001239 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1240 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001241
Chris Lattner1c20a172007-08-26 03:42:43 +00001242 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001243 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001244 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001245 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001246
Neil Boothac582c52007-08-29 22:00:19 +00001247 // long long is a C99 feature.
1248 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001249 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001250 Diag(Tok.getLocation(), diag::ext_longlong);
1251
Chris Lattner67ca9252007-05-21 01:08:44 +00001252 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001253 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001254
Chris Lattner67ca9252007-05-21 01:08:44 +00001255 if (Literal.GetIntegerValue(ResultVal)) {
1256 // If this value didn't fit into uintmax_t, warn and force to ull.
1257 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001258 Ty = Context.UnsignedLongLongTy;
1259 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001260 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001261 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001262 // If this value fits into a ULL, try to figure out what else it fits into
1263 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001264
Chris Lattner67ca9252007-05-21 01:08:44 +00001265 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1266 // be an unsigned int.
1267 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1268
1269 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001270 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001271 if (!Literal.isLong && !Literal.isLongLong) {
1272 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001273 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001274
Chris Lattner67ca9252007-05-21 01:08:44 +00001275 // Does it fit in a unsigned int?
1276 if (ResultVal.isIntN(IntSize)) {
1277 // Does it fit in a signed int?
1278 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001279 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001280 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001281 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001282 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001283 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001284 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001285
Chris Lattner67ca9252007-05-21 01:08:44 +00001286 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001287 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001288 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001289
Chris Lattner67ca9252007-05-21 01:08:44 +00001290 // Does it fit in a unsigned long?
1291 if (ResultVal.isIntN(LongSize)) {
1292 // Does it fit in a signed long?
1293 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001294 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001295 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001296 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001297 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001298 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001299 }
1300
Chris Lattner67ca9252007-05-21 01:08:44 +00001301 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001302 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001303 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001304
Chris Lattner67ca9252007-05-21 01:08:44 +00001305 // Does it fit in a unsigned long long?
1306 if (ResultVal.isIntN(LongLongSize)) {
1307 // Does it fit in a signed long long?
1308 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001309 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001310 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001311 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001312 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001313 }
1314 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001315
Chris Lattner67ca9252007-05-21 01:08:44 +00001316 // If we still couldn't decide a type, we probably have something that
1317 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001318 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001319 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001320 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001321 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001322 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001323
Chris Lattner55258cf2008-05-09 05:59:00 +00001324 if (ResultVal.getBitWidth() != Width)
1325 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001326 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001327 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001328 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001329
Chris Lattner1c20a172007-08-26 03:42:43 +00001330 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1331 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001332 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001333 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001334
1335 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001336}
1337
Sebastian Redlffbcf962009-01-18 18:53:16 +00001338Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1339 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001340 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001341 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001342 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001343}
1344
Steve Naroff71b59a92007-06-04 22:22:31 +00001345/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001346/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001347bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001348 SourceLocation OpLoc,
1349 const SourceRange &ExprRange,
1350 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001351 if (exprType->isDependentType())
1352 return false;
1353
Steve Naroff043d45d2007-05-15 02:32:35 +00001354 // C99 6.5.3.4p1:
Chris Lattnerb1355b12009-01-24 19:46:37 +00001355 if (isa<FunctionType>(exprType)) {
Chris Lattner62975a72009-04-24 00:30:45 +00001356 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001357 if (isSizeof)
1358 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1359 return false;
1360 }
Mike Stump11289f42009-09-09 15:08:12 +00001361
Chris Lattner62975a72009-04-24 00:30:45 +00001362 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001363 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001364 Diag(OpLoc, diag::ext_sizeof_void_type)
1365 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001366 return false;
1367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattner62975a72009-04-24 00:30:45 +00001369 if (RequireCompleteType(OpLoc, exprType,
Mike Stump11289f42009-09-09 15:08:12 +00001370 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssond624e162009-08-26 23:45:07 +00001371 PDiag(diag::err_alignof_incomplete_type)
1372 << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001373 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattner62975a72009-04-24 00:30:45 +00001375 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001376 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001377 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001378 << exprType << isSizeof << ExprRange;
1379 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001380 }
Mike Stump11289f42009-09-09 15:08:12 +00001381
Chris Lattner62975a72009-04-24 00:30:45 +00001382 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001383}
1384
Chris Lattner8dff0172009-01-24 20:17:12 +00001385bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1386 const SourceRange &ExprRange) {
1387 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001388
Mike Stump11289f42009-09-09 15:08:12 +00001389 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001390 if (isa<DeclRefExpr>(E))
1391 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001392
1393 // Cannot know anything else if the expression is dependent.
1394 if (E->isTypeDependent())
1395 return false;
1396
Douglas Gregor71235ec2009-05-02 02:18:30 +00001397 if (E->getBitField()) {
1398 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1399 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001400 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001401
1402 // Alignment of a field access is always okay, so long as it isn't a
1403 // bit-field.
1404 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001405 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001406 return false;
1407
Chris Lattner8dff0172009-01-24 20:17:12 +00001408 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1409}
1410
Douglas Gregor0950e412009-03-13 21:01:28 +00001411/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001412Action::OwningExprResult
1413Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001414 bool isSizeOf, SourceRange R) {
1415 if (T.isNull())
1416 return ExprError();
1417
1418 if (!T->isDependentType() &&
1419 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1420 return ExprError();
1421
1422 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1423 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1424 Context.getSizeType(), OpLoc,
1425 R.getEnd()));
1426}
1427
1428/// \brief Build a sizeof or alignof expression given an expression
1429/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001430Action::OwningExprResult
1431Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001432 bool isSizeOf, SourceRange R) {
1433 // Verify that the operand is valid.
1434 bool isInvalid = false;
1435 if (E->isTypeDependent()) {
1436 // Delay type-checking for type-dependent expressions.
1437 } else if (!isSizeOf) {
1438 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001439 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001440 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1441 isInvalid = true;
1442 } else {
1443 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1444 }
1445
1446 if (isInvalid)
1447 return ExprError();
1448
1449 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1450 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1451 Context.getSizeType(), OpLoc,
1452 R.getEnd()));
1453}
1454
Sebastian Redl6f282892008-11-11 17:56:53 +00001455/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1456/// the same for @c alignof and @c __alignof
1457/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001458Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001459Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1460 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001461 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001462 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001463
Sebastian Redl6f282892008-11-11 17:56:53 +00001464 if (isType) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001465 // FIXME: Preserve type source info.
1466 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor0950e412009-03-13 21:01:28 +00001467 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001468 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001469
Douglas Gregor0950e412009-03-13 21:01:28 +00001470 // Get the end location.
1471 Expr *ArgEx = (Expr *)TyOrEx;
1472 Action::OwningExprResult Result
1473 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1474
1475 if (Result.isInvalid())
1476 DeleteExpr(ArgEx);
1477
1478 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001479}
1480
Chris Lattner709322b2009-02-17 08:12:06 +00001481QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001482 if (V->isTypeDependent())
1483 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001484
Chris Lattnere267f5d2007-08-26 05:39:26 +00001485 // These operators return the element type of a complex type.
Chris Lattner30b5dd02007-08-24 21:16:53 +00001486 if (const ComplexType *CT = V->getType()->getAsComplexType())
1487 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattnere267f5d2007-08-26 05:39:26 +00001489 // Otherwise they pass through real integer and floating point types here.
1490 if (V->getType()->isArithmeticType())
1491 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001492
Chris Lattnere267f5d2007-08-26 05:39:26 +00001493 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001494 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1495 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001496 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001497}
1498
1499
Chris Lattnere168f762006-11-10 05:29:30 +00001500
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001501Action::OwningExprResult
1502Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1503 tok::TokenKind Kind, ExprArg Input) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001504 // Since this might be a postfix expression, get rid of ParenListExprs.
1505 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001506 Expr *Arg = (Expr *)Input.get();
Douglas Gregord08452f2008-11-19 15:42:04 +00001507
Chris Lattnere168f762006-11-10 05:29:30 +00001508 UnaryOperator::Opcode Opc;
1509 switch (Kind) {
1510 default: assert(0 && "Unknown unary op!");
1511 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1512 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1513 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001514
Douglas Gregord08452f2008-11-19 15:42:04 +00001515 if (getLangOptions().CPlusPlus &&
1516 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1517 // Which overloaded operator?
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001518 OverloadedOperatorKind OverOp =
Douglas Gregord08452f2008-11-19 15:42:04 +00001519 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1520
1521 // C++ [over.inc]p1:
1522 //
1523 // [...] If the function is a member function with one
1524 // parameter (which shall be of type int) or a non-member
1525 // function with two parameters (the second of which shall be
1526 // of type int), it defines the postfix increment operator ++
1527 // for objects of that type. When the postfix increment is
1528 // called as a result of using the ++ operator, the int
1529 // argument will have value zero.
Mike Stump11289f42009-09-09 15:08:12 +00001530 Expr *Args[2] = {
1531 Arg,
1532 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
Steve Narofff6009ed2009-01-21 00:14:39 +00001533 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregord08452f2008-11-19 15:42:04 +00001534 };
1535
1536 // Build the candidate set for overloading
1537 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001538 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregord08452f2008-11-19 15:42:04 +00001539
1540 // Perform overload resolution.
1541 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001542 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregord08452f2008-11-19 15:42:04 +00001543 case OR_Success: {
1544 // We found a built-in operator or an overloaded operator.
1545 FunctionDecl *FnDecl = Best->Function;
1546
1547 if (FnDecl) {
1548 // We matched an overloaded operator. Build a call to that
1549 // operator.
1550
1551 // Convert the arguments.
1552 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1553 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001554 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001555 } else {
1556 // Convert the arguments.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001557 if (PerformCopyInitialization(Arg,
Douglas Gregord08452f2008-11-19 15:42:04 +00001558 FnDecl->getParamDecl(0)->getType(),
1559 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001560 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001561 }
1562
1563 // Determine the result type
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001564 QualType ResultTy
Douglas Gregord08452f2008-11-19 15:42:04 +00001565 = FnDecl->getType()->getAsFunctionType()->getResultType();
1566 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001567
Douglas Gregord08452f2008-11-19 15:42:04 +00001568 // Build the actual expression node.
Steve Narofff6009ed2009-01-21 00:14:39 +00001569 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump82191d02009-02-19 02:54:59 +00001570 SourceLocation());
Douglas Gregord08452f2008-11-19 15:42:04 +00001571 UsualUnaryConversions(FnExpr);
1572
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001573 Input.release();
Douglas Gregor2517f332009-05-27 05:00:47 +00001574 Args[0] = Arg;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001575 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
Mike Stump11289f42009-09-09 15:08:12 +00001576 Args, 2, ResultTy,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001577 OpLoc));
Douglas Gregord08452f2008-11-19 15:42:04 +00001578 } else {
1579 // We matched a built-in operator. Convert the arguments, then
1580 // break out so that we will build the appropriate built-in
1581 // operator node.
1582 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1583 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001584 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001585
1586 break;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001587 }
Douglas Gregord08452f2008-11-19 15:42:04 +00001588 }
1589
1590 case OR_No_Viable_Function:
1591 // No viable function; fall through to handling this as a
1592 // built-in operator, which will produce an error message for us.
1593 break;
1594
1595 case OR_Ambiguous:
1596 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1597 << UnaryOperator::getOpcodeStr(Opc)
1598 << Arg->getSourceRange();
1599 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001600 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00001601
1602 case OR_Deleted:
1603 Diag(OpLoc, diag::err_ovl_deleted_oper)
1604 << Best->Function->isDeleted()
1605 << UnaryOperator::getOpcodeStr(Opc)
1606 << Arg->getSourceRange();
1607 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1608 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001609 }
1610
1611 // Either we found no viable overloaded operator or we matched a
1612 // built-in operator. In either case, fall through to trying to
1613 // build a built-in operation.
1614 }
1615
Eli Friedmanf32f0a72009-07-22 23:24:42 +00001616 Input.release();
1617 Input = Arg;
Eli Friedman6aea5752009-07-22 22:25:00 +00001618 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001619}
1620
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001621Action::OwningExprResult
1622Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1623 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001624 // Since this might be a postfix expression, get rid of ParenListExprs.
1625 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1626
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001627 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1628 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001629
Douglas Gregor40412ac2008-11-19 17:17:41 +00001630 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001631 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1632 Base.release();
1633 Idx.release();
1634 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1635 Context.DependentTy, RLoc));
1636 }
1637
Mike Stump11289f42009-09-09 15:08:12 +00001638 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001639 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001640 LHSExp->getType()->isEnumeralType() ||
1641 RHSExp->getType()->isRecordType() ||
1642 RHSExp->getType()->isEnumeralType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001643 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor40412ac2008-11-19 17:17:41 +00001644 // to the candidate set.
1645 OverloadCandidateSet CandidateSet;
1646 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001647 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1648 SourceRange(LLoc, RLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001649
Douglas Gregor40412ac2008-11-19 17:17:41 +00001650 // Perform overload resolution.
1651 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001652 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor40412ac2008-11-19 17:17:41 +00001653 case OR_Success: {
1654 // We found a built-in operator or an overloaded operator.
1655 FunctionDecl *FnDecl = Best->Function;
1656
1657 if (FnDecl) {
1658 // We matched an overloaded operator. Build a call to that
1659 // operator.
1660
1661 // Convert the arguments.
1662 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1663 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
Mike Stump11289f42009-09-09 15:08:12 +00001664 PerformCopyInitialization(RHSExp,
Douglas Gregor40412ac2008-11-19 17:17:41 +00001665 FnDecl->getParamDecl(0)->getType(),
1666 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001667 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001668 } else {
1669 // Convert the arguments.
1670 if (PerformCopyInitialization(LHSExp,
1671 FnDecl->getParamDecl(0)->getType(),
1672 "passing") ||
1673 PerformCopyInitialization(RHSExp,
1674 FnDecl->getParamDecl(1)->getType(),
1675 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001676 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001677 }
1678
1679 // Determine the result type
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001680 QualType ResultTy
Douglas Gregor40412ac2008-11-19 17:17:41 +00001681 = FnDecl->getType()->getAsFunctionType()->getResultType();
1682 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001683
Douglas Gregor40412ac2008-11-19 17:17:41 +00001684 // Build the actual expression node.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001685 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1686 SourceLocation());
Douglas Gregor40412ac2008-11-19 17:17:41 +00001687 UsualUnaryConversions(FnExpr);
1688
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001689 Base.release();
1690 Idx.release();
Douglas Gregor2517f332009-05-27 05:00:47 +00001691 Args[0] = LHSExp;
1692 Args[1] = RHSExp;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001693 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Mike Stump11289f42009-09-09 15:08:12 +00001694 FnExpr, Args, 2,
Steve Narofff6009ed2009-01-21 00:14:39 +00001695 ResultTy, LLoc));
Douglas Gregor40412ac2008-11-19 17:17:41 +00001696 } else {
1697 // We matched a built-in operator. Convert the arguments, then
1698 // break out so that we will build the appropriate built-in
1699 // operator node.
1700 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1701 "passing") ||
1702 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1703 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001704 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001705
1706 break;
1707 }
1708 }
1709
1710 case OR_No_Viable_Function:
1711 // No viable function; fall through to handling this as a
1712 // built-in operator, which will produce an error message for us.
1713 break;
1714
1715 case OR_Ambiguous:
1716 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1717 << "[]"
1718 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1719 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001720 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00001721
1722 case OR_Deleted:
1723 Diag(LLoc, diag::err_ovl_deleted_oper)
1724 << Best->Function->isDeleted()
1725 << "[]"
1726 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1727 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1728 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001729 }
1730
1731 // Either we found no viable overloaded operator or we matched a
1732 // built-in operator. In either case, fall through to trying to
1733 // build a built-in operation.
1734 }
1735
Chris Lattner36d572b2007-07-16 00:14:47 +00001736 // Perform default conversions.
1737 DefaultFunctionArrayConversion(LHSExp);
1738 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001739
Chris Lattner36d572b2007-07-16 00:14:47 +00001740 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00001741
Steve Naroffc1aadb12007-03-28 21:49:40 +00001742 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00001743 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00001744 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00001745 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00001746 Expr *BaseExpr, *IndexExpr;
1747 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001748 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1749 BaseExpr = LHSExp;
1750 IndexExpr = RHSExp;
1751 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001752 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00001753 BaseExpr = LHSExp;
1754 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001755 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001756 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00001757 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00001758 BaseExpr = RHSExp;
1759 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001760 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001761 } else if (const ObjCObjectPointerType *PTy =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001762 LHSTy->getAsObjCObjectPointerType()) {
1763 BaseExpr = LHSExp;
1764 IndexExpr = RHSExp;
1765 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001766 } else if (const ObjCObjectPointerType *PTy =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001767 RHSTy->getAsObjCObjectPointerType()) {
1768 // Handle the uncommon case of "123[Ptr]".
1769 BaseExpr = RHSExp;
1770 IndexExpr = LHSExp;
1771 ResultType = PTy->getPointeeType();
Chris Lattner41977962007-07-31 19:29:30 +00001772 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1773 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00001774 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00001775
Chris Lattner36d572b2007-07-16 00:14:47 +00001776 // FIXME: need to deal with const...
1777 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001778 } else if (LHSTy->isArrayType()) {
1779 // If we see an array that wasn't promoted by
1780 // DefaultFunctionArrayConversion, it must be an array that
1781 // wasn't promoted because of the C90 rule that doesn't
1782 // allow promoting non-lvalue arrays. Warn, then
1783 // force the promotion here.
1784 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1785 LHSExp->getSourceRange();
1786 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1787 LHSTy = LHSExp->getType();
1788
1789 BaseExpr = LHSExp;
1790 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001791 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001792 } else if (RHSTy->isArrayType()) {
1793 // Same as previous, except for 123[f().a] case
1794 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1795 RHSExp->getSourceRange();
1796 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1797 RHSTy = RHSExp->getType();
1798
1799 BaseExpr = RHSExp;
1800 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001801 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00001802 } else {
Chris Lattner003af242009-04-25 22:50:55 +00001803 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1804 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001805 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00001806 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00001807 if (!(IndexExpr->getType()->isIntegerType() &&
1808 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00001809 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1810 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00001811
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00001812 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00001813 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1814 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00001815 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1816
Douglas Gregorac1fb652009-03-24 19:52:54 +00001817 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00001818 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1819 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00001820 // incomplete types are not object types.
1821 if (ResultType->isFunctionType()) {
1822 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1823 << ResultType << BaseExpr->getSourceRange();
1824 return ExprError();
1825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Douglas Gregorac1fb652009-03-24 19:52:54 +00001827 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001828 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00001829 PDiag(diag::err_subscript_incomplete_type)
1830 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00001831 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001832
Chris Lattner62975a72009-04-24 00:30:45 +00001833 // Diagnose bad cases where we step over interface counts.
1834 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1835 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1836 << ResultType << BaseExpr->getSourceRange();
1837 return ExprError();
1838 }
Mike Stump11289f42009-09-09 15:08:12 +00001839
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001840 Base.release();
1841 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001842 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00001843 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00001844}
1845
Steve Narofff8fd09e2007-07-27 22:15:19 +00001846QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00001847CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001848 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00001849 SourceLocation CompLoc) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001850 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanf322eab2008-05-09 06:41:27 +00001851
Steve Narofff8fd09e2007-07-27 22:15:19 +00001852 // The vector accessor can't exceed the number of elements.
Anders Carlssonf571c112009-08-26 18:25:21 +00001853 const char *compStr = CompName->getName();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001854
Mike Stump4e1f26a2009-02-19 03:04:26 +00001855 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00001856 // special names that indicate a subset of exactly half the elements are
1857 // to be selected.
1858 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00001859
Nate Begemanbb70bf62009-01-18 01:47:54 +00001860 // This flag determines whether or not CompName has an 's' char prefix,
1861 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00001862 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00001863
1864 // Check that we've found one of the special components, or that the component
1865 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001866 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00001867 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1868 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00001869 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001870 do
1871 compStr++;
1872 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00001873 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001874 do
1875 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00001876 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00001877 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00001878
Mike Stump4e1f26a2009-02-19 03:04:26 +00001879 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00001880 // We didn't get to the end of the string. This means the component names
1881 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00001882 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1883 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00001884 return QualType();
1885 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00001886
Nate Begemanbb70bf62009-01-18 01:47:54 +00001887 // Ensure no component accessor exceeds the width of the vector type it
1888 // operates on.
1889 if (!HalvingSwizzle) {
Anders Carlssonf571c112009-08-26 18:25:21 +00001890 compStr = CompName->getName();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001891
1892 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00001893 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00001894
1895 while (*compStr) {
1896 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1897 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1898 << baseType << SourceRange(CompLoc);
1899 return QualType();
1900 }
1901 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00001902 }
Nate Begemanf322eab2008-05-09 06:41:27 +00001903
Nate Begemanbb70bf62009-01-18 01:47:54 +00001904 // If this is a halving swizzle, verify that the base type has an even
1905 // number of elements.
1906 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner3b054132008-11-19 05:08:23 +00001907 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001908 << baseType << SourceRange(CompLoc);
Nate Begemanf322eab2008-05-09 06:41:27 +00001909 return QualType();
1910 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00001911
Steve Narofff8fd09e2007-07-27 22:15:19 +00001912 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001913 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00001914 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00001915 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00001916 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanbb70bf62009-01-18 01:47:54 +00001917 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00001918 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001919 if (HexSwizzle)
1920 CompSize--;
1921
Steve Narofff8fd09e2007-07-27 22:15:19 +00001922 if (CompSize == 1)
1923 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001924
Nate Begemance4d7fc2008-04-18 23:10:10 +00001925 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00001926 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00001927 // diagostics look bad. We want extended vector types to appear built-in.
1928 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1929 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1930 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001931 }
1932 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00001933}
1934
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001935static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00001936 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001937 const Selector &Sel,
1938 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00001939
Anders Carlssonf571c112009-08-26 18:25:21 +00001940 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001941 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001942 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001943 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00001944
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001945 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1946 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001947 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001948 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001949 return D;
1950 }
1951 return 0;
1952}
1953
Steve Narofffb4330f2009-06-17 22:40:22 +00001954static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00001955 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001956 const Selector &Sel,
1957 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001958 // Check protocols on qualified interfaces.
1959 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00001960 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001961 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00001962 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001963 GDecl = PD;
1964 break;
1965 }
1966 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001967 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001968 GDecl = OMD;
1969 break;
1970 }
1971 }
1972 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00001973 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001974 E = QIdTy->qual_end(); I != E; ++I) {
1975 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001976 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001977 if (GDecl)
1978 return GDecl;
1979 }
1980 }
1981 return GDecl;
1982}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00001983
Fariborz Jahanian69ba9352009-04-07 18:28:06 +00001984/// FindMethodInNestedImplementations - Look up a method in current and
1985/// all base class implementations.
1986///
1987ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1988 const ObjCInterfaceDecl *IFace,
1989 const Selector &Sel) {
1990 ObjCMethodDecl *Method = 0;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001991 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001992 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump11289f42009-09-09 15:08:12 +00001993
Fariborz Jahanian69ba9352009-04-07 18:28:06 +00001994 if (!Method && IFace->getSuperClass())
1995 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1996 return Method;
1997}
Mike Stump11289f42009-09-09 15:08:12 +00001998
1999Action::OwningExprResult
Anders Carlssonf571c112009-08-26 18:25:21 +00002000Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002001 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002002 DeclarationName MemberName,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002003 bool HasExplicitTemplateArgs,
2004 SourceLocation LAngleLoc,
2005 const TemplateArgument *ExplicitTemplateArgs,
2006 unsigned NumExplicitTemplateArgs,
2007 SourceLocation RAngleLoc,
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002008 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
2009 NamedDecl *FirstQualifierInScope) {
Douglas Gregord8061562009-08-06 03:17:00 +00002010 if (SS && SS->isInvalid())
2011 return ExprError();
2012
Nate Begeman5ec4b312009-08-10 23:49:36 +00002013 // Since this might be a postfix expression, get rid of ParenListExprs.
2014 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2015
Anders Carlsson3cbc8592009-05-01 19:30:39 +00002016 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregorad8a3362009-09-04 17:36:40 +00002017 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002018
Steve Naroffeaaae462007-12-16 21:42:28 +00002019 // Perform default conversions.
2020 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002021
Steve Naroff185616f2007-07-26 03:11:44 +00002022 QualType BaseType = BaseExpr->getType();
David Chisnall9f57c292009-08-17 16:35:33 +00002023 // If this is an Objective-C pseudo-builtin and a definition is provided then
2024 // use that.
2025 if (BaseType->isObjCIdType()) {
2026 // We have an 'id' type. Rather than fall through, we check if this
2027 // is a reference to 'isa'.
2028 if (BaseType != Context.ObjCIdRedefinitionType) {
2029 BaseType = Context.ObjCIdRedefinitionType;
2030 ImpCastExprToType(BaseExpr, BaseType);
2031 }
2032 } else if (BaseType->isObjCClassType() &&
Douglas Gregorfbc18232009-08-31 21:16:32 +00002033 BaseType != Context.ObjCClassRedefinitionType) {
David Chisnall9f57c292009-08-17 16:35:33 +00002034 BaseType = Context.ObjCClassRedefinitionType;
2035 ImpCastExprToType(BaseExpr, BaseType);
2036 }
Steve Naroff185616f2007-07-26 03:11:44 +00002037 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002038
Chris Lattner4befd732008-07-21 04:36:39 +00002039 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2040 // must have pointer type, and the accessed type is the pointee.
Steve Narofff1e53692007-03-23 22:27:02 +00002041 if (OpKind == tok::arrow) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002042 if (BaseType->isDependentType()) {
2043 NestedNameSpecifier *Qualifier = 0;
2044 if (SS) {
2045 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2046 if (!FirstQualifierInScope)
2047 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2048 }
Mike Stump11289f42009-09-09 15:08:12 +00002049
2050 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor308047d2009-09-09 00:23:06 +00002051 OpLoc, Qualifier,
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002052 SS? SS->getRange() : SourceRange(),
Douglas Gregor308047d2009-09-09 00:23:06 +00002053 FirstQualifierInScope,
2054 MemberName,
2055 MemberLoc,
2056 HasExplicitTemplateArgs,
2057 LAngleLoc,
2058 ExplicitTemplateArgs,
2059 NumExplicitTemplateArgs,
2060 RAngleLoc));
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002061 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002062 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002063 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002064 else if (BaseType->isObjCObjectPointerType())
2065 ;
Steve Naroff185616f2007-07-26 03:11:44 +00002066 else
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002067 return ExprError(Diag(MemberLoc,
2068 diag::err_typecheck_member_reference_arrow)
2069 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002070 } else {
Anders Carlsson524d5a42009-05-16 20:31:20 +00002071 if (BaseType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002072 // Require that the base type isn't a pointer type
Anders Carlsson524d5a42009-05-16 20:31:20 +00002073 // (so we'll report an error for)
2074 // T* t;
2075 // t.f;
Mike Stump11289f42009-09-09 15:08:12 +00002076 //
Anders Carlsson524d5a42009-05-16 20:31:20 +00002077 // In Obj-C++, however, the above expression is valid, since it could be
2078 // accessing the 'f' property if T is an Obj-C interface. The extra check
2079 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002080 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002081
Mike Stump11289f42009-09-09 15:08:12 +00002082 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002083 !PT->getPointeeType()->isRecordType())) {
2084 NestedNameSpecifier *Qualifier = 0;
2085 if (SS) {
2086 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2087 if (!FirstQualifierInScope)
2088 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090
Douglas Gregor308047d2009-09-09 00:23:06 +00002091 return Owned(CXXUnresolvedMemberExpr::Create(Context,
Mike Stump11289f42009-09-09 15:08:12 +00002092 BaseExpr, false,
2093 OpLoc,
Douglas Gregor308047d2009-09-09 00:23:06 +00002094 Qualifier,
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002095 SS? SS->getRange() : SourceRange(),
Douglas Gregor308047d2009-09-09 00:23:06 +00002096 FirstQualifierInScope,
2097 MemberName,
2098 MemberLoc,
2099 HasExplicitTemplateArgs,
2100 LAngleLoc,
2101 ExplicitTemplateArgs,
2102 NumExplicitTemplateArgs,
2103 RAngleLoc));
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002104 }
Anders Carlsson524d5a42009-05-16 20:31:20 +00002105 }
Steve Narofff1e53692007-03-23 22:27:02 +00002106 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002107
Chris Lattner4befd732008-07-21 04:36:39 +00002108 // Handle field access to simple records. This also handles access to fields
2109 // of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002110 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff185616f2007-07-26 03:11:44 +00002111 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregored0cfbd2009-03-09 16:13:40 +00002112 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00002113 PDiag(diag::err_typecheck_incomplete_tag)
2114 << BaseExpr->getSourceRange()))
Douglas Gregordd430f72009-01-19 19:26:10 +00002115 return ExprError();
2116
Douglas Gregord8061562009-08-06 03:17:00 +00002117 DeclContext *DC = RDecl;
2118 if (SS && SS->isSet()) {
2119 // If the member name was a qualified-id, look into the
2120 // nested-name-specifier.
2121 DC = computeDeclContext(*SS, false);
Mike Stump11289f42009-09-09 15:08:12 +00002122
2123 // FIXME: If DC is not computable, we should build a
Douglas Gregord8061562009-08-06 03:17:00 +00002124 // CXXUnresolvedMemberExpr.
2125 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2126 }
2127
Steve Naroff185616f2007-07-26 03:11:44 +00002128 // The record definition is complete, now make sure the member is valid.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002129 LookupResult Result
Anders Carlssonf571c112009-08-26 18:25:21 +00002130 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002131
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002132 if (!Result)
Anders Carlsson896c2302009-08-30 00:54:35 +00002133 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlssonf571c112009-08-26 18:25:21 +00002134 << MemberName << BaseExpr->getSourceRange());
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002135 if (Result.isAmbiguous()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002136 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2137 BaseExpr->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002138 return ExprError();
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002139 }
Mike Stump11289f42009-09-09 15:08:12 +00002140
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002141 if (SS && SS->isSet()) {
Mike Stump11289f42009-09-09 15:08:12 +00002142 QualType BaseTypeCanon
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002143 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002144 QualType MemberTypeCanon
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002145 = Context.getCanonicalType(
2146 Context.getTypeDeclType(
2147 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
Mike Stump11289f42009-09-09 15:08:12 +00002148
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002149 if (BaseTypeCanon != MemberTypeCanon &&
2150 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2151 return ExprError(Diag(SS->getBeginLoc(),
2152 diag::err_not_direct_base_or_virtual)
2153 << MemberTypeCanon << BaseTypeCanon);
2154 }
Mike Stump11289f42009-09-09 15:08:12 +00002155
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002156 NamedDecl *MemberDecl = Result;
Douglas Gregor91f84212008-12-11 16:49:14 +00002157
Chris Lattner303284a2009-02-13 22:08:30 +00002158 // If the decl being referenced had an error, return an error for this
2159 // sub-expr without emitting another error, in order to avoid cascading
2160 // error cases.
2161 if (MemberDecl->isInvalidDecl())
2162 return ExprError();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002163
Anders Carlsson04e1e222009-09-10 20:48:14 +00002164 bool ShouldCheckUse = true;
2165 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2166 // Don't diagnose the use of a virtual member function unless it's
2167 // explicitly qualified.
2168 if (MD->isVirtual() && (!SS || !SS->isSet()))
2169 ShouldCheckUse = false;
2170 }
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002171
Douglas Gregor171c45a2009-02-18 21:56:37 +00002172 // Check the use of this field
Anders Carlsson04e1e222009-09-10 20:48:14 +00002173 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002174 return ExprError();
Chris Lattner303284a2009-02-13 22:08:30 +00002175
Douglas Gregor55297ac2008-12-23 00:26:44 +00002176 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002177 // We may have found a field within an anonymous union or struct
2178 // (C++ [class.union]).
2179 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002180 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002181 BaseExpr, OpLoc);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002182
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002183 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor55297ac2008-12-23 00:26:44 +00002184 QualType MemberType = FD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002185 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002186 MemberType = Ref->getPointeeType();
2187 else {
Mon P Wangacedf772009-07-22 03:08:17 +00002188 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002189 unsigned combinedQualifiers =
2190 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor55297ac2008-12-23 00:26:44 +00002191 if (FD->isMutable())
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002192 combinedQualifiers &= ~QualType::Const;
2193 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wangacedf772009-07-22 03:08:17 +00002194 if (BaseAddrSpace != MemberType.getAddressSpace())
2195 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002196 }
Eli Friedman1242fff2008-02-06 22:48:16 +00002197
Douglas Gregor77b50e12009-06-22 23:06:13 +00002198 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002199 if (PerformObjectMemberConversion(BaseExpr, FD))
2200 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002201 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorc1905232009-08-26 22:36:53 +00002202 FD, MemberLoc, MemberType));
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002203 }
Mike Stump11289f42009-09-09 15:08:12 +00002204
Douglas Gregor77b50e12009-06-22 23:06:13 +00002205 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2206 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002207 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2208 Var, MemberLoc,
2209 Var->getType().getNonReferenceType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002210 }
2211 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2212 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002213 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2214 MemberFn, MemberLoc,
2215 MemberFn->getType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002216 }
Mike Stump11289f42009-09-09 15:08:12 +00002217 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor97628d62009-08-21 00:16:32 +00002218 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2219 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002220
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002221 if (HasExplicitTemplateArgs)
Mike Stump11289f42009-09-09 15:08:12 +00002222 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2223 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002224 SS? SS->getRange() : SourceRange(),
Mike Stump11289f42009-09-09 15:08:12 +00002225 FunTmpl, MemberLoc, true,
2226 LAngleLoc, ExplicitTemplateArgs,
2227 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002228 Context.OverloadTy));
Mike Stump11289f42009-09-09 15:08:12 +00002229
Douglas Gregorc1905232009-08-26 22:36:53 +00002230 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2231 FunTmpl, MemberLoc,
2232 Context.OverloadTy));
Douglas Gregor97628d62009-08-21 00:16:32 +00002233 }
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002234 if (OverloadedFunctionDecl *Ovl
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002235 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2236 if (HasExplicitTemplateArgs)
Mike Stump11289f42009-09-09 15:08:12 +00002237 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2238 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002239 SS? SS->getRange() : SourceRange(),
Mike Stump11289f42009-09-09 15:08:12 +00002240 Ovl, MemberLoc, true,
2241 LAngleLoc, ExplicitTemplateArgs,
2242 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002243 Context.OverloadTy));
2244
Douglas Gregorc1905232009-08-26 22:36:53 +00002245 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2246 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002247 }
Douglas Gregor77b50e12009-06-22 23:06:13 +00002248 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2249 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002250 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2251 Enum, MemberLoc, Enum->getType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002252 }
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002253 if (isa<TypeDecl>(MemberDecl))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002254 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlssonf571c112009-08-26 18:25:21 +00002255 << MemberName << int(OpKind == tok::arrow));
Eli Friedman1242fff2008-02-06 22:48:16 +00002256
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002257 // We found a declaration kind that we didn't expect. This is a
2258 // generic error message that tells the user that she can't refer
2259 // to this member with '.' or '->'.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002260 return ExprError(Diag(MemberLoc,
2261 diag::err_typecheck_member_reference_unknown)
Anders Carlssonf571c112009-08-26 18:25:21 +00002262 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002263 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002264
Douglas Gregorad8a3362009-09-04 17:36:40 +00002265 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2266 // into a record type was handled above, any destructor we see here is a
2267 // pseudo-destructor.
2268 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2269 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002270 // The left hand side of the dot operator shall be of scalar type. The
2271 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002272 // type.
2273 if (!BaseType->isScalarType())
2274 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2275 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002276
Douglas Gregorad8a3362009-09-04 17:36:40 +00002277 // [...] The type designated by the pseudo-destructor-name shall be the
2278 // same as the object type.
2279 if (!MemberName.getCXXNameType()->isDependentType() &&
2280 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2281 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2282 << BaseType << MemberName.getCXXNameType()
2283 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002284
2285 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002286 // the form
2287 //
Mike Stump11289f42009-09-09 15:08:12 +00002288 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2289 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002290 // shall designate the same scalar type.
2291 //
2292 // FIXME: DPG can't see any way to trigger this particular clause, so it
2293 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002294
Douglas Gregorad8a3362009-09-04 17:36:40 +00002295 // FIXME: We've lost the precise spelling of the type by going through
2296 // DeclarationName. Can we do better?
2297 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002298 OpKind == tok::arrow,
Douglas Gregorad8a3362009-09-04 17:36:40 +00002299 OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002300 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002301 SS? SS->getRange() : SourceRange(),
2302 MemberName.getCXXNameType(),
2303 MemberLoc));
2304 }
Mike Stump11289f42009-09-09 15:08:12 +00002305
Steve Naroff7cae42b2009-07-10 23:34:53 +00002306 // Handle properties on ObjC 'Class' types.
Steve Naroff4eed7a12009-07-13 17:19:15 +00002307 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002308 // Also must look for a getter name which uses property syntax.
Anders Carlssonf571c112009-08-26 18:25:21 +00002309 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2310 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002311 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2312 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2313 ObjCMethodDecl *Getter;
2314 // FIXME: need to also look locally in the implementation.
2315 if ((Getter = IFace->lookupClassMethod(Sel))) {
2316 // Check the use of this method.
2317 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2318 return ExprError();
2319 }
2320 // If we found a getter then this may be a valid dot-reference, we
2321 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002322 Selector SetterSel =
2323 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002324 PP.getSelectorTable(), Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002325 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2326 if (!Setter) {
2327 // If this reference is in an @implementation, also check for 'private'
2328 // methods.
2329 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2330 }
2331 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002332 if (!Setter)
2333 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002334
2335 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2336 return ExprError();
2337
2338 if (Getter || Setter) {
2339 QualType PType;
2340
2341 if (Getter)
2342 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002343 else
2344 // Get the expression type from Setter's incoming parameter.
2345 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002346 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002347 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002348 Setter, MemberLoc, BaseExpr));
2349 }
2350 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002351 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002352 }
2353 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002354 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2355 // (*Obj).ivar.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002356 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2357 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2358 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
Mike Stump11289f42009-09-09 15:08:12 +00002359 const ObjCInterfaceType *IFaceT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00002360 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroffa057ba92009-07-16 00:25:06 +00002361 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002362 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2363
Steve Naroffa057ba92009-07-16 00:25:06 +00002364 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2365 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002366 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002367
Steve Naroffa057ba92009-07-16 00:25:06 +00002368 if (IV) {
2369 // If the decl being referenced had an error, return an error for this
2370 // sub-expr without emitting another error, in order to avoid cascading
2371 // error cases.
2372 if (IV->isInvalidDecl())
2373 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002374
Steve Naroffa057ba92009-07-16 00:25:06 +00002375 // Check whether we can reference this field.
2376 if (DiagnoseUseOfDecl(IV, MemberLoc))
2377 return ExprError();
2378 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2379 IV->getAccessControl() != ObjCIvarDecl::Package) {
2380 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2381 if (ObjCMethodDecl *MD = getCurMethodDecl())
2382 ClassOfMethodDecl = MD->getClassInterface();
2383 else if (ObjCImpDecl && getCurFunctionDecl()) {
2384 // Case of a c-function declared inside an objc implementation.
2385 // FIXME: For a c-style function nested inside an objc implementation
2386 // class, there is no implementation context available, so we pass
2387 // down the context as argument to this routine. Ideally, this context
2388 // need be passed down in the AST node and somehow calculated from the
2389 // AST for a function decl.
2390 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002391 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002392 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2393 ClassOfMethodDecl = IMPD->getClassInterface();
2394 else if (ObjCCategoryImplDecl* CatImplClass =
2395 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2396 ClassOfMethodDecl = CatImplClass->getClassInterface();
2397 }
Mike Stump11289f42009-09-09 15:08:12 +00002398
2399 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2400 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002401 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002402 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002403 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002404 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2405 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002406 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002407 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002408 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002409
2410 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2411 MemberLoc, BaseExpr,
2412 OpKind == tok::arrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002413 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002414 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002415 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002416 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002417 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002418 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002419 // Handle properties on 'id' and qualified "id".
Mike Stump11289f42009-09-09 15:08:12 +00002420 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroff1329fa02009-07-15 18:40:39 +00002421 BaseType->isObjCQualifiedIdType())) {
2422 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002423 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002424
Steve Naroff7cae42b2009-07-10 23:34:53 +00002425 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002426 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002427 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2428 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2429 // Check the use of this declaration
2430 if (DiagnoseUseOfDecl(PD, MemberLoc))
2431 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002432
Steve Naroff7cae42b2009-07-10 23:34:53 +00002433 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2434 MemberLoc, BaseExpr));
2435 }
2436 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2437 // Check the use of this method.
2438 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2439 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002440
Steve Naroff7cae42b2009-07-10 23:34:53 +00002441 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002442 OMD->getResultType(),
2443 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002444 NULL, 0));
2445 }
2446 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002447
Steve Naroff7cae42b2009-07-10 23:34:53 +00002448 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002449 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002450 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002451 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2452 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002453 const ObjCObjectPointerType *OPT;
Mike Stump11289f42009-09-09 15:08:12 +00002454 if (OpKind == tok::period &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00002455 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2456 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2457 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002458 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002459
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002460 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002461 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002462 // Check whether we can reference this property.
2463 if (DiagnoseUseOfDecl(PD, MemberLoc))
2464 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002465 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002466 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002467 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00002468 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2469 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002470 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00002471 MemberLoc, BaseExpr));
2472 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002473 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00002474 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2475 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002476 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002477 // Check whether we can reference this property.
2478 if (DiagnoseUseOfDecl(PD, MemberLoc))
2479 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00002480
Steve Narofff6009ed2009-01-21 00:14:39 +00002481 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00002482 MemberLoc, BaseExpr));
2483 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002484 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2485 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002486 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002487 // Check whether we can reference this property.
2488 if (DiagnoseUseOfDecl(PD, MemberLoc))
2489 return ExprError();
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002490
Steve Naroff7cae42b2009-07-10 23:34:53 +00002491 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2492 MemberLoc, BaseExpr));
2493 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002494 // If that failed, look for an "implicit" property by seeing if the nullary
2495 // selector is implemented.
2496
2497 // FIXME: The logic for looking up nullary and unary selectors should be
2498 // shared with the code in ActOnInstanceMessage.
2499
Anders Carlssonf571c112009-08-26 18:25:21 +00002500 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002501 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002502
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002503 // If this reference is in an @implementation, check for 'private' methods.
2504 if (!Getter)
Fariborz Jahanian69ba9352009-04-07 18:28:06 +00002505 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002506
Steve Naroff1df62692008-10-22 19:16:27 +00002507 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002508 if (!Getter)
2509 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002510 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002511 // Check if we can reference this property.
2512 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2513 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002514 }
2515 // If we found a getter then this may be a valid dot-reference, we
2516 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002517 Selector SetterSel =
2518 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002519 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002520 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002521 if (!Setter) {
2522 // If this reference is in an @implementation, also check for 'private'
2523 // methods.
Fariborz Jahanian69ba9352009-04-07 18:28:06 +00002524 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002525 }
2526 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002527 if (!Setter)
2528 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002529
Steve Naroff1d984fe2009-03-11 13:48:17 +00002530 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2531 return ExprError();
2532
2533 if (Getter || Setter) {
2534 QualType PType;
2535
2536 if (Getter)
2537 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002538 else
2539 // Get the expression type from Setter's incoming parameter.
2540 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002541 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002542 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00002543 Setter, MemberLoc, BaseExpr));
2544 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002545 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002546 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00002547 }
Mike Stump11289f42009-09-09 15:08:12 +00002548
Steve Naroffe87026a2009-07-24 17:54:45 +00002549 // Handle the following exceptional case (*Obj).isa.
Mike Stump11289f42009-09-09 15:08:12 +00002550 if (OpKind == tok::period &&
Steve Naroffe87026a2009-07-24 17:54:45 +00002551 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00002552 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00002553 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2554 Context.getObjCIdType()));
2555
Chris Lattnerb63a7452008-07-21 04:28:12 +00002556 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002557 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002558 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00002559 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2560 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002561 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00002562 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00002563 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002564 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002565
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002566 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2567 << BaseType << BaseExpr->getSourceRange();
2568
2569 // If the user is trying to apply -> or . to a function or function
2570 // pointer, it's probably because they forgot parentheses to call
2571 // the function. Suggest the addition of those parentheses.
Mike Stump11289f42009-09-09 15:08:12 +00002572 if (BaseType == Context.OverloadTy ||
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002573 BaseType->isFunctionType() ||
Mike Stump11289f42009-09-09 15:08:12 +00002574 (BaseType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002575 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002576 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2577 Diag(Loc, diag::note_member_reference_needs_call)
2578 << CodeModificationHint::CreateInsertion(Loc, "()");
2579 }
2580
2581 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00002582}
2583
Anders Carlssonf571c112009-08-26 18:25:21 +00002584Action::OwningExprResult
2585Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2586 tok::TokenKind OpKind, SourceLocation MemberLoc,
2587 IdentifierInfo &Member,
2588 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Mike Stump11289f42009-09-09 15:08:12 +00002589 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
Anders Carlssonf571c112009-08-26 18:25:21 +00002590 DeclarationName(&Member), ObjCImpDecl, SS);
2591}
2592
Anders Carlsson355933d2009-08-25 03:49:14 +00002593Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2594 FunctionDecl *FD,
2595 ParmVarDecl *Param) {
2596 if (Param->hasUnparsedDefaultArg()) {
2597 Diag (CallLoc,
2598 diag::err_use_of_default_argument_to_function_declared_later) <<
2599 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002600 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00002601 diag::note_default_argument_declared_here);
2602 } else {
2603 if (Param->hasUninstantiatedDefaultArg()) {
2604 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2605
2606 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002607 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00002608
Mike Stump11289f42009-09-09 15:08:12 +00002609 InstantiatingTemplate Inst(*this, CallLoc, Param,
2610 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00002611 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00002612
John McCall76d824f2009-08-25 22:02:44 +00002613 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00002614 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00002615 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002616
2617 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson355933d2009-08-25 03:49:14 +00002618 /*FIXME:EqualLoc*/
2619 UninstExpr->getSourceRange().getBegin()))
2620 return ExprError();
2621 }
Mike Stump11289f42009-09-09 15:08:12 +00002622
Anders Carlsson355933d2009-08-25 03:49:14 +00002623 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +00002624
Anders Carlsson355933d2009-08-25 03:49:14 +00002625 // If the default expression creates temporaries, we need to
2626 // push them to the current stack of expression temporaries so they'll
2627 // be properly destroyed.
Mike Stump11289f42009-09-09 15:08:12 +00002628 if (CXXExprWithTemporaries *E
Anders Carlsson355933d2009-08-25 03:49:14 +00002629 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002630 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson355933d2009-08-25 03:49:14 +00002631 "Can't destroy temporaries in a default argument expr!");
2632 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2633 ExprTemporaries.push_back(E->getTemporary(I));
2634 }
2635 }
2636
2637 // We already type-checked the argument, so we know it works.
2638 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2639}
2640
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002641/// ConvertArgumentsForCall - Converts the arguments specified in
2642/// Args/NumArgs to the parameter types of the function FDecl with
2643/// function prototype Proto. Call is the call expression itself, and
2644/// Fn is the function expression. For a C++ member function, this
2645/// routine does not attempt to convert the object argument. Returns
2646/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002647bool
2648Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002649 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002650 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002651 Expr **Args, unsigned NumArgs,
2652 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002653 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002654 // assignment, to the types of the corresponding parameter, ...
2655 unsigned NumArgsInProto = Proto->getNumArgs();
2656 unsigned NumArgsToCheck = NumArgs;
Douglas Gregorb6b99612009-01-23 21:30:56 +00002657 bool Invalid = false;
2658
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002659 // If too few arguments are available (and we don't have default
2660 // arguments for the remaining parameters), don't make the call.
2661 if (NumArgs < NumArgsInProto) {
2662 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2663 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2664 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2665 // Use default arguments for missing arguments
2666 NumArgsToCheck = NumArgsInProto;
Ted Kremenek5a201952009-02-07 01:47:29 +00002667 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002668 }
2669
2670 // If too many are passed and not variadic, error on the extras and drop
2671 // them.
2672 if (NumArgs > NumArgsInProto) {
2673 if (!Proto->isVariadic()) {
2674 Diag(Args[NumArgsInProto]->getLocStart(),
2675 diag::err_typecheck_call_too_many_args)
2676 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2677 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2678 Args[NumArgs-1]->getLocEnd());
2679 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00002680 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregorb6b99612009-01-23 21:30:56 +00002681 Invalid = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002682 }
2683 NumArgsToCheck = NumArgsInProto;
2684 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002685
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002686 // Continue to check argument types (even if we have too few/many args).
2687 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2688 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002689
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002690 Expr *Arg;
Douglas Gregor58354032008-12-24 00:01:03 +00002691 if (i < NumArgs) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002692 Arg = Args[i];
Douglas Gregor58354032008-12-24 00:01:03 +00002693
Eli Friedman3164fb12009-03-22 22:00:50 +00002694 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2695 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00002696 PDiag(diag::err_call_incomplete_argument)
2697 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002698 return true;
2699
Douglas Gregor58354032008-12-24 00:01:03 +00002700 // Pass the argument.
2701 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2702 return true;
Anders Carlsson84613c42009-06-12 16:51:40 +00002703 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00002704 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump11289f42009-09-09 15:08:12 +00002705
2706 OwningExprResult ArgExpr =
Anders Carlsson355933d2009-08-25 03:49:14 +00002707 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2708 FDecl, Param);
2709 if (ArgExpr.isInvalid())
2710 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002711
Anders Carlsson355933d2009-08-25 03:49:14 +00002712 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00002713 }
Mike Stump11289f42009-09-09 15:08:12 +00002714
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002715 Call->setArg(i, Arg);
2716 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002717
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002718 // If this is a variadic call, handle args passed through "...".
2719 if (Proto->isVariadic()) {
Anders Carlssona7d069d2009-01-16 16:48:51 +00002720 VariadicCallType CallType = VariadicFunction;
2721 if (Fn->getType()->isBlockPointerType())
2722 CallType = VariadicBlock; // Block
2723 else if (isa<MemberExpr>(Fn))
2724 CallType = VariadicMethod;
2725
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002726 // Promote the arguments (C99 6.5.2.2p7).
2727 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2728 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00002729 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002730 Call->setArg(i, Arg);
2731 }
2732 }
2733
Douglas Gregorb6b99612009-01-23 21:30:56 +00002734 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002735}
2736
Steve Naroff83895f72007-09-16 03:34:24 +00002737/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00002738/// This provides the location of the left/right parens and a list of comma
2739/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002740Action::OwningExprResult
2741Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2742 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002743 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002744 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002745
2746 // Since this might be a postfix expression, get rid of ParenListExprs.
2747 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00002748
Anders Carlsson3cbc8592009-05-01 19:30:39 +00002749 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002750 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00002751 assert(Fn && "no function call expression");
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002752 FunctionDecl *FDecl = NULL;
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002753 NamedDecl *NDecl = NULL;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002754 DeclarationName UnqualifiedName;
Mike Stump11289f42009-09-09 15:08:12 +00002755
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002756 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002757 // If this is a pseudo-destructor expression, build the call immediately.
2758 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2759 if (NumArgs > 0) {
2760 // Pseudo-destructor calls should not have any arguments.
2761 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2762 << CodeModificationHint::CreateRemoval(
2763 SourceRange(Args[0]->getLocStart(),
2764 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00002765
Douglas Gregorad8a3362009-09-04 17:36:40 +00002766 for (unsigned I = 0; I != NumArgs; ++I)
2767 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002768
Douglas Gregorad8a3362009-09-04 17:36:40 +00002769 NumArgs = 0;
2770 }
Mike Stump11289f42009-09-09 15:08:12 +00002771
Douglas Gregorad8a3362009-09-04 17:36:40 +00002772 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2773 RParenLoc));
2774 }
Mike Stump11289f42009-09-09 15:08:12 +00002775
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002776 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00002777 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00002778 // FIXME: Will need to cache the results of name lookup (including ADL) in
2779 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002780 bool Dependent = false;
2781 if (Fn->isTypeDependent())
2782 Dependent = true;
2783 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2784 Dependent = true;
2785
2786 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002787 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002788 Context.DependentTy, RParenLoc));
2789
2790 // Determine whether this is a call to an object (C++ [over.call.object]).
2791 if (Fn->getType()->isRecordType())
2792 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2793 CommaLocs, RParenLoc));
2794
Douglas Gregore254f902009-02-04 00:32:51 +00002795 // Determine whether this is a call to a member function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002796 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2797 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2798 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2799 isa<CXXMethodDecl>(MemDecl) ||
2800 (isa<FunctionTemplateDecl>(MemDecl) &&
2801 isa<CXXMethodDecl>(
2802 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002803 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2804 CommaLocs, RParenLoc));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002805 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002806 }
2807
Douglas Gregore254f902009-02-04 00:32:51 +00002808 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002809 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00002810 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregore254f902009-02-04 00:32:51 +00002811 Expr *FnExpr = Fn;
2812 bool ADL = true;
Douglas Gregor89026b52009-06-30 23:57:56 +00002813 bool HasExplicitTemplateArgs = 0;
2814 const TemplateArgument *ExplicitTemplateArgs = 0;
2815 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregore254f902009-02-04 00:32:51 +00002816 while (true) {
2817 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2818 FnExpr = IcExpr->getSubExpr();
2819 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002820 // Parentheses around a function disable ADL
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002821 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregore254f902009-02-04 00:32:51 +00002822 ADL = false;
2823 FnExpr = PExpr->getSubExpr();
2824 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump4e1f26a2009-02-19 03:04:26 +00002825 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregore254f902009-02-04 00:32:51 +00002826 == UnaryOperator::AddrOf) {
2827 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregora727cb92009-06-30 22:34:41 +00002828 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattner3a230732009-02-14 07:22:29 +00002829 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2830 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregora727cb92009-06-30 22:34:41 +00002831 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattner3a230732009-02-14 07:22:29 +00002832 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002833 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattner3a230732009-02-14 07:22:29 +00002834 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2835 UnqualifiedName = DepName->getName();
2836 break;
Mike Stump11289f42009-09-09 15:08:12 +00002837 } else if (TemplateIdRefExpr *TemplateIdRef
Douglas Gregora727cb92009-06-30 22:34:41 +00002838 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2839 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregoraa87ebc2009-07-29 18:26:50 +00002840 if (!NDecl)
2841 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregor89026b52009-06-30 23:57:56 +00002842 HasExplicitTemplateArgs = true;
2843 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2844 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
Mike Stump11289f42009-09-09 15:08:12 +00002845
Douglas Gregor89026b52009-06-30 23:57:56 +00002846 // C++ [temp.arg.explicit]p6:
2847 // [Note: For simple function names, argument dependent lookup (3.4.2)
Mike Stump11289f42009-09-09 15:08:12 +00002848 // applies even when the function name is not visible within the
Douglas Gregor89026b52009-06-30 23:57:56 +00002849 // scope of the call. This is because the call still has the syntactic
2850 // form of a function call (3.4.1). But when a function template with
2851 // explicit template arguments is used, the call does not have the
Mike Stump11289f42009-09-09 15:08:12 +00002852 // correct syntactic form unless there is a function template with
2853 // that name visible at the point of the call. If no such name is
2854 // visible, the call is not syntactically well-formed and
2855 // argument-dependent lookup does not apply. If some such name is
Douglas Gregor89026b52009-06-30 23:57:56 +00002856 // visible, argument dependent lookup applies and additional function
2857 // templates may be found in other namespaces.
2858 //
2859 // The summary of this paragraph is that, if we get to this point and the
2860 // template-id was not a qualified name, then argument-dependent lookup
2861 // is still possible.
2862 if (TemplateIdRef->getQualifier())
2863 ADL = false;
Douglas Gregora727cb92009-06-30 22:34:41 +00002864 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002865 } else {
Chris Lattner3a230732009-02-14 07:22:29 +00002866 // Any kind of name that does not refer to a declaration (or
2867 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2868 ADL = false;
Douglas Gregore254f902009-02-04 00:32:51 +00002869 break;
2870 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002871 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002872
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002873 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002874 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregora727cb92009-06-30 22:34:41 +00002875 if (NDecl) {
2876 FDecl = dyn_cast<FunctionDecl>(NDecl);
2877 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002878 FDecl = FunctionTemplate->getTemplatedDecl();
2879 else
Douglas Gregora727cb92009-06-30 22:34:41 +00002880 FDecl = dyn_cast<FunctionDecl>(NDecl);
2881 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002882 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002883
Mike Stump11289f42009-09-09 15:08:12 +00002884 if (Ovl || FunctionTemplate ||
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002885 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002886 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002887 if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
Douglas Gregore254f902009-02-04 00:32:51 +00002888 ADL = false;
2889
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002890 // We don't perform ADL in C.
2891 if (!getLangOptions().CPlusPlus)
2892 ADL = false;
2893
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002894 if (Ovl || FunctionTemplate || ADL) {
Mike Stump11289f42009-09-09 15:08:12 +00002895 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00002896 HasExplicitTemplateArgs,
2897 ExplicitTemplateArgs,
2898 NumExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00002899 LParenLoc, Args, NumArgs, CommaLocs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002900 RParenLoc, ADL);
Douglas Gregore254f902009-02-04 00:32:51 +00002901 if (!FDecl)
2902 return ExprError();
2903
2904 // Update Fn to refer to the actual function selected.
2905 Expr *NewFn = 0;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002906 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregora727cb92009-06-30 22:34:41 +00002907 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregorf21eb492009-03-26 23:50:42 +00002908 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2909 QDRExpr->getLocation(),
2910 false, false,
2911 QDRExpr->getQualifierRange(),
2912 QDRExpr->getQualifier());
Douglas Gregore254f902009-02-04 00:32:51 +00002913 else
Mike Stump4e1f26a2009-02-19 03:04:26 +00002914 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregore254f902009-02-04 00:32:51 +00002915 Fn->getSourceRange().getBegin());
2916 Fn->Destroy(Context);
2917 Fn = NewFn;
2918 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002919 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002920
2921 // Promote the function operand.
2922 UsualUnaryConversions(Fn);
2923
Chris Lattner08464942007-12-28 05:29:59 +00002924 // Make the call expr early, before semantic checks. This guarantees cleanup
2925 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002926 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2927 Args, NumArgs,
2928 Context.BoolTy,
2929 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002930
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002931 const FunctionType *FuncT;
2932 if (!Fn->getType()->isBlockPointerType()) {
2933 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2934 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002935 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002936 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002937 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2938 << Fn->getType() << Fn->getSourceRange());
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002939 FuncT = PT->getPointeeType()->getAsFunctionType();
2940 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002941 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002942 getAsFunctionType();
2943 }
Chris Lattner08464942007-12-28 05:29:59 +00002944 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002945 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2946 << Fn->getType() << Fn->getSourceRange());
2947
Eli Friedman3164fb12009-03-22 22:00:50 +00002948 // Check for a valid return type
2949 if (!FuncT->getResultType()->isVoidType() &&
2950 RequireCompleteType(Fn->getSourceRange().getBegin(),
2951 FuncT->getResultType(),
Anders Carlssond624e162009-08-26 23:45:07 +00002952 PDiag(diag::err_call_incomplete_return)
2953 << TheCall->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002954 return ExprError();
2955
Chris Lattner08464942007-12-28 05:29:59 +00002956 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00002957 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002958
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002959 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002960 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002961 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002962 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00002963 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002964 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002965
Douglas Gregord8e97de2009-04-02 15:37:10 +00002966 if (FDecl) {
2967 // Check if we have too few/too many template arguments, based
2968 // on our knowledge of the function definition.
2969 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002970 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002971 const FunctionProtoType *Proto =
2972 Def->getType()->getAsFunctionProtoType();
2973 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2974 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2975 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2976 }
2977 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00002978 }
2979
Steve Naroff0b661582007-08-28 23:30:39 +00002980 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00002981 for (unsigned i = 0; i != NumArgs; i++) {
2982 Expr *Arg = Args[i];
2983 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00002984 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2985 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00002986 PDiag(diag::err_call_incomplete_argument)
2987 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002988 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00002989 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00002990 }
Steve Naroffae4143e2007-04-26 20:39:23 +00002991 }
Chris Lattner08464942007-12-28 05:29:59 +00002992
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002993 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2994 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002995 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2996 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002997
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002998 // Check for sentinels
2999 if (NDecl)
3000 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003001
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003002 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003003 if (FDecl) {
3004 if (CheckFunctionCall(FDecl, TheCall.get()))
3005 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003006
Douglas Gregor15fc9562009-09-12 00:22:50 +00003007 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003008 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3009 } else if (NDecl) {
3010 if (CheckBlockCall(NDecl, TheCall.get()))
3011 return ExprError();
3012 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003013
Anders Carlssonf8984012009-08-16 03:06:32 +00003014 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003015}
3016
Sebastian Redlb5d49352009-01-19 22:31:54 +00003017Action::OwningExprResult
3018Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3019 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003020 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003021 //FIXME: Preserve type source info.
3022 QualType literalType = GetTypeFromParser(Ty);
Steve Naroff57eb2c52007-07-19 21:32:11 +00003023 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003024 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003025 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003026
Eli Friedman37a186d2008-05-20 05:22:08 +00003027 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003028 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003029 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3030 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003031 } else if (!literalType->isDependentType() &&
3032 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003033 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003034 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003035 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003036 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003037
Sebastian Redlb5d49352009-01-19 22:31:54 +00003038 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003039 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003040 return ExprError();
Steve Naroffd32419d2008-01-14 18:19:28 +00003041
Chris Lattner79413952008-12-04 23:50:19 +00003042 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003043 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003044 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003045 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003046 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00003047 InitExpr.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003048 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003049 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003050}
3051
Sebastian Redlb5d49352009-01-19 22:31:54 +00003052Action::OwningExprResult
3053Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003054 SourceLocation RBraceLoc) {
3055 unsigned NumInit = initlist.size();
3056 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003057
Steve Naroff30d242c2007-09-15 18:49:24 +00003058 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003059 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003060
Mike Stump4e1f26a2009-02-19 03:04:26 +00003061 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003062 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003063 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003064 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003065}
3066
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003067/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003068bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003069 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003070 CXXMethodDecl *& ConversionDecl,
3071 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003072 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003073 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3074 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003075
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003076 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003077
3078 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3079 // type needs to be scalar.
3080 if (castType->isVoidType()) {
3081 // Cast to void allows any expr type.
3082 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003083 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3084 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3085 (castType->isStructureType() || castType->isUnionType())) {
3086 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003087 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003088 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3089 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003090 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003091 } else if (castType->isUnionType()) {
3092 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003093 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003094 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003095 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003096 Field != FieldEnd; ++Field) {
3097 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3098 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3099 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3100 << castExpr->getSourceRange();
3101 break;
3102 }
3103 }
3104 if (Field == FieldEnd)
3105 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3106 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003107 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003108 } else {
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003109 // Reject any other conversions to non-scalar types.
Chris Lattner3b054132008-11-19 05:08:23 +00003110 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003111 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003112 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003113 } else if (!castExpr->getType()->isScalarType() &&
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003114 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003115 return Diag(castExpr->getLocStart(),
3116 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003117 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanc69b7402009-06-26 00:50:28 +00003118 } else if (castType->isExtVectorType()) {
3119 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003120 return true;
3121 } else if (castType->isVectorType()) {
3122 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3123 return true;
Nate Begemanc69b7402009-06-26 00:50:28 +00003124 } else if (castExpr->getType()->isVectorType()) {
3125 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3126 return true;
Steve Naroff3f49fee2009-03-04 15:11:40 +00003127 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroffb47acdb2009-04-08 23:52:26 +00003128 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003129 } else if (!castType->isArithmeticType()) {
3130 QualType castExprType = castExpr->getType();
3131 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3132 return Diag(castExpr->getLocStart(),
3133 diag::err_cast_pointer_from_non_pointer_int)
3134 << castExprType << castExpr->getSourceRange();
3135 } else if (!castExpr->getType()->isArithmeticType()) {
3136 if (!castType->isIntegralType() && castType->isArithmeticType())
3137 return Diag(castExpr->getLocStart(),
3138 diag::err_cast_pointer_to_non_pointer_int)
3139 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003140 }
Fariborz Jahanian88fead82009-05-22 21:42:52 +00003141 if (isa<ObjCSelectorExpr>(castExpr))
3142 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003143 return false;
3144}
3145
Chris Lattner6c9ffe92007-12-20 00:44:32 +00003146bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003147 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003148
Anders Carlssonde71adf2007-11-27 05:51:55 +00003149 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003150 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003151 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003152 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003153 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003154 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003155 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003156 } else
3157 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003158 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003159 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003160
Anders Carlssonde71adf2007-11-27 05:51:55 +00003161 return false;
3162}
3163
Nate Begemanc69b7402009-06-26 00:50:28 +00003164bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3165 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Mike Stump11289f42009-09-09 15:08:12 +00003166
Nate Begemanc8961a42009-06-27 22:05:55 +00003167 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3168 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003169 if (SrcTy->isVectorType()) {
3170 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3171 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3172 << DestTy << SrcTy << R;
3173 return false;
3174 }
3175
Nate Begemanbd956c42009-06-28 02:36:38 +00003176 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003177 // conversion will take place first from scalar to elt type, and then
3178 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003179 if (SrcTy->isPointerType())
3180 return Diag(R.getBegin(),
3181 diag::err_invalid_conversion_between_vector_and_scalar)
3182 << DestTy << SrcTy << R;
Nate Begemanc69b7402009-06-26 00:50:28 +00003183 return false;
3184}
3185
Sebastian Redlb5d49352009-01-19 22:31:54 +00003186Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003187Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003188 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003189 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003190
Sebastian Redlb5d49352009-01-19 22:31:54 +00003191 assert((Ty != 0) && (Op.get() != 0) &&
3192 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003193
Nate Begeman5ec4b312009-08-10 23:49:36 +00003194 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003195 //FIXME: Preserve type source info.
3196 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003197
Nate Begeman5ec4b312009-08-10 23:49:36 +00003198 // If the Expr being casted is a ParenListExpr, handle it specially.
3199 if (isa<ParenListExpr>(castExpr))
3200 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003201 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003202 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003203 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003204 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003205
3206 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003207 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003208 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003209
Anders Carlssone9766d52009-09-09 21:33:21 +00003210 if (CastArg.isInvalid())
3211 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003212
Anders Carlssone9766d52009-09-09 21:33:21 +00003213 castExpr = CastArg.takeAs<Expr>();
3214 } else {
3215 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003216 }
Mike Stump11289f42009-09-09 15:08:12 +00003217
Sebastian Redl9f831db2009-07-25 15:41:38 +00003218 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003219 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003220 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003221}
3222
Nate Begeman5ec4b312009-08-10 23:49:36 +00003223/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3224/// of comma binary operators.
3225Action::OwningExprResult
3226Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3227 Expr *expr = EA.takeAs<Expr>();
3228 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3229 if (!E)
3230 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003231
Nate Begeman5ec4b312009-08-10 23:49:36 +00003232 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003233
Nate Begeman5ec4b312009-08-10 23:49:36 +00003234 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3235 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3236 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003237
Nate Begeman5ec4b312009-08-10 23:49:36 +00003238 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3239}
3240
3241Action::OwningExprResult
3242Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3243 SourceLocation RParenLoc, ExprArg Op,
3244 QualType Ty) {
3245 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003246
3247 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003248 // then handle it as such.
3249 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3250 if (PE->getNumExprs() == 0) {
3251 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3252 return ExprError();
3253 }
3254
3255 llvm::SmallVector<Expr *, 8> initExprs;
3256 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3257 initExprs.push_back(PE->getExpr(i));
3258
3259 // FIXME: This means that pretty-printing the final AST will produce curly
3260 // braces instead of the original commas.
3261 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003262 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003263 initExprs.size(), RParenLoc);
3264 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003265 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003266 Owned(E));
3267 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003268 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003269 // sequence of BinOp comma operators.
3270 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3271 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3272 }
3273}
3274
3275Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3276 SourceLocation R,
3277 MultiExprArg Val) {
3278 unsigned nexprs = Val.size();
3279 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3280 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3281 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3282 return Owned(expr);
3283}
3284
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003285/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3286/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003287/// C99 6.5.15
3288QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3289 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003290 // C++ is sufficiently different to merit its own checker.
3291 if (getLangOptions().CPlusPlus)
3292 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3293
Chris Lattner432cff52009-02-18 04:28:32 +00003294 UsualUnaryConversions(Cond);
3295 UsualUnaryConversions(LHS);
3296 UsualUnaryConversions(RHS);
3297 QualType CondTy = Cond->getType();
3298 QualType LHSTy = LHS->getType();
3299 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003300
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003301 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003302 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3303 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3304 << CondTy;
3305 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003306 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003307
Chris Lattnere2949f42008-01-06 22:42:25 +00003308 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003309 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3310 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003311
Chris Lattnere2949f42008-01-06 22:42:25 +00003312 // If both operands have arithmetic type, do the usual arithmetic conversions
3313 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003314 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3315 UsualArithmeticConversions(LHS, RHS);
3316 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003317 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003318
Chris Lattnere2949f42008-01-06 22:42:25 +00003319 // If both operands are the same structure or union type, the result is that
3320 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003321 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3322 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003323 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003324 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003325 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003326 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003327 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003328 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003329
Chris Lattnere2949f42008-01-06 22:42:25 +00003330 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003331 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003332 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3333 if (!LHSTy->isVoidType())
3334 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3335 << RHS->getSourceRange();
3336 if (!RHSTy->isVoidType())
3337 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3338 << LHS->getSourceRange();
3339 ImpCastExprToType(LHS, Context.VoidTy);
3340 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003341 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003342 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003343 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3344 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003345 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattner432cff52009-02-18 04:28:32 +00003346 RHS->isNullPointerConstant(Context)) {
3347 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3348 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003349 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003350 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattner432cff52009-02-18 04:28:32 +00003351 LHS->isNullPointerConstant(Context)) {
3352 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3353 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003354 }
David Chisnall9f57c292009-08-17 16:35:33 +00003355 // Handle things like Class and struct objc_class*. Here we case the result
3356 // to the pseudo-builtin, because that will be implicitly cast back to the
3357 // redefinition type if an attempt is made to access its fields.
3358 if (LHSTy->isObjCClassType() &&
3359 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3360 ImpCastExprToType(RHS, LHSTy);
3361 return LHSTy;
3362 }
3363 if (RHSTy->isObjCClassType() &&
3364 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3365 ImpCastExprToType(LHS, RHSTy);
3366 return RHSTy;
3367 }
3368 // And the same for struct objc_object* / id
3369 if (LHSTy->isObjCIdType() &&
3370 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3371 ImpCastExprToType(RHS, LHSTy);
3372 return LHSTy;
3373 }
3374 if (RHSTy->isObjCIdType() &&
3375 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3376 ImpCastExprToType(LHS, RHSTy);
3377 return RHSTy;
3378 }
Steve Naroff05efa972009-07-01 14:36:47 +00003379 // Handle block pointer types.
3380 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3381 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3382 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3383 QualType destType = Context.getPointerType(Context.VoidTy);
Mike Stump11289f42009-09-09 15:08:12 +00003384 ImpCastExprToType(LHS, destType);
Steve Naroff05efa972009-07-01 14:36:47 +00003385 ImpCastExprToType(RHS, destType);
3386 return destType;
3387 }
3388 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3389 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3390 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003391 }
Steve Naroff05efa972009-07-01 14:36:47 +00003392 // We have 2 block pointer types.
3393 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3394 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003395 return LHSTy;
3396 }
Steve Naroff05efa972009-07-01 14:36:47 +00003397 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003398 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3399 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003400
Steve Naroff05efa972009-07-01 14:36:47 +00003401 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3402 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003403 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3404 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3405 // In this situation, we assume void* type. No especially good
3406 // reason, but this is what gcc does, and we do have to pick
3407 // to get a consistent AST.
3408 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3409 ImpCastExprToType(LHS, incompatTy);
3410 ImpCastExprToType(RHS, incompatTy);
3411 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003412 }
Steve Naroff05efa972009-07-01 14:36:47 +00003413 // The block pointer types are compatible.
3414 ImpCastExprToType(LHS, LHSTy);
3415 ImpCastExprToType(RHS, LHSTy);
Steve Naroffea4c7802009-04-08 17:05:15 +00003416 return LHSTy;
3417 }
Steve Naroff05efa972009-07-01 14:36:47 +00003418 // Check constraints for Objective-C object pointers types.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003419 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003420
Steve Naroff05efa972009-07-01 14:36:47 +00003421 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3422 // Two identical object pointer types are always compatible.
3423 return LHSTy;
3424 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00003425 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3426 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff05efa972009-07-01 14:36:47 +00003427 QualType compositeType = LHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003428
Steve Naroff05efa972009-07-01 14:36:47 +00003429 // If both operands are interfaces and either operand can be
3430 // assigned to the other, use that type as the composite
3431 // type. This allows
3432 // xxx ? (A*) a : (B*) b
3433 // where B is a subclass of A.
3434 //
3435 // Additionally, as for assignment, if either type is 'id'
3436 // allow silent coercion. Finally, if the types are
3437 // incompatible then make sure to use 'id' as the composite
3438 // type so the result is acceptable for sending messages to.
3439
3440 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3441 // It could return the composite type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003442 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003443 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003444 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003445 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003446 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00003447 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff8e6aee52009-07-23 01:01:38 +00003448 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump11289f42009-09-09 15:08:12 +00003449 // Need to handle "id<xx>" explicitly.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003450 // GCC allows qualified id and any Objective-C type to devolve to
3451 // id. Currently localizing to here until clear this should be
3452 // part of ObjCQualifiedIdTypesAreCompatible.
3453 compositeType = Context.getObjCIdType();
3454 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff05efa972009-07-01 14:36:47 +00003455 compositeType = Context.getObjCIdType();
3456 } else {
3457 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3458 << LHSTy << RHSTy
3459 << LHS->getSourceRange() << RHS->getSourceRange();
3460 QualType incompatTy = Context.getObjCIdType();
3461 ImpCastExprToType(LHS, incompatTy);
3462 ImpCastExprToType(RHS, incompatTy);
3463 return incompatTy;
3464 }
3465 // The object pointer types are compatible.
3466 ImpCastExprToType(LHS, compositeType);
3467 ImpCastExprToType(RHS, compositeType);
3468 return compositeType;
3469 }
Steve Naroff85d97152009-07-29 15:09:39 +00003470 // Check Objective-C object pointer types and 'void *'
3471 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003472 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff85d97152009-07-29 15:09:39 +00003473 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3474 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3475 QualType destType = Context.getPointerType(destPointee);
3476 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3477 ImpCastExprToType(RHS, destType); // promote to void*
3478 return destType;
3479 }
3480 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3481 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003482 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff85d97152009-07-29 15:09:39 +00003483 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3484 QualType destType = Context.getPointerType(destPointee);
3485 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3486 ImpCastExprToType(LHS, destType); // promote to void*
3487 return destType;
3488 }
Steve Naroff05efa972009-07-01 14:36:47 +00003489 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3490 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3491 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003492 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3493 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00003494
3495 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3496 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3497 // Figure out necessary qualifiers (C99 6.5.15p6)
3498 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3499 QualType destType = Context.getPointerType(destPointee);
3500 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3501 ImpCastExprToType(RHS, destType); // promote to void*
3502 return destType;
3503 }
3504 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3505 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3506 QualType destType = Context.getPointerType(destPointee);
3507 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3508 ImpCastExprToType(RHS, destType); // promote to void*
3509 return destType;
3510 }
3511
3512 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3513 // Two identical pointer types are always compatible.
3514 return LHSTy;
3515 }
3516 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3517 rhptee.getUnqualifiedType())) {
3518 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3519 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3520 // In this situation, we assume void* type. No especially good
3521 // reason, but this is what gcc does, and we do have to pick
3522 // to get a consistent AST.
3523 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3524 ImpCastExprToType(LHS, incompatTy);
3525 ImpCastExprToType(RHS, incompatTy);
3526 return incompatTy;
3527 }
3528 // The pointer types are compatible.
3529 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3530 // differently qualified versions of compatible types, the result type is
3531 // a pointer to an appropriately qualified version of the *composite*
3532 // type.
3533 // FIXME: Need to calculate the composite type.
3534 // FIXME: Need to add qualifiers
3535 ImpCastExprToType(LHS, LHSTy);
3536 ImpCastExprToType(RHS, LHSTy);
3537 return LHSTy;
3538 }
Mike Stump11289f42009-09-09 15:08:12 +00003539
Steve Naroff05efa972009-07-01 14:36:47 +00003540 // GCC compatibility: soften pointer/integer mismatch.
3541 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3542 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3543 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3544 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3545 return RHSTy;
3546 }
3547 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3548 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3549 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3550 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3551 return LHSTy;
3552 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00003553
Chris Lattnere2949f42008-01-06 22:42:25 +00003554 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00003555 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3556 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003557 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00003558}
3559
Steve Naroff83895f72007-09-16 03:34:24 +00003560/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00003561/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003562Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3563 SourceLocation ColonLoc,
3564 ExprArg Cond, ExprArg LHS,
3565 ExprArg RHS) {
3566 Expr *CondExpr = (Expr *) Cond.get();
3567 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00003568
3569 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3570 // was the condition.
3571 bool isLHSNull = LHSExpr == 0;
3572 if (isLHSNull)
3573 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00003574
3575 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00003576 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00003577 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003578 return ExprError();
3579
3580 Cond.release();
3581 LHS.release();
3582 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00003583 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00003584 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00003585 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00003586}
3587
Steve Naroff3f597292007-05-11 22:18:03 +00003588// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00003589// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00003590// routine is it effectively iqnores the qualifiers on the top level pointee.
3591// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3592// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003593Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003594Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00003595 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003596
David Chisnall9f57c292009-08-17 16:35:33 +00003597 if ((lhsType->isObjCClassType() &&
3598 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3599 (rhsType->isObjCClassType() &&
3600 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3601 return Compatible;
3602 }
3603
Steve Naroff1f4d7272007-05-11 04:00:31 +00003604 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003605 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3606 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003607
Steve Naroff1f4d7272007-05-11 04:00:31 +00003608 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00003609 lhptee = Context.getCanonicalType(lhptee);
3610 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00003611
Chris Lattner9bad62c2008-01-04 18:04:52 +00003612 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003613
3614 // C99 6.5.16.1p1: This following citation is common to constraints
3615 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3616 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00003617 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00003618 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00003619 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00003620
Mike Stump4e1f26a2009-02-19 03:04:26 +00003621 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3622 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00003623 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00003624 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003625 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003626 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003627
Chris Lattner0a788432008-01-03 22:56:36 +00003628 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003629 assert(rhptee->isFunctionType());
3630 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003631 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003632
Chris Lattner0a788432008-01-03 22:56:36 +00003633 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003634 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003635 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00003636
3637 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003638 assert(lhptee->isFunctionType());
3639 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003640 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003641 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00003642 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00003643 lhptee = lhptee.getUnqualifiedType();
3644 rhptee = rhptee.getUnqualifiedType();
3645 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3646 // Check if the pointee types are compatible ignoring the sign.
3647 // We explicitly check for char so that we catch "char" vs
3648 // "unsigned char" on systems where "char" is unsigned.
3649 if (lhptee->isCharType()) {
3650 lhptee = Context.UnsignedCharTy;
3651 } else if (lhptee->isSignedIntegerType()) {
3652 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3653 }
3654 if (rhptee->isCharType()) {
3655 rhptee = Context.UnsignedCharTy;
3656 } else if (rhptee->isSignedIntegerType()) {
3657 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3658 }
3659 if (lhptee == rhptee) {
3660 // Types are compatible ignoring the sign. Qualifier incompatibility
3661 // takes priority over sign incompatibility because the sign
3662 // warning can be disabled.
3663 if (ConvTy != Compatible)
3664 return ConvTy;
3665 return IncompatiblePointerSign;
3666 }
3667 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00003668 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00003669 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00003670 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00003671}
3672
Steve Naroff081c7422008-09-04 15:10:53 +00003673/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3674/// block pointer types are compatible or whether a block and normal pointer
3675/// are compatible. It is more restrict than comparing two function pointer
3676// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003677Sema::AssignConvertType
3678Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00003679 QualType rhsType) {
3680 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003681
Steve Naroff081c7422008-09-04 15:10:53 +00003682 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003683 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3684 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003685
Steve Naroff081c7422008-09-04 15:10:53 +00003686 // make sure we operate on the canonical type
3687 lhptee = Context.getCanonicalType(lhptee);
3688 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003689
Steve Naroff081c7422008-09-04 15:10:53 +00003690 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003691
Steve Naroff081c7422008-09-04 15:10:53 +00003692 // For blocks we enforce that qualifiers are identical.
3693 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3694 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003695
Eli Friedmana6638ca2009-06-08 05:08:54 +00003696 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00003697 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00003698 return ConvTy;
3699}
3700
Mike Stump4e1f26a2009-02-19 03:04:26 +00003701/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3702/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00003703/// pointers. Here are some objectionable examples that GCC considers warnings:
3704///
3705/// int a, *pint;
3706/// short *pshort;
3707/// struct foo *pfoo;
3708///
3709/// pint = pshort; // warning: assignment from incompatible pointer type
3710/// a = pint; // warning: assignment makes integer from pointer without a cast
3711/// pint = a; // warning: assignment makes pointer from integer without a cast
3712/// pint = pfoo; // warning: assignment from incompatible pointer type
3713///
3714/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00003715/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00003716///
Chris Lattner9bad62c2008-01-04 18:04:52 +00003717Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003718Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00003719 // Get canonical types. We're not formatting these types, just comparing
3720 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00003721 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3722 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00003723
3724 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00003725 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00003726
David Chisnall9f57c292009-08-17 16:35:33 +00003727 if ((lhsType->isObjCClassType() &&
3728 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3729 (rhsType->isObjCClassType() &&
3730 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3731 return Compatible;
3732 }
3733
Douglas Gregor6b754842008-10-28 00:22:11 +00003734 // If the left-hand side is a reference type, then we are in a
3735 // (rare!) case where we've allowed the use of references in C,
3736 // e.g., as a parameter type in a built-in function. In this case,
3737 // just make sure that the type referenced is compatible with the
3738 // right-hand side type. The caller is responsible for adjusting
3739 // lhsType so that the resulting expression does not have reference
3740 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003741 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00003742 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00003743 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003744 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00003745 }
Nate Begemanbd956c42009-06-28 02:36:38 +00003746 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3747 // to the same ExtVector type.
3748 if (lhsType->isExtVectorType()) {
3749 if (rhsType->isExtVectorType())
3750 return lhsType == rhsType ? Compatible : Incompatible;
3751 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3752 return Compatible;
3753 }
Mike Stump11289f42009-09-09 15:08:12 +00003754
Nate Begeman191a6b12008-07-14 18:02:46 +00003755 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003756 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00003757 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00003758 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00003759 if (getLangOptions().LaxVectorConversions &&
3760 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003761 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00003762 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00003763 }
3764 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003765 }
Eli Friedman3360d892008-05-30 18:07:22 +00003766
Chris Lattner881a2122008-01-04 23:32:24 +00003767 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00003768 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00003769
Chris Lattnerec646832008-04-07 06:49:41 +00003770 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003771 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003772 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00003773
Chris Lattnerec646832008-04-07 06:49:41 +00003774 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003775 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003776
Steve Naroffaccc4882009-07-20 17:56:53 +00003777 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003778 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003779 if (lhsType->isVoidPointerType()) // an exception to the rule.
3780 return Compatible;
3781 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003782 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003783 if (rhsType->getAs<BlockPointerType>()) {
3784 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003785 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00003786
3787 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003788 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003789 return Compatible;
3790 }
Steve Naroff081c7422008-09-04 15:10:53 +00003791 return Incompatible;
3792 }
3793
3794 if (isa<BlockPointerType>(lhsType)) {
3795 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00003796 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003797
Steve Naroff32d072c2008-09-29 18:10:17 +00003798 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003799 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003800 return Compatible;
3801
Steve Naroff081c7422008-09-04 15:10:53 +00003802 if (rhsType->isBlockPointerType())
3803 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003804
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003805 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00003806 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003807 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00003808 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00003809 return Incompatible;
3810 }
3811
Steve Naroff7cae42b2009-07-10 23:34:53 +00003812 if (isa<ObjCObjectPointerType>(lhsType)) {
3813 if (rhsType->isIntegerType())
3814 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00003815
Steve Naroffaccc4882009-07-20 17:56:53 +00003816 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003817 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003818 if (rhsType->isVoidPointerType()) // an exception to the rule.
3819 return Compatible;
3820 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003821 }
3822 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003823 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3824 return Compatible;
Steve Naroffaccc4882009-07-20 17:56:53 +00003825 if (Context.typesAreCompatible(lhsType, rhsType))
3826 return Compatible;
Steve Naroff8e6aee52009-07-23 01:01:38 +00003827 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3828 return IncompatibleObjCQualifiedId;
Steve Naroffaccc4882009-07-20 17:56:53 +00003829 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003830 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003831 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003832 if (RHSPT->getPointeeType()->isVoidType())
3833 return Compatible;
3834 }
3835 // Treat block pointers as objects.
3836 if (rhsType->isBlockPointerType())
3837 return Compatible;
3838 return Incompatible;
3839 }
Chris Lattnerec646832008-04-07 06:49:41 +00003840 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003841 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00003842 if (lhsType == Context.BoolTy)
3843 return Compatible;
3844
3845 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003846 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00003847
Mike Stump4e1f26a2009-02-19 03:04:26 +00003848 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003849 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003850
3851 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003852 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003853 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003854 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003855 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00003856 if (isa<ObjCObjectPointerType>(rhsType)) {
3857 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3858 if (lhsType == Context.BoolTy)
3859 return Compatible;
3860
3861 if (lhsType->isIntegerType())
3862 return PointerToInt;
3863
Steve Naroffaccc4882009-07-20 17:56:53 +00003864 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003865 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003866 if (lhsType->isVoidPointerType()) // an exception to the rule.
3867 return Compatible;
3868 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003869 }
3870 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003871 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00003872 return Compatible;
3873 return Incompatible;
3874 }
Eli Friedman3360d892008-05-30 18:07:22 +00003875
Chris Lattnera52c2f22008-01-04 23:18:45 +00003876 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00003877 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003878 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00003879 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00003880 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00003881}
3882
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003883/// \brief Constructs a transparent union from an expression that is
3884/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00003885static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003886 QualType UnionType, FieldDecl *Field) {
3887 // Build an initializer list that designates the appropriate member
3888 // of the transparent union.
3889 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3890 &E, 1,
3891 SourceLocation());
3892 Initializer->setType(UnionType);
3893 Initializer->setInitializedFieldInUnion(Field);
3894
3895 // Build a compound literal constructing a value of the transparent
3896 // union type from this initializer list.
3897 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3898 false);
3899}
3900
3901Sema::AssignConvertType
3902Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3903 QualType FromType = rExpr->getType();
3904
Mike Stump11289f42009-09-09 15:08:12 +00003905 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003906 // transparent_union GCC extension.
3907 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003908 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003909 return Incompatible;
3910
3911 // The field to initialize within the transparent union.
3912 RecordDecl *UD = UT->getDecl();
3913 FieldDecl *InitField = 0;
3914 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003915 for (RecordDecl::field_iterator it = UD->field_begin(),
3916 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003917 it != itend; ++it) {
3918 if (it->getType()->isPointerType()) {
3919 // If the transparent union contains a pointer type, we allow:
3920 // 1) void pointer
3921 // 2) null pointer constant
3922 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003923 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003924 ImpCastExprToType(rExpr, it->getType());
3925 InitField = *it;
3926 break;
3927 }
Mike Stump11289f42009-09-09 15:08:12 +00003928
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003929 if (rExpr->isNullPointerConstant(Context)) {
3930 ImpCastExprToType(rExpr, it->getType());
3931 InitField = *it;
3932 break;
3933 }
3934 }
3935
3936 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3937 == Compatible) {
3938 InitField = *it;
3939 break;
3940 }
3941 }
3942
3943 if (!InitField)
3944 return Incompatible;
3945
3946 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3947 return Compatible;
3948}
3949
Chris Lattner9bad62c2008-01-04 18:04:52 +00003950Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00003951Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003952 if (getLangOptions().CPlusPlus) {
3953 if (!lhsType->isRecordType()) {
3954 // C++ 5.17p3: If the left operand is not of class type, the
3955 // expression is implicitly converted (C++ 4) to the
3956 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00003957 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3958 "assigning"))
Douglas Gregor9a657932008-10-21 23:43:52 +00003959 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00003960 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00003961 }
3962
3963 // FIXME: Currently, we fall through and treat C++ classes like C
3964 // structures.
3965 }
3966
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00003967 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3968 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00003969 if ((lhsType->isPointerType() ||
3970 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00003971 lhsType->isBlockPointerType())
Fariborz Jahanian5cc21a72008-01-03 18:46:52 +00003972 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnera65e1f32008-01-16 19:17:22 +00003973 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00003974 return Compatible;
3975 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003976
Chris Lattnere6dcd502007-10-16 02:55:40 +00003977 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00003978 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff30d242c2007-09-15 18:49:24 +00003979 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00003980 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00003981 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00003982 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00003983 if (!lhsType->isReferenceType())
3984 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00003985
Chris Lattner9bad62c2008-01-04 18:04:52 +00003986 Sema::AssignConvertType result =
3987 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00003988
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00003989 // C99 6.5.16.1p2: The value of the right operand is converted to the
3990 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00003991 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3992 // so that we can use references in built-in functions even in C.
3993 // The getNonReferenceType() call makes sure that the resulting expression
3994 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003995 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor6b754842008-10-28 00:22:11 +00003996 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00003997 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00003998}
3999
Chris Lattner326f7572008-11-18 01:30:42 +00004000QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004001 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004002 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004003 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004004 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004005}
4006
Mike Stump4e1f26a2009-02-19 03:04:26 +00004007inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004008 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004009 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004010 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004011 QualType lhsType =
4012 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4013 QualType rhsType =
4014 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004015
Nate Begeman191a6b12008-07-14 18:02:46 +00004016 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004017 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004018 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004019
Nate Begeman191a6b12008-07-14 18:02:46 +00004020 // Handle the case of a vector & extvector type of the same size and element
4021 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004022 if (getLangOptions().LaxVectorConversions) {
4023 // FIXME: Should we warn here?
4024 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004025 if (const VectorType *RV = rhsType->getAsVectorType())
4026 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004027 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004028 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004029 }
4030 }
4031 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004032
Nate Begemanbd956c42009-06-28 02:36:38 +00004033 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4034 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4035 bool swapped = false;
4036 if (rhsType->isExtVectorType()) {
4037 swapped = true;
4038 std::swap(rex, lex);
4039 std::swap(rhsType, lhsType);
4040 }
Mike Stump11289f42009-09-09 15:08:12 +00004041
Nate Begeman886448d2009-06-28 19:12:57 +00004042 // Handle the case of an ext vector and scalar.
Nate Begemanbd956c42009-06-28 02:36:38 +00004043 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
4044 QualType EltTy = LV->getElementType();
4045 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4046 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begeman886448d2009-06-28 19:12:57 +00004047 ImpCastExprToType(rex, lhsType);
Nate Begemanbd956c42009-06-28 02:36:38 +00004048 if (swapped) std::swap(rex, lex);
4049 return lhsType;
4050 }
4051 }
4052 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4053 rhsType->isRealFloatingType()) {
4054 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begeman886448d2009-06-28 19:12:57 +00004055 ImpCastExprToType(rex, lhsType);
Nate Begemanbd956c42009-06-28 02:36:38 +00004056 if (swapped) std::swap(rex, lex);
4057 return lhsType;
4058 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004059 }
4060 }
Mike Stump11289f42009-09-09 15:08:12 +00004061
Nate Begeman886448d2009-06-28 19:12:57 +00004062 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004063 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004064 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004065 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004066 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004067}
4068
Steve Naroff218bc2b2007-05-04 21:54:46 +00004069inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004070 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004071 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004072 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004073
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004074 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004075
Steve Naroffdbd9e892007-07-17 00:58:39 +00004076 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004077 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004078 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004079}
4080
Steve Naroff218bc2b2007-05-04 21:54:46 +00004081inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004082 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004083 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4084 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4085 return CheckVectorOperands(Loc, lex, rex);
4086 return InvalidOperands(Loc, lex, rex);
4087 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004088
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004089 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004090
Steve Naroffdbd9e892007-07-17 00:58:39 +00004091 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004092 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004093 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004094}
4095
4096inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004097 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004098 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4099 QualType compType = CheckVectorOperands(Loc, lex, rex);
4100 if (CompLHSTy) *CompLHSTy = compType;
4101 return compType;
4102 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004103
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004104 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004105
Steve Naroffe4718892007-04-27 18:30:00 +00004106 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004107 if (lex->getType()->isArithmeticType() &&
4108 rex->getType()->isArithmeticType()) {
4109 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004110 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004111 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004112
Eli Friedman8e122982008-05-18 18:08:51 +00004113 // Put any potential pointer into PExp
4114 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004115 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004116 std::swap(PExp, IExp);
4117
Steve Naroff6b712a72009-07-14 18:25:06 +00004118 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004119
Eli Friedman8e122982008-05-18 18:08:51 +00004120 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004121 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004122
Chris Lattner12bdebb2009-04-24 23:50:08 +00004123 // Check for arithmetic on pointers to incomplete types.
4124 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004125 if (getLangOptions().CPlusPlus) {
4126 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004127 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004128 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004129 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004130
4131 // GNU extension: arithmetic on pointer to void
4132 Diag(Loc, diag::ext_gnu_void_ptr)
4133 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004134 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004135 if (getLangOptions().CPlusPlus) {
4136 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4137 << lex->getType() << lex->getSourceRange();
4138 return QualType();
4139 }
4140
4141 // GNU extension: arithmetic on pointer to function
4142 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4143 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004144 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004145 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004146 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004147 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004148 PExp->getType()->isObjCObjectPointerType()) &&
4149 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004150 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4151 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004152 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004153 return QualType();
4154 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004155 // Diagnose bad cases where we step over interface counts.
4156 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4157 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4158 << PointeeTy << PExp->getSourceRange();
4159 return QualType();
4160 }
Mike Stump11289f42009-09-09 15:08:12 +00004161
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004162 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004163 QualType LHSTy = Context.isPromotableBitField(lex);
4164 if (LHSTy.isNull()) {
4165 LHSTy = lex->getType();
4166 if (LHSTy->isPromotableIntegerType())
4167 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004168 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004169 *CompLHSTy = LHSTy;
4170 }
Eli Friedman8e122982008-05-18 18:08:51 +00004171 return PExp->getType();
4172 }
4173 }
4174
Chris Lattner326f7572008-11-18 01:30:42 +00004175 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004176}
4177
Chris Lattner2a3569b2008-04-07 05:30:13 +00004178// C99 6.5.6
4179QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004180 SourceLocation Loc, QualType* CompLHSTy) {
4181 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4182 QualType compType = CheckVectorOperands(Loc, lex, rex);
4183 if (CompLHSTy) *CompLHSTy = compType;
4184 return compType;
4185 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004186
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004187 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004188
Chris Lattner4d62f422007-12-09 21:53:25 +00004189 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004190
Chris Lattner4d62f422007-12-09 21:53:25 +00004191 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004192 if (lex->getType()->isArithmeticType()
4193 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004194 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004195 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004196 }
Mike Stump11289f42009-09-09 15:08:12 +00004197
Chris Lattner4d62f422007-12-09 21:53:25 +00004198 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004199 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004200 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004201
Douglas Gregorac1fb652009-03-24 19:52:54 +00004202 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004203
Douglas Gregorac1fb652009-03-24 19:52:54 +00004204 bool ComplainAboutVoid = false;
4205 Expr *ComplainAboutFunc = 0;
4206 if (lpointee->isVoidType()) {
4207 if (getLangOptions().CPlusPlus) {
4208 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4209 << lex->getSourceRange() << rex->getSourceRange();
4210 return QualType();
4211 }
4212
4213 // GNU C extension: arithmetic on pointer to void
4214 ComplainAboutVoid = true;
4215 } else if (lpointee->isFunctionType()) {
4216 if (getLangOptions().CPlusPlus) {
4217 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004218 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004219 return QualType();
4220 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004221
4222 // GNU C extension: arithmetic on pointer to function
4223 ComplainAboutFunc = lex;
4224 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004225 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004226 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004227 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004228 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004229 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004230
Chris Lattner12bdebb2009-04-24 23:50:08 +00004231 // Diagnose bad cases where we step over interface counts.
4232 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4233 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4234 << lpointee << lex->getSourceRange();
4235 return QualType();
4236 }
Mike Stump11289f42009-09-09 15:08:12 +00004237
Chris Lattner4d62f422007-12-09 21:53:25 +00004238 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004239 if (rex->getType()->isIntegerType()) {
4240 if (ComplainAboutVoid)
4241 Diag(Loc, diag::ext_gnu_void_ptr)
4242 << lex->getSourceRange() << rex->getSourceRange();
4243 if (ComplainAboutFunc)
4244 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004245 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004246 << ComplainAboutFunc->getSourceRange();
4247
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004248 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004249 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004250 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004251
Chris Lattner4d62f422007-12-09 21:53:25 +00004252 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004253 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004254 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004255
Douglas Gregorac1fb652009-03-24 19:52:54 +00004256 // RHS must be a completely-type object type.
4257 // Handle the GNU void* extension.
4258 if (rpointee->isVoidType()) {
4259 if (getLangOptions().CPlusPlus) {
4260 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4261 << lex->getSourceRange() << rex->getSourceRange();
4262 return QualType();
4263 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004264
Douglas Gregorac1fb652009-03-24 19:52:54 +00004265 ComplainAboutVoid = true;
4266 } else if (rpointee->isFunctionType()) {
4267 if (getLangOptions().CPlusPlus) {
4268 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004269 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004270 return QualType();
4271 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004272
4273 // GNU extension: arithmetic on pointer to function
4274 if (!ComplainAboutFunc)
4275 ComplainAboutFunc = rex;
4276 } else if (!rpointee->isDependentType() &&
4277 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004278 PDiag(diag::err_typecheck_sub_ptr_object)
4279 << rex->getSourceRange()
4280 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004281 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004282
Eli Friedman168fe152009-05-16 13:54:38 +00004283 if (getLangOptions().CPlusPlus) {
4284 // Pointee types must be the same: C++ [expr.add]
4285 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4286 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4287 << lex->getType() << rex->getType()
4288 << lex->getSourceRange() << rex->getSourceRange();
4289 return QualType();
4290 }
4291 } else {
4292 // Pointee types must be compatible C99 6.5.6p3
4293 if (!Context.typesAreCompatible(
4294 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4295 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4296 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4297 << lex->getType() << rex->getType()
4298 << lex->getSourceRange() << rex->getSourceRange();
4299 return QualType();
4300 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004301 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004302
Douglas Gregorac1fb652009-03-24 19:52:54 +00004303 if (ComplainAboutVoid)
4304 Diag(Loc, diag::ext_gnu_void_ptr)
4305 << lex->getSourceRange() << rex->getSourceRange();
4306 if (ComplainAboutFunc)
4307 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004308 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004309 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004310
4311 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004312 return Context.getPointerDiffType();
4313 }
4314 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004315
Chris Lattner326f7572008-11-18 01:30:42 +00004316 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004317}
4318
Chris Lattner2a3569b2008-04-07 05:30:13 +00004319// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004320QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004321 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00004322 // C99 6.5.7p2: Each of the operands shall have integer type.
4323 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00004324 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004325
Chris Lattner5c11c412007-12-12 05:47:28 +00004326 // Shifts don't perform usual arithmetic conversions, they just do integer
4327 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00004328 QualType LHSTy = Context.isPromotableBitField(lex);
4329 if (LHSTy.isNull()) {
4330 LHSTy = lex->getType();
4331 if (LHSTy->isPromotableIntegerType())
4332 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004333 }
Chris Lattner3c133402007-12-13 07:28:16 +00004334 if (!isCompAssign)
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004335 ImpCastExprToType(lex, LHSTy);
4336
Chris Lattner5c11c412007-12-12 05:47:28 +00004337 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004338
Ryan Flynnf53fab82009-08-07 16:20:20 +00004339 // Sanity-check shift operands
4340 llvm::APSInt Right;
4341 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00004342 if (!rex->isValueDependent() &&
4343 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00004344 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00004345 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4346 else {
4347 llvm::APInt LeftBits(Right.getBitWidth(),
4348 Context.getTypeSize(lex->getType()));
4349 if (Right.uge(LeftBits))
4350 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4351 }
4352 }
4353
Chris Lattner5c11c412007-12-12 05:47:28 +00004354 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004355 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004356}
4357
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004358// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00004359QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004360 unsigned OpaqueOpc, bool isRelational) {
4361 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4362
Nate Begeman191a6b12008-07-14 18:02:46 +00004363 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004364 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004365
Chris Lattnerb620c342007-08-26 01:18:55 +00004366 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00004367 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4368 UsualArithmeticConversions(lex, rex);
4369 else {
4370 UsualUnaryConversions(lex);
4371 UsualUnaryConversions(rex);
4372 }
Steve Naroff31090012007-07-16 21:54:35 +00004373 QualType lType = lex->getType();
4374 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004375
Mike Stumpf70bcf72009-05-07 18:43:07 +00004376 if (!lType->isFloatingType()
4377 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004378 // For non-floating point types, check for self-comparisons of the form
4379 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4380 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00004381 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00004382 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004383 Expr *LHSStripped = lex->IgnoreParens();
4384 Expr *RHSStripped = rex->IgnoreParens();
4385 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4386 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00004387 if (DRL->getDecl() == DRR->getDecl() &&
4388 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004389 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00004390
Chris Lattner222b8bd2009-03-08 19:39:53 +00004391 if (isa<CastExpr>(LHSStripped))
4392 LHSStripped = LHSStripped->IgnoreParenCasts();
4393 if (isa<CastExpr>(RHSStripped))
4394 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004395
Chris Lattner222b8bd2009-03-08 19:39:53 +00004396 // Warn about comparisons against a string constant (unless the other
4397 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004398 Expr *literalString = 0;
4399 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00004400 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004401 !RHSStripped->isNullPointerConstant(Context)) {
4402 literalString = lex;
4403 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00004404 } else if ((isa<StringLiteral>(RHSStripped) ||
4405 isa<ObjCEncodeExpr>(RHSStripped)) &&
4406 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004407 literalString = rex;
4408 literalStringStripped = RHSStripped;
4409 }
4410
4411 if (literalString) {
4412 std::string resultComparison;
4413 switch (Opc) {
4414 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4415 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4416 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4417 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4418 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4419 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4420 default: assert(false && "Invalid comparison operator");
4421 }
4422 Diag(Loc, diag::warn_stringcompare)
4423 << isa<ObjCEncodeExpr>(literalStringStripped)
4424 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00004425 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4426 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4427 "strcmp(")
4428 << CodeModificationHint::CreateInsertion(
4429 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004430 resultComparison);
4431 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00004432 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004433
Douglas Gregorca63811b2008-11-19 03:25:36 +00004434 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004435 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00004436
Chris Lattnerb620c342007-08-26 01:18:55 +00004437 if (isRelational) {
4438 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004439 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004440 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00004441 // Check for comparisons of floating point operands using != and ==.
Ted Kremeneke2763b02007-10-29 17:13:39 +00004442 if (lType->isFloatingType()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004443 assert(rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004444 CheckFloatComparison(Loc,lex,rex);
Ted Kremenekd4ecc6d2007-10-29 16:40:01 +00004445 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004446
Chris Lattnerb620c342007-08-26 01:18:55 +00004447 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004448 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004449 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004450
Chris Lattner1895e582007-08-26 01:10:14 +00004451 bool LHSIsNull = lex->isNullPointerConstant(Context);
4452 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004453
Chris Lattnerb620c342007-08-26 01:18:55 +00004454 // All of the following pointer related warnings are GCC extensions, except
4455 // when handling null pointer constants. One day, we can consider making them
4456 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00004457 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00004458 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004459 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00004460 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004461 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004462
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004463 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00004464 if (LCanPointeeTy == RCanPointeeTy)
4465 return ResultTy;
4466
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004467 // C++ [expr.rel]p2:
4468 // [...] Pointer conversions (4.10) and qualification
4469 // conversions (4.4) are performed on pointer operands (or on
4470 // a pointer operand and a null pointer constant) to bring
4471 // them to their composite pointer type. [...]
4472 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004473 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004474 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00004475 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004476 if (T.isNull()) {
4477 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4478 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4479 return QualType();
4480 }
4481
4482 ImpCastExprToType(lex, T);
4483 ImpCastExprToType(rex, T);
4484 return ResultTy;
4485 }
Eli Friedman16c209612009-08-23 00:27:47 +00004486 // C99 6.5.9p2 and C99 6.5.8p2
4487 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4488 RCanPointeeTy.getUnqualifiedType())) {
4489 // Valid unless a relational comparison of function pointers
4490 if (isRelational && LCanPointeeTy->isFunctionType()) {
4491 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4492 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4493 }
4494 } else if (!isRelational &&
4495 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4496 // Valid unless comparison between non-null pointer and function pointer
4497 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4498 && !LHSIsNull && !RHSIsNull) {
4499 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4500 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4501 }
4502 } else {
4503 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00004504 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004505 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00004506 }
Eli Friedman16c209612009-08-23 00:27:47 +00004507 if (LCanPointeeTy != RCanPointeeTy)
4508 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004509 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004510 }
Mike Stump11289f42009-09-09 15:08:12 +00004511
Sebastian Redl576fd422009-05-10 18:38:11 +00004512 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00004513 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004514 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00004515 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004516 (lType->isPointerType() ||
4517 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004518 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004519 return ResultTy;
4520 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004521 if (LHSIsNull &&
4522 (rType->isPointerType() ||
4523 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004524 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004525 return ResultTy;
4526 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004527
4528 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00004529 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004530 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4531 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004532 // In addition, pointers to members can be compared, or a pointer to
4533 // member and a null pointer constant. Pointer to member conversions
4534 // (4.11) and qualification conversions (4.4) are performed to bring
4535 // them to a common type. If one operand is a null pointer constant,
4536 // the common type is the type of the other operand. Otherwise, the
4537 // common type is a pointer to member type similar (4.4) to the type
4538 // of one of the operands, with a cv-qualification signature (4.4)
4539 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004540 // types.
4541 QualType T = FindCompositePointerType(lex, rex);
4542 if (T.isNull()) {
4543 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4544 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4545 return QualType();
4546 }
Mike Stump11289f42009-09-09 15:08:12 +00004547
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004548 ImpCastExprToType(lex, T);
4549 ImpCastExprToType(rex, T);
4550 return ResultTy;
4551 }
Mike Stump11289f42009-09-09 15:08:12 +00004552
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004553 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00004554 if (lType->isNullPtrType() && rType->isNullPtrType())
4555 return ResultTy;
4556 }
Mike Stump11289f42009-09-09 15:08:12 +00004557
Steve Naroff081c7422008-09-04 15:10:53 +00004558 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00004559 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004560 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4561 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004562
Steve Naroff081c7422008-09-04 15:10:53 +00004563 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00004564 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004565 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004566 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00004567 }
4568 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004569 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00004570 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00004571 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00004572 if (!isRelational
4573 && ((lType->isBlockPointerType() && rType->isPointerType())
4574 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00004575 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004576 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004577 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004578 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004579 ->getPointeeType()->isVoidType())))
4580 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4581 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00004582 }
4583 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004584 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00004585 }
Steve Naroff081c7422008-09-04 15:10:53 +00004586
Steve Naroff7cae42b2009-07-10 23:34:53 +00004587 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004588 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004589 const PointerType *LPT = lType->getAs<PointerType>();
4590 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004591 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004592 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004593 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004594 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004595
Steve Naroff753567f2008-11-17 19:49:16 +00004596 if (!LPtrToVoid && !RPtrToVoid &&
4597 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004598 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004599 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004600 }
Daniel Dunbar340b5dd2008-10-23 23:30:52 +00004601 ImpCastExprToType(rex, lType);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004602 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00004603 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004604 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004605 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004606 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4607 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffb788d9b2008-06-03 14:04:54 +00004608 ImpCastExprToType(rex, lType);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004609 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00004610 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00004611 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004612 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004613 unsigned DiagID = 0;
4614 if (RHSIsNull) {
4615 if (isRelational)
4616 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4617 } else if (isRelational)
4618 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4619 else
4620 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004621
Chris Lattnerd99bd522009-08-23 00:03:44 +00004622 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004623 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004624 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004625 }
Chris Lattnera65e1f32008-01-16 19:17:22 +00004626 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004627 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004628 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004629 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004630 unsigned DiagID = 0;
4631 if (LHSIsNull) {
4632 if (isRelational)
4633 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4634 } else if (isRelational)
4635 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4636 else
4637 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004638
Chris Lattnerd99bd522009-08-23 00:03:44 +00004639 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004640 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004641 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004642 }
Chris Lattnera65e1f32008-01-16 19:17:22 +00004643 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004644 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00004645 }
Steve Naroff4b191572008-09-04 16:56:14 +00004646 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00004647 if (!isRelational && RHSIsNull
4648 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4b191572008-09-04 16:56:14 +00004649 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004650 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004651 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00004652 if (!isRelational && LHSIsNull
4653 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4b191572008-09-04 16:56:14 +00004654 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004655 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004656 }
Chris Lattner326f7572008-11-18 01:30:42 +00004657 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004658}
4659
Nate Begeman191a6b12008-07-14 18:02:46 +00004660/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00004661/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00004662/// like a scalar comparison, a vector comparison produces a vector of integer
4663/// types.
4664QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00004665 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00004666 bool isRelational) {
4667 // Check to make sure we're operating on vectors of the same type and width,
4668 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00004669 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004670 if (vType.isNull())
4671 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004672
Nate Begeman191a6b12008-07-14 18:02:46 +00004673 QualType lType = lex->getType();
4674 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004675
Nate Begeman191a6b12008-07-14 18:02:46 +00004676 // For non-floating point types, check for self-comparisons of the form
4677 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4678 // often indicate logic errors in the program.
4679 if (!lType->isFloatingType()) {
4680 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4681 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4682 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004683 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00004684 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004685
Nate Begeman191a6b12008-07-14 18:02:46 +00004686 // Check for comparisons of floating point operands using != and ==.
4687 if (!isRelational && lType->isFloatingType()) {
4688 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004689 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004690 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004691
Nate Begeman191a6b12008-07-14 18:02:46 +00004692 // Return the type for the comparison, which is the same as vector type for
4693 // integer vectors, or an integer type of identical size and number of
4694 // elements for floating point vectors.
4695 if (lType->isIntegerType())
4696 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004697
Nate Begeman191a6b12008-07-14 18:02:46 +00004698 const VectorType *VTy = lType->getAsVectorType();
Nate Begeman191a6b12008-07-14 18:02:46 +00004699 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004700 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00004701 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00004702 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004703 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4704
Mike Stump4e1f26a2009-02-19 03:04:26 +00004705 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004706 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00004707 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4708}
4709
Steve Naroff218bc2b2007-05-04 21:54:46 +00004710inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004711 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00004712 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004713 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004714
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004715 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004716
Steve Naroffdbd9e892007-07-17 00:58:39 +00004717 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004718 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004719 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004720}
4721
Steve Naroff218bc2b2007-05-04 21:54:46 +00004722inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00004723 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroff31090012007-07-16 21:54:35 +00004724 UsualUnaryConversions(lex);
4725 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004726
Eli Friedman58639e52008-05-13 20:16:47 +00004727 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Steve Naroff218bc2b2007-05-04 21:54:46 +00004728 return Context.IntTy;
Chris Lattner326f7572008-11-18 01:30:42 +00004729 return InvalidOperands(Loc, lex, rex);
Steve Naroffae4143e2007-04-26 20:39:23 +00004730}
4731
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004732/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4733/// is a read-only property; return true if so. A readonly property expression
4734/// depends on various declarations and thus must be treated specially.
4735///
Mike Stump11289f42009-09-09 15:08:12 +00004736static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004737 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4738 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4739 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4740 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004741 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00004742 BaseType->getAsObjCInterfacePointerType())
4743 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4744 if (S.isPropertyReadonly(PDecl, IFace))
4745 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004746 }
4747 }
4748 return false;
4749}
4750
Chris Lattner30bd3272008-11-18 01:22:49 +00004751/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4752/// emit an error and return true. If so, return false.
4753static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004754 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00004755 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004756 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004757 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4758 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00004759 if (IsLV == Expr::MLV_Valid)
4760 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004761
Chris Lattner30bd3272008-11-18 01:22:49 +00004762 unsigned Diag = 0;
4763 bool NeedType = false;
4764 switch (IsLV) { // C99 6.5.16p2
4765 default: assert(0 && "Unknown result from isModifiableLvalue!");
4766 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004767 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004768 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4769 NeedType = true;
4770 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004771 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004772 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4773 NeedType = true;
4774 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00004775 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00004776 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4777 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004778 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00004779 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4780 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004781 case Expr::MLV_IncompleteType:
4782 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00004783 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00004784 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4785 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00004786 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00004787 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4788 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00004789 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00004790 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4791 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00004792 case Expr::MLV_ReadonlyProperty:
4793 Diag = diag::error_readonly_property_assignment;
4794 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00004795 case Expr::MLV_NoSetterProperty:
4796 Diag = diag::error_nosetter_property_assignment;
4797 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004798 }
Steve Naroffad373bd2007-07-31 12:34:36 +00004799
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004800 SourceRange Assign;
4801 if (Loc != OrigLoc)
4802 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00004803 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004804 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004805 else
Mike Stump11289f42009-09-09 15:08:12 +00004806 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004807 return true;
4808}
4809
4810
4811
4812// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00004813QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4814 SourceLocation Loc,
4815 QualType CompoundType) {
4816 // Verify that LHS is a modifiable lvalue, and emit error if not.
4817 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00004818 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00004819
4820 QualType LHSType = LHS->getType();
4821 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004822
Chris Lattner9bad62c2008-01-04 18:04:52 +00004823 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00004824 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00004825 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00004826 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004827 // Special case of NSObject attributes on c-style pointer types.
4828 if (ConvTy == IncompatiblePointer &&
4829 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00004830 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004831 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00004832 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004833 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004834
Chris Lattnerea714382008-08-21 18:04:13 +00004835 // If the RHS is a unary plus or minus, check to see if they = and + are
4836 // right next to each other. If so, the user may have typo'd "x =+ 4"
4837 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00004838 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00004839 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4840 RHSCheck = ICE->getSubExpr();
4841 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4842 if ((UO->getOpcode() == UnaryOperator::Plus ||
4843 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00004844 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00004845 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00004846 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4847 // And there is a space or other character before the subexpr of the
4848 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00004849 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4850 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00004851 Diag(Loc, diag::warn_not_compound_assign)
4852 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4853 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00004854 }
Chris Lattnerea714382008-08-21 18:04:13 +00004855 }
4856 } else {
4857 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00004858 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00004859 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004860
Chris Lattner326f7572008-11-18 01:30:42 +00004861 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4862 RHS, "assigning"))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004863 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004864
Steve Naroff98cf3e92007-06-06 18:38:38 +00004865 // C99 6.5.16p3: The type of an assignment expression is the type of the
4866 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00004867 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00004868 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4869 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00004870 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00004871 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00004872 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00004873}
4874
Chris Lattner326f7572008-11-18 01:30:42 +00004875// C99 6.5.17
4876QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00004877 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00004878 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00004879
4880 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4881 // incomplete in C++).
4882
Chris Lattner326f7572008-11-18 01:30:42 +00004883 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00004884}
4885
Steve Naroff7a5af782007-07-13 16:58:59 +00004886/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4887/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00004888QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4889 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004890 if (Op->isTypeDependent())
4891 return Context.DependentTy;
4892
Chris Lattner6b0cf142008-11-21 07:05:48 +00004893 QualType ResType = Op->getType();
4894 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00004895
Sebastian Redle10c2c32008-12-20 09:35:34 +00004896 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4897 // Decrement of bool is not allowed.
4898 if (!isInc) {
4899 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4900 return QualType();
4901 }
4902 // Increment of bool sets it to true, but is deprecated.
4903 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4904 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00004905 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00004906 } else if (ResType->isAnyPointerType()) {
4907 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004908
Chris Lattner6b0cf142008-11-21 07:05:48 +00004909 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00004910 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004911 if (getLangOptions().CPlusPlus) {
4912 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4913 << Op->getSourceRange();
4914 return QualType();
4915 }
4916
4917 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00004918 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004919 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004920 if (getLangOptions().CPlusPlus) {
4921 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4922 << Op->getType() << Op->getSourceRange();
4923 return QualType();
4924 }
4925
4926 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004927 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004928 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00004929 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004930 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004931 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00004932 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00004933 // Diagnose bad cases where we step over interface counts.
4934 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4935 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4936 << PointeeTy << Op->getSourceRange();
4937 return QualType();
4938 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00004939 } else if (ResType->isComplexType()) {
4940 // C99 does not support ++/-- on complex types, we allow as an extension.
4941 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004942 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00004943 } else {
4944 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004945 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00004946 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00004947 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004948 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00004949 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00004950 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00004951 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00004952 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004953}
4954
Anders Carlsson806700f2008-02-01 07:15:58 +00004955/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00004956/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00004957/// where the declaration is needed for type checking. We only need to
4958/// handle cases when the expression references a function designator
4959/// or is an lvalue. Here are some examples:
4960/// - &(x) => x
4961/// - &*****f => f for f a function designator.
4962/// - &s.xx => s
4963/// - &s.zz[1].yy -> s, if zz is an array
4964/// - *(x + 1) -> x, if x is an array
4965/// - &"123"[2] -> 0
4966/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004967static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004968 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00004969 case Stmt::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00004970 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004971 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00004972 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00004973 // If this is an arrow operator, the address is an offset from
4974 // the base's value, so the object the base refers to is
4975 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004976 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00004977 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00004978 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004979 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00004980 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00004981 // FIXME: This code shouldn't be necessary! We should catch the implicit
4982 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00004983 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4984 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4985 if (ICE->getSubExpr()->getType()->isArrayType())
4986 return getPrimaryDecl(ICE->getSubExpr());
4987 }
4988 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00004989 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00004990 case Stmt::UnaryOperatorClass: {
4991 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004992
Daniel Dunbarb692ef42008-08-04 20:02:37 +00004993 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00004994 case UnaryOperator::Real:
4995 case UnaryOperator::Imag:
4996 case UnaryOperator::Extension:
4997 return getPrimaryDecl(UO->getSubExpr());
4998 default:
4999 return 0;
5000 }
5001 }
Steve Naroff47500512007-04-19 23:00:49 +00005002 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005003 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005004 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005005 // If the result of an implicit cast is an l-value, we care about
5006 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005007 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005008 default:
5009 return 0;
5010 }
5011}
5012
5013/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005014/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005015/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005016/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005017/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005018/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005019/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005020QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005021 // Make sure to ignore parentheses in subsequent checks
5022 op = op->IgnoreParens();
5023
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005024 if (op->isTypeDependent())
5025 return Context.DependentTy;
5026
Steve Naroff826e91a2008-01-13 17:10:08 +00005027 if (getLangOptions().C99) {
5028 // Implement C99-only parts of addressof rules.
5029 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5030 if (uOp->getOpcode() == UnaryOperator::Deref)
5031 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5032 // (assuming the deref expression is valid).
5033 return uOp->getSubExpr()->getType();
5034 }
5035 // Technically, there should be a check for array subscript
5036 // expressions here, but the result of one is always an lvalue anyway.
5037 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005038 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005039 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005040
Eli Friedmance7f9002009-05-16 23:27:50 +00005041 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5042 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005043 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005044 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005045 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005046 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5047 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005048 return QualType();
5049 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005050 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005051 // The operand cannot be a bit-field
5052 Diag(OpLoc, diag::err_typecheck_address_of)
5053 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005054 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005055 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5056 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005057 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005058 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005059 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005060 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005061 } else if (isa<ObjCPropertyRefExpr>(op)) {
5062 // cannot take address of a property expression.
5063 Diag(OpLoc, diag::err_typecheck_address_of)
5064 << "property expression" << op->getSourceRange();
5065 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005066 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5067 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005068 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5069 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005070 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005071 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005072 // with the register storage-class specifier.
5073 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005074 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005075 Diag(OpLoc, diag::err_typecheck_address_of)
5076 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005077 return QualType();
5078 }
Douglas Gregor9b146582009-07-08 20:55:45 +00005079 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5080 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005081 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005082 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005083 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005084 // Could be a pointer to member, though, if there is an explicit
5085 // scope qualifier for the class.
5086 if (isa<QualifiedDeclRefExpr>(op)) {
5087 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005088 if (Ctx && Ctx->isRecord()) {
5089 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005090 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005091 diag::err_cannot_form_pointer_to_member_of_reference_type)
5092 << FD->getDeclName() << FD->getType();
5093 return QualType();
5094 }
Mike Stump11289f42009-09-09 15:08:12 +00005095
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005096 return Context.getMemberPointerType(op->getType(),
5097 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005098 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005099 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005100 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005101 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005102 // As above.
Anders Carlsson5b535762009-05-16 21:43:42 +00005103 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5104 return Context.getMemberPointerType(op->getType(),
5105 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5106 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005107 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005108 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005109
Eli Friedmance7f9002009-05-16 23:27:50 +00005110 if (lval == Expr::LV_IncompleteVoidType) {
5111 // Taking the address of a void variable is technically illegal, but we
5112 // allow it in cases which are otherwise valid.
5113 // Example: "extern void x; void* y = &x;".
5114 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5115 }
5116
Steve Naroff47500512007-04-19 23:00:49 +00005117 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005118 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005119}
5120
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005121QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005122 if (Op->isTypeDependent())
5123 return Context.DependentTy;
5124
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005125 UsualUnaryConversions(Op);
5126 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005127
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005128 // Note that per both C89 and C99, this is always legal, even if ptype is an
5129 // incomplete type or void. It would be possible to warn about dereferencing
5130 // a void pointer, but it's completely well-defined, and such a warning is
5131 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005132 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005133 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005134
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005135 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5136 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005137
Chris Lattner29e812b2008-11-20 06:06:08 +00005138 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005139 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005140 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005141}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005142
5143static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5144 tok::TokenKind Kind) {
5145 BinaryOperator::Opcode Opc;
5146 switch (Kind) {
5147 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005148 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5149 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005150 case tok::star: Opc = BinaryOperator::Mul; break;
5151 case tok::slash: Opc = BinaryOperator::Div; break;
5152 case tok::percent: Opc = BinaryOperator::Rem; break;
5153 case tok::plus: Opc = BinaryOperator::Add; break;
5154 case tok::minus: Opc = BinaryOperator::Sub; break;
5155 case tok::lessless: Opc = BinaryOperator::Shl; break;
5156 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5157 case tok::lessequal: Opc = BinaryOperator::LE; break;
5158 case tok::less: Opc = BinaryOperator::LT; break;
5159 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5160 case tok::greater: Opc = BinaryOperator::GT; break;
5161 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5162 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5163 case tok::amp: Opc = BinaryOperator::And; break;
5164 case tok::caret: Opc = BinaryOperator::Xor; break;
5165 case tok::pipe: Opc = BinaryOperator::Or; break;
5166 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5167 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5168 case tok::equal: Opc = BinaryOperator::Assign; break;
5169 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5170 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5171 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5172 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5173 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5174 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5175 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5176 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5177 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5178 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5179 case tok::comma: Opc = BinaryOperator::Comma; break;
5180 }
5181 return Opc;
5182}
5183
Steve Naroff35d85152007-05-07 00:24:15 +00005184static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5185 tok::TokenKind Kind) {
5186 UnaryOperator::Opcode Opc;
5187 switch (Kind) {
5188 default: assert(0 && "Unknown unary op!");
5189 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5190 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5191 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5192 case tok::star: Opc = UnaryOperator::Deref; break;
5193 case tok::plus: Opc = UnaryOperator::Plus; break;
5194 case tok::minus: Opc = UnaryOperator::Minus; break;
5195 case tok::tilde: Opc = UnaryOperator::Not; break;
5196 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005197 case tok::kw___real: Opc = UnaryOperator::Real; break;
5198 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00005199 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005200 }
5201 return Opc;
5202}
5203
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005204/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5205/// operator @p Opc at location @c TokLoc. This routine only supports
5206/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005207Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5208 unsigned Op,
5209 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005210 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005211 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005212 // The following two variables are used for compound assignment operators
5213 QualType CompLHSTy; // Type of LHS after promotions for computation
5214 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005215
5216 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005217 case BinaryOperator::Assign:
5218 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5219 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005220 case BinaryOperator::PtrMemD:
5221 case BinaryOperator::PtrMemI:
5222 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5223 Opc == BinaryOperator::PtrMemI);
5224 break;
5225 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005226 case BinaryOperator::Div:
5227 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5228 break;
5229 case BinaryOperator::Rem:
5230 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5231 break;
5232 case BinaryOperator::Add:
5233 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5234 break;
5235 case BinaryOperator::Sub:
5236 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5237 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005238 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005239 case BinaryOperator::Shr:
5240 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5241 break;
5242 case BinaryOperator::LE:
5243 case BinaryOperator::LT:
5244 case BinaryOperator::GE:
5245 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005246 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005247 break;
5248 case BinaryOperator::EQ:
5249 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005250 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005251 break;
5252 case BinaryOperator::And:
5253 case BinaryOperator::Xor:
5254 case BinaryOperator::Or:
5255 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5256 break;
5257 case BinaryOperator::LAnd:
5258 case BinaryOperator::LOr:
5259 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5260 break;
5261 case BinaryOperator::MulAssign:
5262 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005263 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5264 CompLHSTy = CompResultTy;
5265 if (!CompResultTy.isNull())
5266 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005267 break;
5268 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005269 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5270 CompLHSTy = CompResultTy;
5271 if (!CompResultTy.isNull())
5272 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005273 break;
5274 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005275 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5276 if (!CompResultTy.isNull())
5277 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005278 break;
5279 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005280 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5281 if (!CompResultTy.isNull())
5282 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005283 break;
5284 case BinaryOperator::ShlAssign:
5285 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005286 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5287 CompLHSTy = CompResultTy;
5288 if (!CompResultTy.isNull())
5289 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005290 break;
5291 case BinaryOperator::AndAssign:
5292 case BinaryOperator::XorAssign:
5293 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005294 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5295 CompLHSTy = CompResultTy;
5296 if (!CompResultTy.isNull())
5297 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005298 break;
5299 case BinaryOperator::Comma:
5300 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5301 break;
5302 }
5303 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005304 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005305 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00005306 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5307 else
5308 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005309 CompLHSTy, CompResultTy,
5310 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005311}
5312
Steve Naroff218bc2b2007-05-04 21:54:46 +00005313// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005314Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5315 tok::TokenKind Kind,
5316 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00005317 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00005318 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00005319
Steve Naroff83895f72007-09-16 03:34:24 +00005320 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5321 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00005322
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005323 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00005324 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005325 rhs->getType()->isOverloadableType())) {
5326 // Find all of the overloaded operators visible from this
5327 // point. We perform both an operator-name lookup from the local
5328 // scope and an argument-dependent lookup based on the types of
5329 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005330 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005331 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5332 if (OverOp != OO_None) {
5333 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5334 Functions);
5335 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00005336 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005337 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5338 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00005339 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005340
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005341 // Build the (potentially-overloaded, potentially-dependent)
5342 // binary operation.
5343 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00005344 }
5345
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005346 // Build a built-in binary operation.
5347 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005348}
5349
Douglas Gregor084d8552009-03-13 23:49:33 +00005350Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005351 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00005352 ExprArg InputArg) {
5353 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00005354
Mike Stump87c57ac2009-05-16 07:39:55 +00005355 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00005356 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00005357 QualType resultType;
5358 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005359 case UnaryOperator::OffsetOf:
5360 assert(false && "Invalid unary operator");
5361 break;
5362
Steve Naroff35d85152007-05-07 00:24:15 +00005363 case UnaryOperator::PreInc:
5364 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00005365 case UnaryOperator::PostInc:
5366 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00005367 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00005368 Opc == UnaryOperator::PreInc ||
5369 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00005370 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005371 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00005372 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005373 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005374 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00005375 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00005376 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005377 break;
5378 case UnaryOperator::Plus:
5379 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00005380 UsualUnaryConversions(Input);
5381 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005382 if (resultType->isDependentType())
5383 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005384 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5385 break;
5386 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5387 resultType->isEnumeralType())
5388 break;
5389 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5390 Opc == UnaryOperator::Plus &&
5391 resultType->isPointerType())
5392 break;
5393
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005394 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5395 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005396 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00005397 UsualUnaryConversions(Input);
5398 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005399 if (resultType->isDependentType())
5400 break;
Chris Lattner0d707612008-07-25 23:52:49 +00005401 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5402 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5403 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00005404 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005405 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00005406 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005407 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5408 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005409 break;
5410 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00005411 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00005412 DefaultFunctionArrayConversion(Input);
5413 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005414 if (resultType->isDependentType())
5415 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005416 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005417 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5418 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00005419 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005420 // In C++, it's bool. C++ 5.3.1p8
5421 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00005422 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00005423 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00005424 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00005425 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00005426 break;
Chris Lattner86554282007-06-08 22:32:33 +00005427 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00005428 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00005429 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005430 }
5431 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005432 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00005433
5434 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00005435 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00005436}
Chris Lattnereefa10e2007-05-28 06:56:27 +00005437
Douglas Gregor084d8552009-03-13 23:49:33 +00005438// Unary Operators. 'Tok' is the token for the operator.
5439Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5440 tok::TokenKind Op, ExprArg input) {
5441 Expr *Input = (Expr*)input.get();
5442 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5443
5444 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5445 // Find all of the overloaded operators visible from this
5446 // point. We perform both an operator-name lookup from the local
5447 // scope and an argument-dependent lookup based on the types of
5448 // the arguments.
5449 FunctionSet Functions;
5450 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5451 if (OverOp != OO_None) {
5452 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5453 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00005454 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00005455 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5456 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5457 }
5458
5459 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5460 }
5461
5462 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5463}
5464
Steve Naroff66356bd2007-09-16 14:56:35 +00005465/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005466Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5467 SourceLocation LabLoc,
5468 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00005469 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00005470 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00005471
Daniel Dunbar88402ce2008-08-04 16:51:22 +00005472 // If we haven't seen this label yet, create a forward reference. It
5473 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00005474 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00005475 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005476
Chris Lattnereefa10e2007-05-28 06:56:27 +00005477 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005478 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5479 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00005480}
5481
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005482Sema::OwningExprResult
5483Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5484 SourceLocation RPLoc) { // "({..})"
5485 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00005486 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5487 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5488
Eli Friedman52cc0162009-01-24 23:09:00 +00005489 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00005490 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005491 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00005492
Chris Lattner366727f2007-07-24 16:58:17 +00005493 // FIXME: there are a variety of strange constraints to enforce here, for
5494 // example, it is not possible to goto into a stmt expression apparently.
5495 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005496
Chris Lattner366727f2007-07-24 16:58:17 +00005497 // If there are sub stmts in the compound stmt, take the type of the last one
5498 // as the type of the stmtexpr.
5499 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005500
Chris Lattner944d3062008-07-26 19:51:01 +00005501 if (!Compound->body_empty()) {
5502 Stmt *LastStmt = Compound->body_back();
5503 // If LastStmt is a label, skip down through into the body.
5504 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5505 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005506
Chris Lattner944d3062008-07-26 19:51:01 +00005507 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00005508 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00005509 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005510
Eli Friedmanba961a92009-03-23 00:24:07 +00005511 // FIXME: Check that expression type is complete/non-abstract; statement
5512 // expressions are not lvalues.
5513
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005514 substmt.release();
5515 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00005516}
Steve Naroff78864672007-08-01 22:05:33 +00005517
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005518Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5519 SourceLocation BuiltinLoc,
5520 SourceLocation TypeLoc,
5521 TypeTy *argty,
5522 OffsetOfComponent *CompPtr,
5523 unsigned NumComponents,
5524 SourceLocation RPLoc) {
5525 // FIXME: This function leaks all expressions in the offset components on
5526 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005527 // FIXME: Preserve type source info.
5528 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00005529 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005530
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005531 bool Dependent = ArgTy->isDependentType();
5532
Chris Lattnerf17bd422007-08-30 17:45:32 +00005533 // We must have at least one component that refers to the type, and the first
5534 // one is known to be a field designator. Verify that the ArgTy represents
5535 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005536 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005537 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005538
Eli Friedmanba961a92009-03-23 00:24:07 +00005539 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5540 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00005541
Eli Friedman988a16b2009-02-27 06:44:11 +00005542 // Otherwise, create a null pointer as the base, and iteratively process
5543 // the offsetof designators.
5544 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5545 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005546 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00005547 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00005548
Chris Lattner78502cf2007-08-31 21:49:13 +00005549 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5550 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00005551 // FIXME: This diagnostic isn't actually visible because the location is in
5552 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00005553 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00005554 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5555 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005556
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005557 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00005558 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00005559
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005560 // FIXME: Dependent case loses a lot of information here. And probably
5561 // leaks like a sieve.
5562 for (unsigned i = 0; i != NumComponents; ++i) {
5563 const OffsetOfComponent &OC = CompPtr[i];
5564 if (OC.isBrackets) {
5565 // Offset of an array sub-field. TODO: Should we allow vector elements?
5566 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5567 if (!AT) {
5568 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005569 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5570 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005571 }
5572
5573 // FIXME: C++: Verify that operator[] isn't overloaded.
5574
Eli Friedman988a16b2009-02-27 06:44:11 +00005575 // Promote the array so it looks more like a normal array subscript
5576 // expression.
5577 DefaultFunctionArrayConversion(Res);
5578
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005579 // C99 6.5.2.1p1
5580 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005581 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005582 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005583 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00005584 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005585 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005586
5587 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5588 OC.LocEnd);
5589 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00005590 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005591
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005592 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005593 if (!RC) {
5594 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005595 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5596 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005597 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00005598
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005599 // Get the decl corresponding to this.
5600 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005601 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005602 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlsson8b98d022009-05-02 17:45:47 +00005603 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5604 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5605 << Res->getType());
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005606 DidWarnAboutNonPOD = true;
5607 }
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005608 }
Mike Stump11289f42009-09-09 15:08:12 +00005609
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005610 FieldDecl *MemberDecl
5611 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5612 LookupMemberName)
5613 .getAsDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005614 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005615 if (!MemberDecl)
Anders Carlsson896c2302009-08-30 00:54:35 +00005616 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005617 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00005618
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005619 // FIXME: C++: Verify that MemberDecl isn't a static field.
5620 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00005621 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00005622 Res = BuildAnonymousStructUnionMemberReference(
5623 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00005624 } else {
5625 // MemberDecl->getType() doesn't get the right qualifiers, but it
5626 // doesn't matter here.
5627 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5628 MemberDecl->getType().getNonReferenceType());
5629 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005630 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00005631 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005632
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005633 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5634 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00005635}
5636
5637
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005638Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5639 TypeTy *arg1,TypeTy *arg2,
5640 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005641 // FIXME: Preserve type source info.
5642 QualType argT1 = GetTypeFromParser(arg1);
5643 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005644
Steve Naroff78864672007-08-01 22:05:33 +00005645 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005646
Douglas Gregorf907cbf2009-05-19 22:28:02 +00005647 if (getLangOptions().CPlusPlus) {
5648 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5649 << SourceRange(BuiltinLoc, RPLoc);
5650 return ExprError();
5651 }
5652
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005653 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5654 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00005655}
5656
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005657Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5658 ExprArg cond,
5659 ExprArg expr1, ExprArg expr2,
5660 SourceLocation RPLoc) {
5661 Expr *CondExpr = static_cast<Expr*>(cond.get());
5662 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5663 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005664
Steve Naroff9efdabc2007-08-03 21:21:27 +00005665 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5666
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005667 QualType resType;
Douglas Gregor0df91122009-05-19 22:43:30 +00005668 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005669 resType = Context.DependentTy;
5670 } else {
5671 // The conditional expression is required to be a constant expression.
5672 llvm::APSInt condEval(32);
5673 SourceLocation ExpLoc;
5674 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005675 return ExprError(Diag(ExpLoc,
5676 diag::err_typecheck_choose_expr_requires_constant)
5677 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00005678
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005679 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5680 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5681 }
5682
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005683 cond.release(); expr1.release(); expr2.release();
5684 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5685 resType, RPLoc));
Steve Naroff9efdabc2007-08-03 21:21:27 +00005686}
5687
Steve Naroffc540d662008-09-03 18:15:37 +00005688//===----------------------------------------------------------------------===//
5689// Clang Extensions.
5690//===----------------------------------------------------------------------===//
5691
5692/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005693void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00005694 // Analyze block parameters.
5695 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005696
Steve Naroffc540d662008-09-03 18:15:37 +00005697 // Add BSI to CurBlock.
5698 BSI->PrevBlockInfo = CurBlock;
5699 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005700
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005701 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00005702 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00005703 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00005704 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00005705 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5706 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005707
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005708 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00005709 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005710}
5711
Mike Stump82f071f2009-02-04 22:31:32 +00005712void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00005713 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00005714
5715 if (ParamInfo.getNumTypeObjects() == 0
5716 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00005717 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00005718 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5719
Mike Stumpd456c482009-04-28 01:10:27 +00005720 if (T->isArrayType()) {
5721 Diag(ParamInfo.getSourceRange().getBegin(),
5722 diag::err_block_returns_array);
5723 return;
5724 }
5725
Mike Stump82f071f2009-02-04 22:31:32 +00005726 // The parameter list is optional, if there was none, assume ().
5727 if (!T->isFunctionType())
5728 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5729
5730 CurBlock->hasPrototype = true;
5731 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005732 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005733 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00005734 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00005735 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005736 // FIXME: remove the attribute.
5737 }
Chris Lattner6de05082009-04-11 19:27:54 +00005738 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00005739
Chris Lattner6de05082009-04-11 19:27:54 +00005740 // Do not allow returning a objc interface by-value.
5741 if (RetTy->isObjCInterfaceType()) {
5742 Diag(ParamInfo.getSourceRange().getBegin(),
5743 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5744 return;
5745 }
Mike Stump82f071f2009-02-04 22:31:32 +00005746 return;
5747 }
5748
Steve Naroffc540d662008-09-03 18:15:37 +00005749 // Analyze arguments to block.
5750 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5751 "Not a function declarator!");
5752 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005753
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005754 CurBlock->hasPrototype = FTI.hasPrototype;
5755 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005756
Steve Naroffc540d662008-09-03 18:15:37 +00005757 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5758 // no arguments, not a function that takes a single void argument.
5759 if (FTI.hasPrototype &&
5760 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00005761 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5762 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00005763 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005764 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00005765 } else if (FTI.hasPrototype) {
5766 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00005767 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005768 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00005769 }
Jay Foad7d0479f2009-05-21 09:52:38 +00005770 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00005771 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00005772 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00005773 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005774 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5775 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5776 // If this has an identifier, add it to the scope stack.
5777 if ((*AI)->getIdentifier())
5778 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00005779
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005780 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00005781 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005782 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00005783 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00005784 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005785 // FIXME: remove the attribute.
5786 }
Mike Stump11289f42009-09-09 15:08:12 +00005787
Chris Lattner6de05082009-04-11 19:27:54 +00005788 // Analyze the return type.
5789 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5790 QualType RetTy = T->getAsFunctionType()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00005791
Chris Lattner6de05082009-04-11 19:27:54 +00005792 // Do not allow returning a objc interface by-value.
5793 if (RetTy->isObjCInterfaceType()) {
5794 Diag(ParamInfo.getSourceRange().getBegin(),
5795 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5796 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005797 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00005798}
5799
5800/// ActOnBlockError - If there is an error parsing a block, this callback
5801/// is invoked to pop the information about the block from the action impl.
5802void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5803 // Ensure that CurBlock is deleted.
5804 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005805
Chris Lattner45542ea2009-04-19 05:28:12 +00005806 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5807
Steve Naroffc540d662008-09-03 18:15:37 +00005808 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00005809 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00005810 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00005811 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00005812}
5813
5814/// ActOnBlockStmtExpr - This is called when the body of a block statement
5815/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005816Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5817 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00005818 // If blocks are disabled, emit an error.
5819 if (!LangOpts.Blocks)
5820 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00005821
Steve Naroffc540d662008-09-03 18:15:37 +00005822 // Ensure that CurBlock is deleted.
5823 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00005824
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005825 PopDeclContext();
5826
Steve Naroffc540d662008-09-03 18:15:37 +00005827 // Pop off CurBlock, handle nested blocks.
5828 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005829
Steve Naroffc540d662008-09-03 18:15:37 +00005830 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005831 if (!BSI->ReturnType.isNull())
5832 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005833
Steve Naroffc540d662008-09-03 18:15:37 +00005834 llvm::SmallVector<QualType, 8> ArgTypes;
5835 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5836 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005837
Mike Stump3bf1ab42009-07-28 22:04:01 +00005838 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00005839 QualType BlockTy;
5840 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00005841 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5842 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00005843 else
Jay Foad7d0479f2009-05-21 09:52:38 +00005844 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00005845 BSI->isVariadic, 0, false, false, 0, 0,
5846 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005847
Eli Friedmanba961a92009-03-23 00:24:07 +00005848 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005849 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00005850 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005851
Chris Lattner45542ea2009-04-19 05:28:12 +00005852 // If needed, diagnose invalid gotos and switches in the block.
5853 if (CurFunctionNeedsScopeChecking)
5854 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5855 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00005856
Anders Carlssonb781bcd2009-05-01 19:49:17 +00005857 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00005858 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005859 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5860 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00005861}
5862
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005863Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5864 ExprArg expr, TypeTy *type,
5865 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005866 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00005867 Expr *E = static_cast<Expr*>(expr.get());
5868 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00005869
Anders Carlsson7e13ab82007-10-15 20:28:48 +00005870 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00005871
5872 // Get the va_list type
5873 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00005874 if (VaListType->isArrayType()) {
5875 // Deal with implicit array decay; for example, on x86-64,
5876 // va_list is an array, but it's supposed to decay to
5877 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00005878 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00005879 // Make sure the input expression also decays appropriately.
5880 UsualUnaryConversions(E);
5881 } else {
5882 // Otherwise, the va_list argument must be an l-value because
5883 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00005884 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00005885 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00005886 return ExprError();
5887 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00005888
Douglas Gregorad3150c2009-05-19 23:10:31 +00005889 if (!E->isTypeDependent() &&
5890 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005891 return ExprError(Diag(E->getLocStart(),
5892 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00005893 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00005894 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005895
Eli Friedmanba961a92009-03-23 00:24:07 +00005896 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00005897 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005898
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005899 expr.release();
5900 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5901 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00005902}
5903
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005904Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00005905 // The type of __null will be int or long, depending on the size of
5906 // pointers on the target.
5907 QualType Ty;
5908 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5909 Ty = Context.IntTy;
5910 else
5911 Ty = Context.LongTy;
5912
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005913 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00005914}
5915
Chris Lattner9bad62c2008-01-04 18:04:52 +00005916bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5917 SourceLocation Loc,
5918 QualType DstType, QualType SrcType,
5919 Expr *SrcExpr, const char *Flavor) {
5920 // Decode the result (notice that AST's are still created for extensions).
5921 bool isInvalid = false;
5922 unsigned DiagKind;
5923 switch (ConvTy) {
5924 default: assert(0 && "Unknown conversion type");
5925 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005926 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00005927 DiagKind = diag::ext_typecheck_convert_pointer_int;
5928 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005929 case IntToPointer:
5930 DiagKind = diag::ext_typecheck_convert_int_pointer;
5931 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005932 case IncompatiblePointer:
5933 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5934 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00005935 case IncompatiblePointerSign:
5936 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5937 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005938 case FunctionVoidPointer:
5939 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5940 break;
5941 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00005942 // If the qualifiers lost were because we were applying the
5943 // (deprecated) C++ conversion from a string literal to a char*
5944 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5945 // Ideally, this check would be performed in
5946 // CheckPointerTypesForAssignment. However, that would require a
5947 // bit of refactoring (so that the second argument is an
5948 // expression, rather than a type), which should be done as part
5949 // of a larger effort to fix CheckPointerTypesForAssignment for
5950 // C++ semantics.
5951 if (getLangOptions().CPlusPlus &&
5952 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5953 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005954 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5955 break;
Steve Naroff081c7422008-09-04 15:10:53 +00005956 case IntToBlockPointer:
5957 DiagKind = diag::err_int_to_block_pointer;
5958 break;
5959 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00005960 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00005961 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00005962 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00005963 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00005964 // it can give a more specific diagnostic.
5965 DiagKind = diag::warn_incompatible_qualified_id;
5966 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005967 case IncompatibleVectors:
5968 DiagKind = diag::warn_incompatible_vectors;
5969 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005970 case Incompatible:
5971 DiagKind = diag::err_typecheck_convert_incompatible;
5972 isInvalid = true;
5973 break;
5974 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005975
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005976 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5977 << SrcExpr->getSourceRange();
Chris Lattner9bad62c2008-01-04 18:04:52 +00005978 return isInvalid;
5979}
Anders Carlssone54e8a12008-11-30 19:50:32 +00005980
Chris Lattnerc71d08b2009-04-25 21:59:05 +00005981bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00005982 llvm::APSInt ICEResult;
5983 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5984 if (Result)
5985 *Result = ICEResult;
5986 return false;
5987 }
5988
Anders Carlssone54e8a12008-11-30 19:50:32 +00005989 Expr::EvalResult EvalResult;
5990
Mike Stump4e1f26a2009-02-19 03:04:26 +00005991 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00005992 EvalResult.HasSideEffects) {
5993 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5994
5995 if (EvalResult.Diag) {
5996 // We only show the note if it's not the usual "invalid subexpression"
5997 // or if it's actually in a subexpression.
5998 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5999 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6000 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6001 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006002
Anders Carlssone54e8a12008-11-30 19:50:32 +00006003 return true;
6004 }
6005
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006006 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6007 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00006008
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006009 if (EvalResult.Diag &&
6010 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6011 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006012
Anders Carlssone54e8a12008-11-30 19:50:32 +00006013 if (Result)
6014 *Result = EvalResult.Val.getInt();
6015 return false;
6016}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006017
Mike Stump11289f42009-09-09 15:08:12 +00006018Sema::ExpressionEvaluationContext
6019Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006020 // Introduce a new set of potentially referenced declarations to the stack.
6021 if (NewContext == PotentiallyPotentiallyEvaluated)
6022 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump11289f42009-09-09 15:08:12 +00006023
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006024 std::swap(ExprEvalContext, NewContext);
6025 return NewContext;
6026}
6027
Mike Stump11289f42009-09-09 15:08:12 +00006028void
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006029Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6030 ExpressionEvaluationContext NewContext) {
6031 ExprEvalContext = NewContext;
6032
6033 if (OldContext == PotentiallyPotentiallyEvaluated) {
6034 // Mark any remaining declarations in the current position of the stack
6035 // as "referenced". If they were not meant to be referenced, semantic
6036 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6037 PotentiallyReferencedDecls RemainingDecls;
6038 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6039 PotentiallyReferencedDeclStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00006040
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006041 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6042 IEnd = RemainingDecls.end();
6043 I != IEnd; ++I)
6044 MarkDeclarationReferenced(I->first, I->second);
6045 }
6046}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006047
6048/// \brief Note that the given declaration was referenced in the source code.
6049///
6050/// This routine should be invoke whenever a given declaration is referenced
6051/// in the source code, and where that reference occurred. If this declaration
6052/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6053/// C99 6.9p3), then the declaration will be marked as used.
6054///
6055/// \param Loc the location where the declaration was referenced.
6056///
6057/// \param D the declaration that has been referenced by the source code.
6058void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6059 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00006060
Douglas Gregor77b50e12009-06-22 23:06:13 +00006061 if (D->isUsed())
6062 return;
Mike Stump11289f42009-09-09 15:08:12 +00006063
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006064 // Mark a parameter declaration "used", regardless of whether we're in a
6065 // template or not.
6066 if (isa<ParmVarDecl>(D))
6067 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00006068
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006069 // Do not mark anything as "used" within a dependent context; wait for
6070 // an instantiation.
6071 if (CurContext->isDependentContext())
6072 return;
Mike Stump11289f42009-09-09 15:08:12 +00006073
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006074 switch (ExprEvalContext) {
6075 case Unevaluated:
6076 // We are in an expression that is not potentially evaluated; do nothing.
6077 return;
Mike Stump11289f42009-09-09 15:08:12 +00006078
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006079 case PotentiallyEvaluated:
6080 // We are in a potentially-evaluated expression, so this declaration is
6081 // "used"; handle this below.
6082 break;
Mike Stump11289f42009-09-09 15:08:12 +00006083
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006084 case PotentiallyPotentiallyEvaluated:
6085 // We are in an expression that may be potentially evaluated; queue this
6086 // declaration reference until we know whether the expression is
6087 // potentially evaluated.
6088 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6089 return;
6090 }
Mike Stump11289f42009-09-09 15:08:12 +00006091
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006092 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00006093 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006094 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006095 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6096 if (!Constructor->isUsed())
6097 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00006098 } else if (Constructor->isImplicit() &&
Mike Stump12b8ce12009-08-04 21:02:39 +00006099 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006100 if (!Constructor->isUsed())
6101 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6102 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006103 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6104 if (Destructor->isImplicit() && !Destructor->isUsed())
6105 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00006106
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006107 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6108 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6109 MethodDecl->getOverloadedOperator() == OO_Equal) {
6110 if (!MethodDecl->isUsed())
6111 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6112 }
6113 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00006114 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00006115 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00006116 // class templates.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00006117 if (!Function->getBody()) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00006118 // FIXME: distinguish between implicit instantiations of function
6119 // templates and explicit specializations (the latter don't get
6120 // instantiated, naturally).
6121 if (Function->getInstantiatedFromMemberFunction() ||
6122 Function->getPrimaryTemplate())
Douglas Gregordda7ced2009-06-30 17:20:14 +00006123 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor77b50e12009-06-22 23:06:13 +00006124 }
Mike Stump11289f42009-09-09 15:08:12 +00006125
6126
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006127 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006128 Function->setUsed(true);
6129 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00006130 }
Mike Stump11289f42009-09-09 15:08:12 +00006131
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006132 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006133 // Implicit instantiation of static data members of class templates.
6134 // FIXME: distinguish between implicit instantiations (which we need to
6135 // actually instantiate) and explicit specializations.
Douglas Gregor4aa04b12009-09-11 21:19:12 +00006136 // FIXME: extern templates
Mike Stump11289f42009-09-09 15:08:12 +00006137 if (Var->isStaticDataMember() &&
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006138 Var->getInstantiatedFromStaticDataMember())
6139 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
Mike Stump11289f42009-09-09 15:08:12 +00006140
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006141 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006142
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006143 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006144 return;
Sam Weinigbae69142009-09-11 03:29:30 +00006145 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006146}