blob: 53f3dde28319bf13cd1a4525f75c5e1bd5b906a5 [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();
Anders Carlsson21776b72009-08-08 16:55:18 +00001005 if (DiagnoseUseOfDecl(D, Loc))
1006 return ExprError();
Douglas Gregorc1905232009-08-26 22:36:53 +00001007 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1008 Loc, MemberType));
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001009 }
1010 }
1011 }
1012 }
1013
Douglas Gregor91f84212008-12-11 16:49:14 +00001014 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001015 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1016 if (MD->isStatic())
1017 // "invalid use of member 'x' in static member function"
Sebastian Redlffbcf962009-01-18 18:53:16 +00001018 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1019 << FD->getDeclName());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001020 }
1021
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001022 // Any other ways we could have found the field in a well-formed
1023 // program would have been turned into implicit member expressions
1024 // above.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001025 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1026 << FD->getDeclName());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001027 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001028
Steve Naroff46ba1eb2007-04-03 23:13:13 +00001029 if (isa<TypedefDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +00001030 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001031 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +00001032 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001033 if (isa<NamespaceDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +00001034 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Steve Narofff1e53692007-03-23 22:27:02 +00001035
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001036 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001037 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson946b86d2009-06-24 00:10:43 +00001038 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1039 false, false, SS);
Douglas Gregord32e0282009-02-09 23:23:08 +00001040 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson946b86d2009-06-24 00:10:43 +00001041 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1042 false, false, SS);
Anders Carlsson938b1002009-08-29 01:06:32 +00001043 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
Mike Stump11289f42009-09-09 15:08:12 +00001044 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1045 /*TypeDependent=*/true,
Anders Carlsson938b1002009-08-29 01:06:32 +00001046 /*ValueDependent=*/true, SS);
1047
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001048 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001049
Douglas Gregor171c45a2009-02-18 21:56:37 +00001050 // Check whether this declaration can be used. Note that we suppress
1051 // this check when we're going to perform argument-dependent lookup
1052 // on this function name, because this might not be the function
1053 // that overload resolution actually selects.
Mike Stump11289f42009-09-09 15:08:12 +00001054 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001055 HasTrailingLParen;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001056 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1057 return ExprError();
1058
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001059 // Only create DeclRefExpr's for valid Decl's.
1060 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001061 return ExprError();
1062
Chris Lattner2a9d9892008-10-20 05:16:36 +00001063 // If the identifier reference is inside a block, and it refers to a value
1064 // that is outside the block, create a BlockDeclRefExpr instead of a
1065 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1066 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001067 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001068 // We do not do this for things like enum constants, global variables, etc,
1069 // as they do not get snapshotted.
1070 //
1071 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001072 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001073 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001074 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001075 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001076 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001077 // This is to record that a 'const' was actually synthesize and added.
1078 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001079 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001080
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001081 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001082 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001083 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001084 }
1085 // If this reference is not in a block or if the referenced variable is
1086 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001087
Douglas Gregor4619e432008-12-05 23:32:09 +00001088 bool TypeDependent = false;
Douglas Gregor872ffce2008-12-10 20:57:37 +00001089 bool ValueDependent = false;
1090 if (getLangOptions().CPlusPlus) {
1091 // C++ [temp.dep.expr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001092 // An id-expression is type-dependent if it contains:
Douglas Gregor872ffce2008-12-10 20:57:37 +00001093 // - an identifier that was declared with a dependent type,
1094 if (VD->getType()->isDependentType())
1095 TypeDependent = true;
1096 // - FIXME: a template-id that is dependent,
1097 // - a conversion-function-id that specifies a dependent type,
1098 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1099 Name.getCXXNameType()->isDependentType())
1100 TypeDependent = true;
1101 // - a nested-name-specifier that contains a class-name that
1102 // names a dependent type.
1103 else if (SS && !SS->isEmpty()) {
Douglas Gregor52537682009-03-19 00:18:19 +00001104 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor872ffce2008-12-10 20:57:37 +00001105 DC; DC = DC->getParent()) {
1106 // FIXME: could stop early at namespace scope.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001107 if (DC->isRecord()) {
Douglas Gregor872ffce2008-12-10 20:57:37 +00001108 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1109 if (Context.getTypeDeclType(Record)->isDependentType()) {
1110 TypeDependent = true;
1111 break;
1112 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001113 }
1114 }
1115 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001116
Douglas Gregor872ffce2008-12-10 20:57:37 +00001117 // C++ [temp.dep.constexpr]p2:
1118 //
1119 // An identifier is value-dependent if it is:
1120 // - a name declared with a dependent type,
1121 if (TypeDependent)
1122 ValueDependent = true;
1123 // - the name of a non-type template parameter,
1124 else if (isa<NonTypeTemplateParmDecl>(VD))
1125 ValueDependent = true;
1126 // - a constant with integral or enumeration type and is
1127 // initialized with an expression that is value-dependent
Eli Friedmandd49ee32009-06-11 01:11:20 +00001128 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1129 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1130 Dcl->getInit()) {
1131 ValueDependent = Dcl->getInit()->isValueDependent();
1132 }
1133 }
Douglas Gregor872ffce2008-12-10 20:57:37 +00001134 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001135
Anders Carlsson946b86d2009-06-24 00:10:43 +00001136 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1137 TypeDependent, ValueDependent, SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001138}
Chris Lattnere168f762006-11-10 05:29:30 +00001139
Sebastian Redlffbcf962009-01-18 18:53:16 +00001140Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1141 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001142 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001143
Chris Lattnere168f762006-11-10 05:29:30 +00001144 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001145 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001146 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1147 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1148 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001149 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001150
Chris Lattnera81a0272008-01-12 08:14:25 +00001151 // Pre-defined identifiers are of type char[x], where x is the length of the
1152 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001153
Anders Carlsson2fb08242009-09-08 18:24:21 +00001154 Decl *currentDecl = getCurFunctionOrMethodDecl();
1155 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001156 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001157 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001158 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001159
Anders Carlsson2fb08242009-09-08 18:24:21 +00001160 unsigned Length =
1161 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001162
Chris Lattner0a8c2322008-01-12 19:32:28 +00001163 llvm::APInt LengthI(32, Length + 1);
Chris Lattner317e6ba2008-01-12 18:39:25 +00001164 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner0a8c2322008-01-12 19:32:28 +00001165 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Narofff6009ed2009-01-21 00:14:39 +00001166 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001167}
1168
Sebastian Redlffbcf962009-01-18 18:53:16 +00001169Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001170 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001171 CharBuffer.resize(Tok.getLength());
1172 const char *ThisTokBegin = &CharBuffer[0];
1173 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001174
Steve Naroffae4143e2007-04-26 20:39:23 +00001175 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1176 Tok.getLocation(), PP);
1177 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001178 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001179
1180 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1181
Sebastian Redl20614a72009-01-20 22:23:13 +00001182 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1183 Literal.isWide(),
1184 type, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001185}
1186
Sebastian Redlffbcf962009-01-18 18:53:16 +00001187Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1188 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001189 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1190 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001191 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001192 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001193 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001194 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001195 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001196
Chris Lattner23b7eb62007-06-15 23:05:46 +00001197 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001198 // Add padding so that NumericLiteralParser can overread by one character.
1199 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001200 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001201
Chris Lattner67ca9252007-05-21 01:08:44 +00001202 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001203 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001204
Mike Stump11289f42009-09-09 15:08:12 +00001205 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001206 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001207 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001208 return ExprError();
1209
Chris Lattner1c20a172007-08-26 03:42:43 +00001210 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001211
Chris Lattner1c20a172007-08-26 03:42:43 +00001212 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001213 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001214 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001215 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001216 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001217 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001218 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001219 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001220
1221 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1222
Ted Kremenek3a2c9502007-11-29 00:56:49 +00001223 // isExact will be set by GetFloatValue().
1224 bool isExact = false;
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001225 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1226 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001227
Chris Lattner1c20a172007-08-26 03:42:43 +00001228 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001229 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001230 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001231 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001232
Neil Boothac582c52007-08-29 22:00:19 +00001233 // long long is a C99 feature.
1234 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001235 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001236 Diag(Tok.getLocation(), diag::ext_longlong);
1237
Chris Lattner67ca9252007-05-21 01:08:44 +00001238 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001239 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001240
Chris Lattner67ca9252007-05-21 01:08:44 +00001241 if (Literal.GetIntegerValue(ResultVal)) {
1242 // If this value didn't fit into uintmax_t, warn and force to ull.
1243 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001244 Ty = Context.UnsignedLongLongTy;
1245 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001246 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001247 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001248 // If this value fits into a ULL, try to figure out what else it fits into
1249 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001250
Chris Lattner67ca9252007-05-21 01:08:44 +00001251 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1252 // be an unsigned int.
1253 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1254
1255 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001256 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001257 if (!Literal.isLong && !Literal.isLongLong) {
1258 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001259 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001260
Chris Lattner67ca9252007-05-21 01:08:44 +00001261 // Does it fit in a unsigned int?
1262 if (ResultVal.isIntN(IntSize)) {
1263 // Does it fit in a signed int?
1264 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001265 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001266 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001267 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001268 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001269 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001270 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001271
Chris Lattner67ca9252007-05-21 01:08:44 +00001272 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001273 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001274 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001275
Chris Lattner67ca9252007-05-21 01:08:44 +00001276 // Does it fit in a unsigned long?
1277 if (ResultVal.isIntN(LongSize)) {
1278 // Does it fit in a signed long?
1279 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001280 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001281 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001282 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001283 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001284 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001285 }
1286
Chris Lattner67ca9252007-05-21 01:08:44 +00001287 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001288 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001289 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001290
Chris Lattner67ca9252007-05-21 01:08:44 +00001291 // Does it fit in a unsigned long long?
1292 if (ResultVal.isIntN(LongLongSize)) {
1293 // Does it fit in a signed long long?
1294 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001295 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001296 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001297 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001298 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001299 }
1300 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001301
Chris Lattner67ca9252007-05-21 01:08:44 +00001302 // If we still couldn't decide a type, we probably have something that
1303 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001304 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001305 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001306 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001307 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001308 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001309
Chris Lattner55258cf2008-05-09 05:59:00 +00001310 if (ResultVal.getBitWidth() != Width)
1311 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001312 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001313 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001314 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001315
Chris Lattner1c20a172007-08-26 03:42:43 +00001316 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1317 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001318 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001319 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001320
1321 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001322}
1323
Sebastian Redlffbcf962009-01-18 18:53:16 +00001324Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1325 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001326 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001327 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001328 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001329}
1330
Steve Naroff71b59a92007-06-04 22:22:31 +00001331/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001332/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001333bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001334 SourceLocation OpLoc,
1335 const SourceRange &ExprRange,
1336 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001337 if (exprType->isDependentType())
1338 return false;
1339
Steve Naroff043d45d2007-05-15 02:32:35 +00001340 // C99 6.5.3.4p1:
Chris Lattnerb1355b12009-01-24 19:46:37 +00001341 if (isa<FunctionType>(exprType)) {
Chris Lattner62975a72009-04-24 00:30:45 +00001342 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001343 if (isSizeof)
1344 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1345 return false;
1346 }
Mike Stump11289f42009-09-09 15:08:12 +00001347
Chris Lattner62975a72009-04-24 00:30:45 +00001348 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001349 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001350 Diag(OpLoc, diag::ext_sizeof_void_type)
1351 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001352 return false;
1353 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Chris Lattner62975a72009-04-24 00:30:45 +00001355 if (RequireCompleteType(OpLoc, exprType,
Mike Stump11289f42009-09-09 15:08:12 +00001356 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssond624e162009-08-26 23:45:07 +00001357 PDiag(diag::err_alignof_incomplete_type)
1358 << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001359 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattner62975a72009-04-24 00:30:45 +00001361 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001362 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001363 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001364 << exprType << isSizeof << ExprRange;
1365 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001366 }
Mike Stump11289f42009-09-09 15:08:12 +00001367
Chris Lattner62975a72009-04-24 00:30:45 +00001368 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001369}
1370
Chris Lattner8dff0172009-01-24 20:17:12 +00001371bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1372 const SourceRange &ExprRange) {
1373 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001374
Mike Stump11289f42009-09-09 15:08:12 +00001375 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001376 if (isa<DeclRefExpr>(E))
1377 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001378
1379 // Cannot know anything else if the expression is dependent.
1380 if (E->isTypeDependent())
1381 return false;
1382
Douglas Gregor71235ec2009-05-02 02:18:30 +00001383 if (E->getBitField()) {
1384 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1385 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001386 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001387
1388 // Alignment of a field access is always okay, so long as it isn't a
1389 // bit-field.
1390 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001391 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001392 return false;
1393
Chris Lattner8dff0172009-01-24 20:17:12 +00001394 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1395}
1396
Douglas Gregor0950e412009-03-13 21:01:28 +00001397/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001398Action::OwningExprResult
1399Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001400 bool isSizeOf, SourceRange R) {
1401 if (T.isNull())
1402 return ExprError();
1403
1404 if (!T->isDependentType() &&
1405 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1406 return ExprError();
1407
1408 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1409 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1410 Context.getSizeType(), OpLoc,
1411 R.getEnd()));
1412}
1413
1414/// \brief Build a sizeof or alignof expression given an expression
1415/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001416Action::OwningExprResult
1417Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001418 bool isSizeOf, SourceRange R) {
1419 // Verify that the operand is valid.
1420 bool isInvalid = false;
1421 if (E->isTypeDependent()) {
1422 // Delay type-checking for type-dependent expressions.
1423 } else if (!isSizeOf) {
1424 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001425 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001426 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1427 isInvalid = true;
1428 } else {
1429 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1430 }
1431
1432 if (isInvalid)
1433 return ExprError();
1434
1435 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1436 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1437 Context.getSizeType(), OpLoc,
1438 R.getEnd()));
1439}
1440
Sebastian Redl6f282892008-11-11 17:56:53 +00001441/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1442/// the same for @c alignof and @c __alignof
1443/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001444Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001445Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1446 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001447 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001448 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001449
Sebastian Redl6f282892008-11-11 17:56:53 +00001450 if (isType) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001451 // FIXME: Preserve type source info.
1452 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor0950e412009-03-13 21:01:28 +00001453 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001454 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001455
Douglas Gregor0950e412009-03-13 21:01:28 +00001456 // Get the end location.
1457 Expr *ArgEx = (Expr *)TyOrEx;
1458 Action::OwningExprResult Result
1459 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1460
1461 if (Result.isInvalid())
1462 DeleteExpr(ArgEx);
1463
1464 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001465}
1466
Chris Lattner709322b2009-02-17 08:12:06 +00001467QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001468 if (V->isTypeDependent())
1469 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001470
Chris Lattnere267f5d2007-08-26 05:39:26 +00001471 // These operators return the element type of a complex type.
Chris Lattner30b5dd02007-08-24 21:16:53 +00001472 if (const ComplexType *CT = V->getType()->getAsComplexType())
1473 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001474
Chris Lattnere267f5d2007-08-26 05:39:26 +00001475 // Otherwise they pass through real integer and floating point types here.
1476 if (V->getType()->isArithmeticType())
1477 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001478
Chris Lattnere267f5d2007-08-26 05:39:26 +00001479 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001480 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1481 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001482 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001483}
1484
1485
Chris Lattnere168f762006-11-10 05:29:30 +00001486
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001487Action::OwningExprResult
1488Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1489 tok::TokenKind Kind, ExprArg Input) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001490 // Since this might be a postfix expression, get rid of ParenListExprs.
1491 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001492 Expr *Arg = (Expr *)Input.get();
Douglas Gregord08452f2008-11-19 15:42:04 +00001493
Chris Lattnere168f762006-11-10 05:29:30 +00001494 UnaryOperator::Opcode Opc;
1495 switch (Kind) {
1496 default: assert(0 && "Unknown unary op!");
1497 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1498 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1499 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001500
Douglas Gregord08452f2008-11-19 15:42:04 +00001501 if (getLangOptions().CPlusPlus &&
1502 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1503 // Which overloaded operator?
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001504 OverloadedOperatorKind OverOp =
Douglas Gregord08452f2008-11-19 15:42:04 +00001505 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1506
1507 // C++ [over.inc]p1:
1508 //
1509 // [...] If the function is a member function with one
1510 // parameter (which shall be of type int) or a non-member
1511 // function with two parameters (the second of which shall be
1512 // of type int), it defines the postfix increment operator ++
1513 // for objects of that type. When the postfix increment is
1514 // called as a result of using the ++ operator, the int
1515 // argument will have value zero.
Mike Stump11289f42009-09-09 15:08:12 +00001516 Expr *Args[2] = {
1517 Arg,
1518 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
Steve Narofff6009ed2009-01-21 00:14:39 +00001519 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregord08452f2008-11-19 15:42:04 +00001520 };
1521
1522 // Build the candidate set for overloading
1523 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001524 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregord08452f2008-11-19 15:42:04 +00001525
1526 // Perform overload resolution.
1527 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001528 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregord08452f2008-11-19 15:42:04 +00001529 case OR_Success: {
1530 // We found a built-in operator or an overloaded operator.
1531 FunctionDecl *FnDecl = Best->Function;
1532
1533 if (FnDecl) {
1534 // We matched an overloaded operator. Build a call to that
1535 // operator.
1536
1537 // Convert the arguments.
1538 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1539 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001540 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001541 } else {
1542 // Convert the arguments.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001543 if (PerformCopyInitialization(Arg,
Douglas Gregord08452f2008-11-19 15:42:04 +00001544 FnDecl->getParamDecl(0)->getType(),
1545 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001546 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001547 }
1548
1549 // Determine the result type
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001550 QualType ResultTy
Douglas Gregord08452f2008-11-19 15:42:04 +00001551 = FnDecl->getType()->getAsFunctionType()->getResultType();
1552 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001553
Douglas Gregord08452f2008-11-19 15:42:04 +00001554 // Build the actual expression node.
Steve Narofff6009ed2009-01-21 00:14:39 +00001555 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump82191d02009-02-19 02:54:59 +00001556 SourceLocation());
Douglas Gregord08452f2008-11-19 15:42:04 +00001557 UsualUnaryConversions(FnExpr);
1558
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001559 Input.release();
Douglas Gregor2517f332009-05-27 05:00:47 +00001560 Args[0] = Arg;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001561 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
Mike Stump11289f42009-09-09 15:08:12 +00001562 Args, 2, ResultTy,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001563 OpLoc));
Douglas Gregord08452f2008-11-19 15:42:04 +00001564 } else {
1565 // We matched a built-in operator. Convert the arguments, then
1566 // break out so that we will build the appropriate built-in
1567 // operator node.
1568 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1569 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001570 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001571
1572 break;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001573 }
Douglas Gregord08452f2008-11-19 15:42:04 +00001574 }
1575
1576 case OR_No_Viable_Function:
1577 // No viable function; fall through to handling this as a
1578 // built-in operator, which will produce an error message for us.
1579 break;
1580
1581 case OR_Ambiguous:
1582 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1583 << UnaryOperator::getOpcodeStr(Opc)
1584 << Arg->getSourceRange();
1585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001586 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00001587
1588 case OR_Deleted:
1589 Diag(OpLoc, diag::err_ovl_deleted_oper)
1590 << Best->Function->isDeleted()
1591 << UnaryOperator::getOpcodeStr(Opc)
1592 << Arg->getSourceRange();
1593 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1594 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001595 }
1596
1597 // Either we found no viable overloaded operator or we matched a
1598 // built-in operator. In either case, fall through to trying to
1599 // build a built-in operation.
1600 }
1601
Eli Friedmanf32f0a72009-07-22 23:24:42 +00001602 Input.release();
1603 Input = Arg;
Eli Friedman6aea5752009-07-22 22:25:00 +00001604 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001605}
1606
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001607Action::OwningExprResult
1608Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1609 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001610 // Since this might be a postfix expression, get rid of ParenListExprs.
1611 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1612
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001613 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1614 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001615
Douglas Gregor40412ac2008-11-19 17:17:41 +00001616 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001617 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1618 Base.release();
1619 Idx.release();
1620 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1621 Context.DependentTy, RLoc));
1622 }
1623
Mike Stump11289f42009-09-09 15:08:12 +00001624 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001625 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001626 LHSExp->getType()->isEnumeralType() ||
1627 RHSExp->getType()->isRecordType() ||
1628 RHSExp->getType()->isEnumeralType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001629 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor40412ac2008-11-19 17:17:41 +00001630 // to the candidate set.
1631 OverloadCandidateSet CandidateSet;
1632 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001633 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1634 SourceRange(LLoc, RLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001635
Douglas Gregor40412ac2008-11-19 17:17:41 +00001636 // Perform overload resolution.
1637 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001638 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor40412ac2008-11-19 17:17:41 +00001639 case OR_Success: {
1640 // We found a built-in operator or an overloaded operator.
1641 FunctionDecl *FnDecl = Best->Function;
1642
1643 if (FnDecl) {
1644 // We matched an overloaded operator. Build a call to that
1645 // operator.
1646
1647 // Convert the arguments.
1648 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1649 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
Mike Stump11289f42009-09-09 15:08:12 +00001650 PerformCopyInitialization(RHSExp,
Douglas Gregor40412ac2008-11-19 17:17:41 +00001651 FnDecl->getParamDecl(0)->getType(),
1652 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001653 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001654 } else {
1655 // Convert the arguments.
1656 if (PerformCopyInitialization(LHSExp,
1657 FnDecl->getParamDecl(0)->getType(),
1658 "passing") ||
1659 PerformCopyInitialization(RHSExp,
1660 FnDecl->getParamDecl(1)->getType(),
1661 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001662 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001663 }
1664
1665 // Determine the result type
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001666 QualType ResultTy
Douglas Gregor40412ac2008-11-19 17:17:41 +00001667 = FnDecl->getType()->getAsFunctionType()->getResultType();
1668 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001669
Douglas Gregor40412ac2008-11-19 17:17:41 +00001670 // Build the actual expression node.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001671 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1672 SourceLocation());
Douglas Gregor40412ac2008-11-19 17:17:41 +00001673 UsualUnaryConversions(FnExpr);
1674
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001675 Base.release();
1676 Idx.release();
Douglas Gregor2517f332009-05-27 05:00:47 +00001677 Args[0] = LHSExp;
1678 Args[1] = RHSExp;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001679 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Mike Stump11289f42009-09-09 15:08:12 +00001680 FnExpr, Args, 2,
Steve Narofff6009ed2009-01-21 00:14:39 +00001681 ResultTy, LLoc));
Douglas Gregor40412ac2008-11-19 17:17:41 +00001682 } else {
1683 // We matched a built-in operator. Convert the arguments, then
1684 // break out so that we will build the appropriate built-in
1685 // operator node.
1686 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1687 "passing") ||
1688 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1689 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001690 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001691
1692 break;
1693 }
1694 }
1695
1696 case OR_No_Viable_Function:
1697 // No viable function; fall through to handling this as a
1698 // built-in operator, which will produce an error message for us.
1699 break;
1700
1701 case OR_Ambiguous:
1702 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1703 << "[]"
1704 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1705 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001706 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00001707
1708 case OR_Deleted:
1709 Diag(LLoc, diag::err_ovl_deleted_oper)
1710 << Best->Function->isDeleted()
1711 << "[]"
1712 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1713 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1714 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001715 }
1716
1717 // Either we found no viable overloaded operator or we matched a
1718 // built-in operator. In either case, fall through to trying to
1719 // build a built-in operation.
1720 }
1721
Chris Lattner36d572b2007-07-16 00:14:47 +00001722 // Perform default conversions.
1723 DefaultFunctionArrayConversion(LHSExp);
1724 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001725
Chris Lattner36d572b2007-07-16 00:14:47 +00001726 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00001727
Steve Naroffc1aadb12007-03-28 21:49:40 +00001728 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00001729 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00001730 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00001731 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00001732 Expr *BaseExpr, *IndexExpr;
1733 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001734 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1735 BaseExpr = LHSExp;
1736 IndexExpr = RHSExp;
1737 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001738 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00001739 BaseExpr = LHSExp;
1740 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001741 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001742 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00001743 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00001744 BaseExpr = RHSExp;
1745 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001746 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001747 } else if (const ObjCObjectPointerType *PTy =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001748 LHSTy->getAsObjCObjectPointerType()) {
1749 BaseExpr = LHSExp;
1750 IndexExpr = RHSExp;
1751 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001752 } else if (const ObjCObjectPointerType *PTy =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001753 RHSTy->getAsObjCObjectPointerType()) {
1754 // Handle the uncommon case of "123[Ptr]".
1755 BaseExpr = RHSExp;
1756 IndexExpr = LHSExp;
1757 ResultType = PTy->getPointeeType();
Chris Lattner41977962007-07-31 19:29:30 +00001758 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1759 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00001760 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00001761
Chris Lattner36d572b2007-07-16 00:14:47 +00001762 // FIXME: need to deal with const...
1763 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001764 } else if (LHSTy->isArrayType()) {
1765 // If we see an array that wasn't promoted by
1766 // DefaultFunctionArrayConversion, it must be an array that
1767 // wasn't promoted because of the C90 rule that doesn't
1768 // allow promoting non-lvalue arrays. Warn, then
1769 // force the promotion here.
1770 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1771 LHSExp->getSourceRange();
1772 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1773 LHSTy = LHSExp->getType();
1774
1775 BaseExpr = LHSExp;
1776 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001777 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001778 } else if (RHSTy->isArrayType()) {
1779 // Same as previous, except for 123[f().a] case
1780 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1781 RHSExp->getSourceRange();
1782 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1783 RHSTy = RHSExp->getType();
1784
1785 BaseExpr = RHSExp;
1786 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001787 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00001788 } else {
Chris Lattner003af242009-04-25 22:50:55 +00001789 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1790 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001791 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00001792 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00001793 if (!(IndexExpr->getType()->isIntegerType() &&
1794 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00001795 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1796 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00001797
Douglas Gregorac1fb652009-03-24 19:52:54 +00001798 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00001799 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1800 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00001801 // incomplete types are not object types.
1802 if (ResultType->isFunctionType()) {
1803 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1804 << ResultType << BaseExpr->getSourceRange();
1805 return ExprError();
1806 }
Mike Stump11289f42009-09-09 15:08:12 +00001807
Douglas Gregorac1fb652009-03-24 19:52:54 +00001808 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001809 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00001810 PDiag(diag::err_subscript_incomplete_type)
1811 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00001812 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001813
Chris Lattner62975a72009-04-24 00:30:45 +00001814 // Diagnose bad cases where we step over interface counts.
1815 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1816 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1817 << ResultType << BaseExpr->getSourceRange();
1818 return ExprError();
1819 }
Mike Stump11289f42009-09-09 15:08:12 +00001820
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001821 Base.release();
1822 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001823 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00001824 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00001825}
1826
Steve Narofff8fd09e2007-07-27 22:15:19 +00001827QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00001828CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001829 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00001830 SourceLocation CompLoc) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001831 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanf322eab2008-05-09 06:41:27 +00001832
Steve Narofff8fd09e2007-07-27 22:15:19 +00001833 // The vector accessor can't exceed the number of elements.
Anders Carlssonf571c112009-08-26 18:25:21 +00001834 const char *compStr = CompName->getName();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001835
Mike Stump4e1f26a2009-02-19 03:04:26 +00001836 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00001837 // special names that indicate a subset of exactly half the elements are
1838 // to be selected.
1839 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00001840
Nate Begemanbb70bf62009-01-18 01:47:54 +00001841 // This flag determines whether or not CompName has an 's' char prefix,
1842 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00001843 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00001844
1845 // Check that we've found one of the special components, or that the component
1846 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001847 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00001848 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1849 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00001850 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001851 do
1852 compStr++;
1853 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00001854 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001855 do
1856 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00001857 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00001858 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00001859
Mike Stump4e1f26a2009-02-19 03:04:26 +00001860 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00001861 // We didn't get to the end of the string. This means the component names
1862 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00001863 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1864 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00001865 return QualType();
1866 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00001867
Nate Begemanbb70bf62009-01-18 01:47:54 +00001868 // Ensure no component accessor exceeds the width of the vector type it
1869 // operates on.
1870 if (!HalvingSwizzle) {
Anders Carlssonf571c112009-08-26 18:25:21 +00001871 compStr = CompName->getName();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001872
1873 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00001874 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00001875
1876 while (*compStr) {
1877 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1878 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1879 << baseType << SourceRange(CompLoc);
1880 return QualType();
1881 }
1882 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00001883 }
Nate Begemanf322eab2008-05-09 06:41:27 +00001884
Nate Begemanbb70bf62009-01-18 01:47:54 +00001885 // If this is a halving swizzle, verify that the base type has an even
1886 // number of elements.
1887 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner3b054132008-11-19 05:08:23 +00001888 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001889 << baseType << SourceRange(CompLoc);
Nate Begemanf322eab2008-05-09 06:41:27 +00001890 return QualType();
1891 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00001892
Steve Narofff8fd09e2007-07-27 22:15:19 +00001893 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001894 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00001895 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00001896 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00001897 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanbb70bf62009-01-18 01:47:54 +00001898 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00001899 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001900 if (HexSwizzle)
1901 CompSize--;
1902
Steve Narofff8fd09e2007-07-27 22:15:19 +00001903 if (CompSize == 1)
1904 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001905
Nate Begemance4d7fc2008-04-18 23:10:10 +00001906 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00001907 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00001908 // diagostics look bad. We want extended vector types to appear built-in.
1909 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1910 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1911 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001912 }
1913 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00001914}
1915
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001916static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00001917 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001918 const Selector &Sel,
1919 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00001920
Anders Carlssonf571c112009-08-26 18:25:21 +00001921 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001922 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001923 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001924 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00001925
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001926 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1927 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001928 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001929 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001930 return D;
1931 }
1932 return 0;
1933}
1934
Steve Narofffb4330f2009-06-17 22:40:22 +00001935static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00001936 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001937 const Selector &Sel,
1938 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001939 // Check protocols on qualified interfaces.
1940 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00001941 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001942 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00001943 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001944 GDecl = PD;
1945 break;
1946 }
1947 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001948 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001949 GDecl = OMD;
1950 break;
1951 }
1952 }
1953 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00001954 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001955 E = QIdTy->qual_end(); I != E; ++I) {
1956 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001957 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001958 if (GDecl)
1959 return GDecl;
1960 }
1961 }
1962 return GDecl;
1963}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00001964
Fariborz Jahanian69ba9352009-04-07 18:28:06 +00001965/// FindMethodInNestedImplementations - Look up a method in current and
1966/// all base class implementations.
1967///
1968ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1969 const ObjCInterfaceDecl *IFace,
1970 const Selector &Sel) {
1971 ObjCMethodDecl *Method = 0;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001972 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001973 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump11289f42009-09-09 15:08:12 +00001974
Fariborz Jahanian69ba9352009-04-07 18:28:06 +00001975 if (!Method && IFace->getSuperClass())
1976 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1977 return Method;
1978}
Mike Stump11289f42009-09-09 15:08:12 +00001979
1980Action::OwningExprResult
Anders Carlssonf571c112009-08-26 18:25:21 +00001981Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001982 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001983 DeclarationName MemberName,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001984 bool HasExplicitTemplateArgs,
1985 SourceLocation LAngleLoc,
1986 const TemplateArgument *ExplicitTemplateArgs,
1987 unsigned NumExplicitTemplateArgs,
1988 SourceLocation RAngleLoc,
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001989 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1990 NamedDecl *FirstQualifierInScope) {
Douglas Gregord8061562009-08-06 03:17:00 +00001991 if (SS && SS->isInvalid())
1992 return ExprError();
1993
Nate Begeman5ec4b312009-08-10 23:49:36 +00001994 // Since this might be a postfix expression, get rid of ParenListExprs.
1995 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1996
Anders Carlsson3cbc8592009-05-01 19:30:39 +00001997 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregorad8a3362009-09-04 17:36:40 +00001998 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00001999
Steve Naroffeaaae462007-12-16 21:42:28 +00002000 // Perform default conversions.
2001 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002002
Steve Naroff185616f2007-07-26 03:11:44 +00002003 QualType BaseType = BaseExpr->getType();
David Chisnall9f57c292009-08-17 16:35:33 +00002004 // If this is an Objective-C pseudo-builtin and a definition is provided then
2005 // use that.
2006 if (BaseType->isObjCIdType()) {
2007 // We have an 'id' type. Rather than fall through, we check if this
2008 // is a reference to 'isa'.
2009 if (BaseType != Context.ObjCIdRedefinitionType) {
2010 BaseType = Context.ObjCIdRedefinitionType;
2011 ImpCastExprToType(BaseExpr, BaseType);
2012 }
2013 } else if (BaseType->isObjCClassType() &&
Douglas Gregorfbc18232009-08-31 21:16:32 +00002014 BaseType != Context.ObjCClassRedefinitionType) {
David Chisnall9f57c292009-08-17 16:35:33 +00002015 BaseType = Context.ObjCClassRedefinitionType;
2016 ImpCastExprToType(BaseExpr, BaseType);
2017 }
Steve Naroff185616f2007-07-26 03:11:44 +00002018 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002019
Chris Lattner4befd732008-07-21 04:36:39 +00002020 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2021 // must have pointer type, and the accessed type is the pointee.
Steve Narofff1e53692007-03-23 22:27:02 +00002022 if (OpKind == tok::arrow) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002023 if (BaseType->isDependentType()) {
2024 NestedNameSpecifier *Qualifier = 0;
2025 if (SS) {
2026 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2027 if (!FirstQualifierInScope)
2028 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2029 }
Mike Stump11289f42009-09-09 15:08:12 +00002030
2031 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor308047d2009-09-09 00:23:06 +00002032 OpLoc, Qualifier,
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002033 SS? SS->getRange() : SourceRange(),
Douglas Gregor308047d2009-09-09 00:23:06 +00002034 FirstQualifierInScope,
2035 MemberName,
2036 MemberLoc,
2037 HasExplicitTemplateArgs,
2038 LAngleLoc,
2039 ExplicitTemplateArgs,
2040 NumExplicitTemplateArgs,
2041 RAngleLoc));
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002042 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002043 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002044 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002045 else if (BaseType->isObjCObjectPointerType())
2046 ;
Steve Naroff185616f2007-07-26 03:11:44 +00002047 else
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002048 return ExprError(Diag(MemberLoc,
2049 diag::err_typecheck_member_reference_arrow)
2050 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002051 } else {
Anders Carlsson524d5a42009-05-16 20:31:20 +00002052 if (BaseType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002053 // Require that the base type isn't a pointer type
Anders Carlsson524d5a42009-05-16 20:31:20 +00002054 // (so we'll report an error for)
2055 // T* t;
2056 // t.f;
Mike Stump11289f42009-09-09 15:08:12 +00002057 //
Anders Carlsson524d5a42009-05-16 20:31:20 +00002058 // In Obj-C++, however, the above expression is valid, since it could be
2059 // accessing the 'f' property if T is an Obj-C interface. The extra check
2060 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002061 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002062
Mike Stump11289f42009-09-09 15:08:12 +00002063 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002064 !PT->getPointeeType()->isRecordType())) {
2065 NestedNameSpecifier *Qualifier = 0;
2066 if (SS) {
2067 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2068 if (!FirstQualifierInScope)
2069 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2070 }
Mike Stump11289f42009-09-09 15:08:12 +00002071
Douglas Gregor308047d2009-09-09 00:23:06 +00002072 return Owned(CXXUnresolvedMemberExpr::Create(Context,
Mike Stump11289f42009-09-09 15:08:12 +00002073 BaseExpr, false,
2074 OpLoc,
Douglas Gregor308047d2009-09-09 00:23:06 +00002075 Qualifier,
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002076 SS? SS->getRange() : SourceRange(),
Douglas Gregor308047d2009-09-09 00:23:06 +00002077 FirstQualifierInScope,
2078 MemberName,
2079 MemberLoc,
2080 HasExplicitTemplateArgs,
2081 LAngleLoc,
2082 ExplicitTemplateArgs,
2083 NumExplicitTemplateArgs,
2084 RAngleLoc));
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002085 }
Anders Carlsson524d5a42009-05-16 20:31:20 +00002086 }
Steve Narofff1e53692007-03-23 22:27:02 +00002087 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002088
Chris Lattner4befd732008-07-21 04:36:39 +00002089 // Handle field access to simple records. This also handles access to fields
2090 // of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002091 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff185616f2007-07-26 03:11:44 +00002092 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregored0cfbd2009-03-09 16:13:40 +00002093 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00002094 PDiag(diag::err_typecheck_incomplete_tag)
2095 << BaseExpr->getSourceRange()))
Douglas Gregordd430f72009-01-19 19:26:10 +00002096 return ExprError();
2097
Douglas Gregord8061562009-08-06 03:17:00 +00002098 DeclContext *DC = RDecl;
2099 if (SS && SS->isSet()) {
2100 // If the member name was a qualified-id, look into the
2101 // nested-name-specifier.
2102 DC = computeDeclContext(*SS, false);
Mike Stump11289f42009-09-09 15:08:12 +00002103
2104 // FIXME: If DC is not computable, we should build a
Douglas Gregord8061562009-08-06 03:17:00 +00002105 // CXXUnresolvedMemberExpr.
2106 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2107 }
2108
Steve Naroff185616f2007-07-26 03:11:44 +00002109 // The record definition is complete, now make sure the member is valid.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002110 LookupResult Result
Anders Carlssonf571c112009-08-26 18:25:21 +00002111 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002112
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002113 if (!Result)
Anders Carlsson896c2302009-08-30 00:54:35 +00002114 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlssonf571c112009-08-26 18:25:21 +00002115 << MemberName << BaseExpr->getSourceRange());
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002116 if (Result.isAmbiguous()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002117 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2118 BaseExpr->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002119 return ExprError();
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002120 }
Mike Stump11289f42009-09-09 15:08:12 +00002121
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002122 if (SS && SS->isSet()) {
Mike Stump11289f42009-09-09 15:08:12 +00002123 QualType BaseTypeCanon
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002124 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002125 QualType MemberTypeCanon
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002126 = Context.getCanonicalType(
2127 Context.getTypeDeclType(
2128 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
Mike Stump11289f42009-09-09 15:08:12 +00002129
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002130 if (BaseTypeCanon != MemberTypeCanon &&
2131 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2132 return ExprError(Diag(SS->getBeginLoc(),
2133 diag::err_not_direct_base_or_virtual)
2134 << MemberTypeCanon << BaseTypeCanon);
2135 }
Mike Stump11289f42009-09-09 15:08:12 +00002136
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002137 NamedDecl *MemberDecl = Result;
Douglas Gregor91f84212008-12-11 16:49:14 +00002138
Chris Lattner303284a2009-02-13 22:08:30 +00002139 // If the decl being referenced had an error, return an error for this
2140 // sub-expr without emitting another error, in order to avoid cascading
2141 // error cases.
2142 if (MemberDecl->isInvalidDecl())
2143 return ExprError();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002144
Anders Carlsson04e1e222009-09-10 20:48:14 +00002145 bool ShouldCheckUse = true;
2146 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2147 // Don't diagnose the use of a virtual member function unless it's
2148 // explicitly qualified.
2149 if (MD->isVirtual() && (!SS || !SS->isSet()))
2150 ShouldCheckUse = false;
2151 }
2152
Douglas Gregor171c45a2009-02-18 21:56:37 +00002153 // Check the use of this field
Anders Carlsson04e1e222009-09-10 20:48:14 +00002154 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002155 return ExprError();
Chris Lattner303284a2009-02-13 22:08:30 +00002156
Douglas Gregor55297ac2008-12-23 00:26:44 +00002157 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002158 // We may have found a field within an anonymous union or struct
2159 // (C++ [class.union]).
2160 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002161 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002162 BaseExpr, OpLoc);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002163
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002164 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor55297ac2008-12-23 00:26:44 +00002165 QualType MemberType = FD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002166 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002167 MemberType = Ref->getPointeeType();
2168 else {
Mon P Wangacedf772009-07-22 03:08:17 +00002169 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002170 unsigned combinedQualifiers =
2171 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor55297ac2008-12-23 00:26:44 +00002172 if (FD->isMutable())
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002173 combinedQualifiers &= ~QualType::Const;
2174 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wangacedf772009-07-22 03:08:17 +00002175 if (BaseAddrSpace != MemberType.getAddressSpace())
2176 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002177 }
Eli Friedman1242fff2008-02-06 22:48:16 +00002178
Douglas Gregor77b50e12009-06-22 23:06:13 +00002179 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002180 if (PerformObjectMemberConversion(BaseExpr, FD))
2181 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002182 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorc1905232009-08-26 22:36:53 +00002183 FD, MemberLoc, MemberType));
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002184 }
Mike Stump11289f42009-09-09 15:08:12 +00002185
Douglas Gregor77b50e12009-06-22 23:06:13 +00002186 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2187 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002188 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2189 Var, MemberLoc,
2190 Var->getType().getNonReferenceType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002191 }
2192 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2193 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002194 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2195 MemberFn, MemberLoc,
2196 MemberFn->getType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002197 }
Mike Stump11289f42009-09-09 15:08:12 +00002198 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor97628d62009-08-21 00:16:32 +00002199 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2200 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002201
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002202 if (HasExplicitTemplateArgs)
Mike Stump11289f42009-09-09 15:08:12 +00002203 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2204 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002205 SS? SS->getRange() : SourceRange(),
Mike Stump11289f42009-09-09 15:08:12 +00002206 FunTmpl, MemberLoc, true,
2207 LAngleLoc, ExplicitTemplateArgs,
2208 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002209 Context.OverloadTy));
Mike Stump11289f42009-09-09 15:08:12 +00002210
Douglas Gregorc1905232009-08-26 22:36:53 +00002211 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2212 FunTmpl, MemberLoc,
2213 Context.OverloadTy));
Douglas Gregor97628d62009-08-21 00:16:32 +00002214 }
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002215 if (OverloadedFunctionDecl *Ovl
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002216 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2217 if (HasExplicitTemplateArgs)
Mike Stump11289f42009-09-09 15:08:12 +00002218 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2219 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002220 SS? SS->getRange() : SourceRange(),
Mike Stump11289f42009-09-09 15:08:12 +00002221 Ovl, MemberLoc, true,
2222 LAngleLoc, ExplicitTemplateArgs,
2223 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002224 Context.OverloadTy));
2225
Douglas Gregorc1905232009-08-26 22:36:53 +00002226 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2227 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002228 }
Douglas Gregor77b50e12009-06-22 23:06:13 +00002229 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2230 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002231 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2232 Enum, MemberLoc, Enum->getType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002233 }
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002234 if (isa<TypeDecl>(MemberDecl))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002235 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlssonf571c112009-08-26 18:25:21 +00002236 << MemberName << int(OpKind == tok::arrow));
Eli Friedman1242fff2008-02-06 22:48:16 +00002237
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002238 // We found a declaration kind that we didn't expect. This is a
2239 // generic error message that tells the user that she can't refer
2240 // to this member with '.' or '->'.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002241 return ExprError(Diag(MemberLoc,
2242 diag::err_typecheck_member_reference_unknown)
Anders Carlssonf571c112009-08-26 18:25:21 +00002243 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002244 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002245
Douglas Gregorad8a3362009-09-04 17:36:40 +00002246 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2247 // into a record type was handled above, any destructor we see here is a
2248 // pseudo-destructor.
2249 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2250 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002251 // The left hand side of the dot operator shall be of scalar type. The
2252 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002253 // type.
2254 if (!BaseType->isScalarType())
2255 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2256 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002257
Douglas Gregorad8a3362009-09-04 17:36:40 +00002258 // [...] The type designated by the pseudo-destructor-name shall be the
2259 // same as the object type.
2260 if (!MemberName.getCXXNameType()->isDependentType() &&
2261 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2262 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2263 << BaseType << MemberName.getCXXNameType()
2264 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002265
2266 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002267 // the form
2268 //
Mike Stump11289f42009-09-09 15:08:12 +00002269 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2270 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002271 // shall designate the same scalar type.
2272 //
2273 // FIXME: DPG can't see any way to trigger this particular clause, so it
2274 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002275
Douglas Gregorad8a3362009-09-04 17:36:40 +00002276 // FIXME: We've lost the precise spelling of the type by going through
2277 // DeclarationName. Can we do better?
2278 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002279 OpKind == tok::arrow,
Douglas Gregorad8a3362009-09-04 17:36:40 +00002280 OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002281 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002282 SS? SS->getRange() : SourceRange(),
2283 MemberName.getCXXNameType(),
2284 MemberLoc));
2285 }
Mike Stump11289f42009-09-09 15:08:12 +00002286
Steve Naroff7cae42b2009-07-10 23:34:53 +00002287 // Handle properties on ObjC 'Class' types.
Steve Naroff4eed7a12009-07-13 17:19:15 +00002288 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002289 // Also must look for a getter name which uses property syntax.
Anders Carlssonf571c112009-08-26 18:25:21 +00002290 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2291 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002292 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2293 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2294 ObjCMethodDecl *Getter;
2295 // FIXME: need to also look locally in the implementation.
2296 if ((Getter = IFace->lookupClassMethod(Sel))) {
2297 // Check the use of this method.
2298 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2299 return ExprError();
2300 }
2301 // If we found a getter then this may be a valid dot-reference, we
2302 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002303 Selector SetterSel =
2304 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002305 PP.getSelectorTable(), Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002306 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2307 if (!Setter) {
2308 // If this reference is in an @implementation, also check for 'private'
2309 // methods.
2310 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2311 }
2312 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002313 if (!Setter)
2314 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002315
2316 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2317 return ExprError();
2318
2319 if (Getter || Setter) {
2320 QualType PType;
2321
2322 if (Getter)
2323 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002324 else
2325 // Get the expression type from Setter's incoming parameter.
2326 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002327 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002328 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002329 Setter, MemberLoc, BaseExpr));
2330 }
2331 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002332 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002333 }
2334 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002335 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2336 // (*Obj).ivar.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002337 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2338 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2339 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
Mike Stump11289f42009-09-09 15:08:12 +00002340 const ObjCInterfaceType *IFaceT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00002341 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroffa057ba92009-07-16 00:25:06 +00002342 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002343 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2344
Steve Naroffa057ba92009-07-16 00:25:06 +00002345 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2346 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002347 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002348
Steve Naroffa057ba92009-07-16 00:25:06 +00002349 if (IV) {
2350 // If the decl being referenced had an error, return an error for this
2351 // sub-expr without emitting another error, in order to avoid cascading
2352 // error cases.
2353 if (IV->isInvalidDecl())
2354 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002355
Steve Naroffa057ba92009-07-16 00:25:06 +00002356 // Check whether we can reference this field.
2357 if (DiagnoseUseOfDecl(IV, MemberLoc))
2358 return ExprError();
2359 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2360 IV->getAccessControl() != ObjCIvarDecl::Package) {
2361 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2362 if (ObjCMethodDecl *MD = getCurMethodDecl())
2363 ClassOfMethodDecl = MD->getClassInterface();
2364 else if (ObjCImpDecl && getCurFunctionDecl()) {
2365 // Case of a c-function declared inside an objc implementation.
2366 // FIXME: For a c-style function nested inside an objc implementation
2367 // class, there is no implementation context available, so we pass
2368 // down the context as argument to this routine. Ideally, this context
2369 // need be passed down in the AST node and somehow calculated from the
2370 // AST for a function decl.
2371 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002372 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002373 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2374 ClassOfMethodDecl = IMPD->getClassInterface();
2375 else if (ObjCCategoryImplDecl* CatImplClass =
2376 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2377 ClassOfMethodDecl = CatImplClass->getClassInterface();
2378 }
Mike Stump11289f42009-09-09 15:08:12 +00002379
2380 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2381 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002382 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002383 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002384 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002385 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2386 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002387 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002388 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002389 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002390
2391 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2392 MemberLoc, BaseExpr,
2393 OpKind == tok::arrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002394 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002395 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002396 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002397 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002398 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002399 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002400 // Handle properties on 'id' and qualified "id".
Mike Stump11289f42009-09-09 15:08:12 +00002401 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroff1329fa02009-07-15 18:40:39 +00002402 BaseType->isObjCQualifiedIdType())) {
2403 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002404 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002405
Steve Naroff7cae42b2009-07-10 23:34:53 +00002406 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002407 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002408 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2409 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2410 // Check the use of this declaration
2411 if (DiagnoseUseOfDecl(PD, MemberLoc))
2412 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002413
Steve Naroff7cae42b2009-07-10 23:34:53 +00002414 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2415 MemberLoc, BaseExpr));
2416 }
2417 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2418 // Check the use of this method.
2419 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2420 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002421
Steve Naroff7cae42b2009-07-10 23:34:53 +00002422 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002423 OMD->getResultType(),
2424 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002425 NULL, 0));
2426 }
2427 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002428
Steve Naroff7cae42b2009-07-10 23:34:53 +00002429 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002430 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002431 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002432 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2433 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002434 const ObjCObjectPointerType *OPT;
Mike Stump11289f42009-09-09 15:08:12 +00002435 if (OpKind == tok::period &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00002436 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2437 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2438 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002439 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002440
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002441 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002442 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002443 // Check whether we can reference this property.
2444 if (DiagnoseUseOfDecl(PD, MemberLoc))
2445 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002446 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002447 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002448 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00002449 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2450 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002451 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00002452 MemberLoc, BaseExpr));
2453 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002454 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00002455 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2456 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002457 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002458 // Check whether we can reference this property.
2459 if (DiagnoseUseOfDecl(PD, MemberLoc))
2460 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00002461
Steve Narofff6009ed2009-01-21 00:14:39 +00002462 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00002463 MemberLoc, BaseExpr));
2464 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002465 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2466 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002467 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002468 // Check whether we can reference this property.
2469 if (DiagnoseUseOfDecl(PD, MemberLoc))
2470 return ExprError();
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002471
Steve Naroff7cae42b2009-07-10 23:34:53 +00002472 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2473 MemberLoc, BaseExpr));
2474 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002475 // If that failed, look for an "implicit" property by seeing if the nullary
2476 // selector is implemented.
2477
2478 // FIXME: The logic for looking up nullary and unary selectors should be
2479 // shared with the code in ActOnInstanceMessage.
2480
Anders Carlssonf571c112009-08-26 18:25:21 +00002481 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002482 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002483
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002484 // If this reference is in an @implementation, check for 'private' methods.
2485 if (!Getter)
Fariborz Jahanian69ba9352009-04-07 18:28:06 +00002486 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002487
Steve Naroff1df62692008-10-22 19:16:27 +00002488 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002489 if (!Getter)
2490 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002491 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002492 // Check if we can reference this property.
2493 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2494 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002495 }
2496 // If we found a getter then this may be a valid dot-reference, we
2497 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002498 Selector SetterSel =
2499 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002500 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002501 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002502 if (!Setter) {
2503 // If this reference is in an @implementation, also check for 'private'
2504 // methods.
Fariborz Jahanian69ba9352009-04-07 18:28:06 +00002505 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002506 }
2507 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002508 if (!Setter)
2509 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002510
Steve Naroff1d984fe2009-03-11 13:48:17 +00002511 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2512 return ExprError();
2513
2514 if (Getter || Setter) {
2515 QualType PType;
2516
2517 if (Getter)
2518 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002519 else
2520 // Get the expression type from Setter's incoming parameter.
2521 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002522 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002523 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00002524 Setter, MemberLoc, BaseExpr));
2525 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002526 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002527 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00002528 }
Mike Stump11289f42009-09-09 15:08:12 +00002529
Steve Naroffe87026a2009-07-24 17:54:45 +00002530 // Handle the following exceptional case (*Obj).isa.
Mike Stump11289f42009-09-09 15:08:12 +00002531 if (OpKind == tok::period &&
Steve Naroffe87026a2009-07-24 17:54:45 +00002532 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00002533 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00002534 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2535 Context.getObjCIdType()));
2536
Chris Lattnerb63a7452008-07-21 04:28:12 +00002537 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002538 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002539 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00002540 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2541 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002542 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00002543 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00002544 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002545 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002546
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002547 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2548 << BaseType << BaseExpr->getSourceRange();
2549
2550 // If the user is trying to apply -> or . to a function or function
2551 // pointer, it's probably because they forgot parentheses to call
2552 // the function. Suggest the addition of those parentheses.
Mike Stump11289f42009-09-09 15:08:12 +00002553 if (BaseType == Context.OverloadTy ||
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002554 BaseType->isFunctionType() ||
Mike Stump11289f42009-09-09 15:08:12 +00002555 (BaseType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002556 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002557 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2558 Diag(Loc, diag::note_member_reference_needs_call)
2559 << CodeModificationHint::CreateInsertion(Loc, "()");
2560 }
2561
2562 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00002563}
2564
Anders Carlssonf571c112009-08-26 18:25:21 +00002565Action::OwningExprResult
2566Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2567 tok::TokenKind OpKind, SourceLocation MemberLoc,
2568 IdentifierInfo &Member,
2569 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Mike Stump11289f42009-09-09 15:08:12 +00002570 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
Anders Carlssonf571c112009-08-26 18:25:21 +00002571 DeclarationName(&Member), ObjCImpDecl, SS);
2572}
2573
Anders Carlsson355933d2009-08-25 03:49:14 +00002574Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2575 FunctionDecl *FD,
2576 ParmVarDecl *Param) {
2577 if (Param->hasUnparsedDefaultArg()) {
2578 Diag (CallLoc,
2579 diag::err_use_of_default_argument_to_function_declared_later) <<
2580 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002581 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00002582 diag::note_default_argument_declared_here);
2583 } else {
2584 if (Param->hasUninstantiatedDefaultArg()) {
2585 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2586
2587 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002588 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00002589
Mike Stump11289f42009-09-09 15:08:12 +00002590 InstantiatingTemplate Inst(*this, CallLoc, Param,
2591 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00002592 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00002593
John McCall76d824f2009-08-25 22:02:44 +00002594 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00002595 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00002596 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002597
2598 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson355933d2009-08-25 03:49:14 +00002599 /*FIXME:EqualLoc*/
2600 UninstExpr->getSourceRange().getBegin()))
2601 return ExprError();
2602 }
Mike Stump11289f42009-09-09 15:08:12 +00002603
Anders Carlsson355933d2009-08-25 03:49:14 +00002604 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +00002605
Anders Carlsson355933d2009-08-25 03:49:14 +00002606 // If the default expression creates temporaries, we need to
2607 // push them to the current stack of expression temporaries so they'll
2608 // be properly destroyed.
Mike Stump11289f42009-09-09 15:08:12 +00002609 if (CXXExprWithTemporaries *E
Anders Carlsson355933d2009-08-25 03:49:14 +00002610 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002611 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson355933d2009-08-25 03:49:14 +00002612 "Can't destroy temporaries in a default argument expr!");
2613 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2614 ExprTemporaries.push_back(E->getTemporary(I));
2615 }
2616 }
2617
2618 // We already type-checked the argument, so we know it works.
2619 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2620}
2621
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002622/// ConvertArgumentsForCall - Converts the arguments specified in
2623/// Args/NumArgs to the parameter types of the function FDecl with
2624/// function prototype Proto. Call is the call expression itself, and
2625/// Fn is the function expression. For a C++ member function, this
2626/// routine does not attempt to convert the object argument. Returns
2627/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002628bool
2629Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002630 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002631 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002632 Expr **Args, unsigned NumArgs,
2633 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002634 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002635 // assignment, to the types of the corresponding parameter, ...
2636 unsigned NumArgsInProto = Proto->getNumArgs();
2637 unsigned NumArgsToCheck = NumArgs;
Douglas Gregorb6b99612009-01-23 21:30:56 +00002638 bool Invalid = false;
2639
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002640 // If too few arguments are available (and we don't have default
2641 // arguments for the remaining parameters), don't make the call.
2642 if (NumArgs < NumArgsInProto) {
2643 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2644 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2645 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2646 // Use default arguments for missing arguments
2647 NumArgsToCheck = NumArgsInProto;
Ted Kremenek5a201952009-02-07 01:47:29 +00002648 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002649 }
2650
2651 // If too many are passed and not variadic, error on the extras and drop
2652 // them.
2653 if (NumArgs > NumArgsInProto) {
2654 if (!Proto->isVariadic()) {
2655 Diag(Args[NumArgsInProto]->getLocStart(),
2656 diag::err_typecheck_call_too_many_args)
2657 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2658 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2659 Args[NumArgs-1]->getLocEnd());
2660 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00002661 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregorb6b99612009-01-23 21:30:56 +00002662 Invalid = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002663 }
2664 NumArgsToCheck = NumArgsInProto;
2665 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002666
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002667 // Continue to check argument types (even if we have too few/many args).
2668 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2669 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002670
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002671 Expr *Arg;
Douglas Gregor58354032008-12-24 00:01:03 +00002672 if (i < NumArgs) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002673 Arg = Args[i];
Douglas Gregor58354032008-12-24 00:01:03 +00002674
Eli Friedman3164fb12009-03-22 22:00:50 +00002675 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2676 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00002677 PDiag(diag::err_call_incomplete_argument)
2678 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002679 return true;
2680
Douglas Gregor58354032008-12-24 00:01:03 +00002681 // Pass the argument.
2682 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2683 return true;
Anders Carlsson84613c42009-06-12 16:51:40 +00002684 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00002685 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump11289f42009-09-09 15:08:12 +00002686
2687 OwningExprResult ArgExpr =
Anders Carlsson355933d2009-08-25 03:49:14 +00002688 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2689 FDecl, Param);
2690 if (ArgExpr.isInvalid())
2691 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002692
Anders Carlsson355933d2009-08-25 03:49:14 +00002693 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00002694 }
Mike Stump11289f42009-09-09 15:08:12 +00002695
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002696 Call->setArg(i, Arg);
2697 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002698
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002699 // If this is a variadic call, handle args passed through "...".
2700 if (Proto->isVariadic()) {
Anders Carlssona7d069d2009-01-16 16:48:51 +00002701 VariadicCallType CallType = VariadicFunction;
2702 if (Fn->getType()->isBlockPointerType())
2703 CallType = VariadicBlock; // Block
2704 else if (isa<MemberExpr>(Fn))
2705 CallType = VariadicMethod;
2706
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002707 // Promote the arguments (C99 6.5.2.2p7).
2708 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2709 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00002710 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002711 Call->setArg(i, Arg);
2712 }
2713 }
2714
Douglas Gregorb6b99612009-01-23 21:30:56 +00002715 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002716}
2717
Steve Naroff83895f72007-09-16 03:34:24 +00002718/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00002719/// This provides the location of the left/right parens and a list of comma
2720/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002721Action::OwningExprResult
2722Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2723 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002724 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002725 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002726
2727 // Since this might be a postfix expression, get rid of ParenListExprs.
2728 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00002729
Anders Carlsson3cbc8592009-05-01 19:30:39 +00002730 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002731 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00002732 assert(Fn && "no function call expression");
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002733 FunctionDecl *FDecl = NULL;
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002734 NamedDecl *NDecl = NULL;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002735 DeclarationName UnqualifiedName;
Mike Stump11289f42009-09-09 15:08:12 +00002736
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002737 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002738 // If this is a pseudo-destructor expression, build the call immediately.
2739 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2740 if (NumArgs > 0) {
2741 // Pseudo-destructor calls should not have any arguments.
2742 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2743 << CodeModificationHint::CreateRemoval(
2744 SourceRange(Args[0]->getLocStart(),
2745 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00002746
Douglas Gregorad8a3362009-09-04 17:36:40 +00002747 for (unsigned I = 0; I != NumArgs; ++I)
2748 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002749
Douglas Gregorad8a3362009-09-04 17:36:40 +00002750 NumArgs = 0;
2751 }
Mike Stump11289f42009-09-09 15:08:12 +00002752
Douglas Gregorad8a3362009-09-04 17:36:40 +00002753 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2754 RParenLoc));
2755 }
Mike Stump11289f42009-09-09 15:08:12 +00002756
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002757 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00002758 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00002759 // FIXME: Will need to cache the results of name lookup (including ADL) in
2760 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002761 bool Dependent = false;
2762 if (Fn->isTypeDependent())
2763 Dependent = true;
2764 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2765 Dependent = true;
2766
2767 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002768 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002769 Context.DependentTy, RParenLoc));
2770
2771 // Determine whether this is a call to an object (C++ [over.call.object]).
2772 if (Fn->getType()->isRecordType())
2773 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2774 CommaLocs, RParenLoc));
2775
Douglas Gregore254f902009-02-04 00:32:51 +00002776 // Determine whether this is a call to a member function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002777 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2778 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2779 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2780 isa<CXXMethodDecl>(MemDecl) ||
2781 (isa<FunctionTemplateDecl>(MemDecl) &&
2782 isa<CXXMethodDecl>(
2783 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002784 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2785 CommaLocs, RParenLoc));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002786 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002787 }
2788
Douglas Gregore254f902009-02-04 00:32:51 +00002789 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002790 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00002791 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregore254f902009-02-04 00:32:51 +00002792 Expr *FnExpr = Fn;
2793 bool ADL = true;
Douglas Gregor89026b52009-06-30 23:57:56 +00002794 bool HasExplicitTemplateArgs = 0;
2795 const TemplateArgument *ExplicitTemplateArgs = 0;
2796 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregore254f902009-02-04 00:32:51 +00002797 while (true) {
2798 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2799 FnExpr = IcExpr->getSubExpr();
2800 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002801 // Parentheses around a function disable ADL
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002802 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregore254f902009-02-04 00:32:51 +00002803 ADL = false;
2804 FnExpr = PExpr->getSubExpr();
2805 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump4e1f26a2009-02-19 03:04:26 +00002806 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregore254f902009-02-04 00:32:51 +00002807 == UnaryOperator::AddrOf) {
2808 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregora727cb92009-06-30 22:34:41 +00002809 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattner3a230732009-02-14 07:22:29 +00002810 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2811 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregora727cb92009-06-30 22:34:41 +00002812 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattner3a230732009-02-14 07:22:29 +00002813 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002814 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattner3a230732009-02-14 07:22:29 +00002815 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2816 UnqualifiedName = DepName->getName();
2817 break;
Mike Stump11289f42009-09-09 15:08:12 +00002818 } else if (TemplateIdRefExpr *TemplateIdRef
Douglas Gregora727cb92009-06-30 22:34:41 +00002819 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2820 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregoraa87ebc2009-07-29 18:26:50 +00002821 if (!NDecl)
2822 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregor89026b52009-06-30 23:57:56 +00002823 HasExplicitTemplateArgs = true;
2824 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2825 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
Mike Stump11289f42009-09-09 15:08:12 +00002826
Douglas Gregor89026b52009-06-30 23:57:56 +00002827 // C++ [temp.arg.explicit]p6:
2828 // [Note: For simple function names, argument dependent lookup (3.4.2)
Mike Stump11289f42009-09-09 15:08:12 +00002829 // applies even when the function name is not visible within the
Douglas Gregor89026b52009-06-30 23:57:56 +00002830 // scope of the call. This is because the call still has the syntactic
2831 // form of a function call (3.4.1). But when a function template with
2832 // explicit template arguments is used, the call does not have the
Mike Stump11289f42009-09-09 15:08:12 +00002833 // correct syntactic form unless there is a function template with
2834 // that name visible at the point of the call. If no such name is
2835 // visible, the call is not syntactically well-formed and
2836 // argument-dependent lookup does not apply. If some such name is
Douglas Gregor89026b52009-06-30 23:57:56 +00002837 // visible, argument dependent lookup applies and additional function
2838 // templates may be found in other namespaces.
2839 //
2840 // The summary of this paragraph is that, if we get to this point and the
2841 // template-id was not a qualified name, then argument-dependent lookup
2842 // is still possible.
2843 if (TemplateIdRef->getQualifier())
2844 ADL = false;
Douglas Gregora727cb92009-06-30 22:34:41 +00002845 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002846 } else {
Chris Lattner3a230732009-02-14 07:22:29 +00002847 // Any kind of name that does not refer to a declaration (or
2848 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2849 ADL = false;
Douglas Gregore254f902009-02-04 00:32:51 +00002850 break;
2851 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002852 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002853
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002854 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002855 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregora727cb92009-06-30 22:34:41 +00002856 if (NDecl) {
2857 FDecl = dyn_cast<FunctionDecl>(NDecl);
2858 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002859 FDecl = FunctionTemplate->getTemplatedDecl();
2860 else
Douglas Gregora727cb92009-06-30 22:34:41 +00002861 FDecl = dyn_cast<FunctionDecl>(NDecl);
2862 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002863 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002864
Mike Stump11289f42009-09-09 15:08:12 +00002865 if (Ovl || FunctionTemplate ||
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002866 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002867 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregore711f702009-02-14 18:57:46 +00002868 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregore254f902009-02-04 00:32:51 +00002869 ADL = false;
2870
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002871 // We don't perform ADL in C.
2872 if (!getLangOptions().CPlusPlus)
2873 ADL = false;
2874
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002875 if (Ovl || FunctionTemplate || ADL) {
Mike Stump11289f42009-09-09 15:08:12 +00002876 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00002877 HasExplicitTemplateArgs,
2878 ExplicitTemplateArgs,
2879 NumExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00002880 LParenLoc, Args, NumArgs, CommaLocs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002881 RParenLoc, ADL);
Douglas Gregore254f902009-02-04 00:32:51 +00002882 if (!FDecl)
2883 return ExprError();
2884
2885 // Update Fn to refer to the actual function selected.
2886 Expr *NewFn = 0;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002887 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregora727cb92009-06-30 22:34:41 +00002888 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregorf21eb492009-03-26 23:50:42 +00002889 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2890 QDRExpr->getLocation(),
2891 false, false,
2892 QDRExpr->getQualifierRange(),
2893 QDRExpr->getQualifier());
Douglas Gregore254f902009-02-04 00:32:51 +00002894 else
Mike Stump4e1f26a2009-02-19 03:04:26 +00002895 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregore254f902009-02-04 00:32:51 +00002896 Fn->getSourceRange().getBegin());
2897 Fn->Destroy(Context);
2898 Fn = NewFn;
2899 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002900 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002901
2902 // Promote the function operand.
2903 UsualUnaryConversions(Fn);
2904
Chris Lattner08464942007-12-28 05:29:59 +00002905 // Make the call expr early, before semantic checks. This guarantees cleanup
2906 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002907 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2908 Args, NumArgs,
2909 Context.BoolTy,
2910 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002911
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002912 const FunctionType *FuncT;
2913 if (!Fn->getType()->isBlockPointerType()) {
2914 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2915 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002916 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002917 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002918 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2919 << Fn->getType() << Fn->getSourceRange());
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002920 FuncT = PT->getPointeeType()->getAsFunctionType();
2921 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002922 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002923 getAsFunctionType();
2924 }
Chris Lattner08464942007-12-28 05:29:59 +00002925 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002926 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2927 << Fn->getType() << Fn->getSourceRange());
2928
Eli Friedman3164fb12009-03-22 22:00:50 +00002929 // Check for a valid return type
2930 if (!FuncT->getResultType()->isVoidType() &&
2931 RequireCompleteType(Fn->getSourceRange().getBegin(),
2932 FuncT->getResultType(),
Anders Carlssond624e162009-08-26 23:45:07 +00002933 PDiag(diag::err_call_incomplete_return)
2934 << TheCall->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002935 return ExprError();
2936
Chris Lattner08464942007-12-28 05:29:59 +00002937 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00002938 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002939
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002940 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002941 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002942 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002943 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00002944 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002945 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002946
Douglas Gregord8e97de2009-04-02 15:37:10 +00002947 if (FDecl) {
2948 // Check if we have too few/too many template arguments, based
2949 // on our knowledge of the function definition.
2950 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002951 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002952 const FunctionProtoType *Proto =
2953 Def->getType()->getAsFunctionProtoType();
2954 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2955 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2956 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2957 }
2958 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00002959 }
2960
Steve Naroff0b661582007-08-28 23:30:39 +00002961 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00002962 for (unsigned i = 0; i != NumArgs; i++) {
2963 Expr *Arg = Args[i];
2964 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00002965 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2966 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00002967 PDiag(diag::err_call_incomplete_argument)
2968 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002969 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00002970 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00002971 }
Steve Naroffae4143e2007-04-26 20:39:23 +00002972 }
Chris Lattner08464942007-12-28 05:29:59 +00002973
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002974 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2975 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002976 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2977 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002978
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002979 // Check for sentinels
2980 if (NDecl)
2981 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002982
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002983 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002984 if (FDecl) {
2985 if (CheckFunctionCall(FDecl, TheCall.get()))
2986 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002987
2988 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002989 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2990 } else if (NDecl) {
2991 if (CheckBlockCall(NDecl, TheCall.get()))
2992 return ExprError();
2993 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002994
Anders Carlssonf8984012009-08-16 03:06:32 +00002995 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00002996}
2997
Sebastian Redlb5d49352009-01-19 22:31:54 +00002998Action::OwningExprResult
2999Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3000 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003001 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003002 //FIXME: Preserve type source info.
3003 QualType literalType = GetTypeFromParser(Ty);
Steve Naroff57eb2c52007-07-19 21:32:11 +00003004 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003005 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003006 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003007
Eli Friedman37a186d2008-05-20 05:22:08 +00003008 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003009 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003010 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3011 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003012 } else if (!literalType->isDependentType() &&
3013 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003014 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003015 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003016 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003017 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003018
Sebastian Redlb5d49352009-01-19 22:31:54 +00003019 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003020 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003021 return ExprError();
Steve Naroffd32419d2008-01-14 18:19:28 +00003022
Chris Lattner79413952008-12-04 23:50:19 +00003023 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003024 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003025 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003026 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003027 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00003028 InitExpr.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003029 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003030 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003031}
3032
Sebastian Redlb5d49352009-01-19 22:31:54 +00003033Action::OwningExprResult
3034Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003035 SourceLocation RBraceLoc) {
3036 unsigned NumInit = initlist.size();
3037 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003038
Steve Naroff30d242c2007-09-15 18:49:24 +00003039 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003040 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003041
Mike Stump4e1f26a2009-02-19 03:04:26 +00003042 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003043 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003044 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003045 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003046}
3047
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003048/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003049bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003050 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003051 CXXMethodDecl *& ConversionDecl,
3052 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003053 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003054 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3055 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003056
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003057 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003058
3059 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3060 // type needs to be scalar.
3061 if (castType->isVoidType()) {
3062 // Cast to void allows any expr type.
3063 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003064 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3065 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3066 (castType->isStructureType() || castType->isUnionType())) {
3067 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003068 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003069 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3070 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003071 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003072 } else if (castType->isUnionType()) {
3073 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003074 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003075 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003076 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003077 Field != FieldEnd; ++Field) {
3078 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3079 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3080 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3081 << castExpr->getSourceRange();
3082 break;
3083 }
3084 }
3085 if (Field == FieldEnd)
3086 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3087 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003088 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003089 } else {
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003090 // Reject any other conversions to non-scalar types.
Chris Lattner3b054132008-11-19 05:08:23 +00003091 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003092 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003093 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003094 } else if (!castExpr->getType()->isScalarType() &&
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003095 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003096 return Diag(castExpr->getLocStart(),
3097 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003098 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanc69b7402009-06-26 00:50:28 +00003099 } else if (castType->isExtVectorType()) {
3100 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003101 return true;
3102 } else if (castType->isVectorType()) {
3103 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3104 return true;
Nate Begemanc69b7402009-06-26 00:50:28 +00003105 } else if (castExpr->getType()->isVectorType()) {
3106 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3107 return true;
Steve Naroff3f49fee2009-03-04 15:11:40 +00003108 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroffb47acdb2009-04-08 23:52:26 +00003109 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003110 } else if (!castType->isArithmeticType()) {
3111 QualType castExprType = castExpr->getType();
3112 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3113 return Diag(castExpr->getLocStart(),
3114 diag::err_cast_pointer_from_non_pointer_int)
3115 << castExprType << castExpr->getSourceRange();
3116 } else if (!castExpr->getType()->isArithmeticType()) {
3117 if (!castType->isIntegralType() && castType->isArithmeticType())
3118 return Diag(castExpr->getLocStart(),
3119 diag::err_cast_pointer_to_non_pointer_int)
3120 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003121 }
Fariborz Jahanian88fead82009-05-22 21:42:52 +00003122 if (isa<ObjCSelectorExpr>(castExpr))
3123 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003124 return false;
3125}
3126
Chris Lattner6c9ffe92007-12-20 00:44:32 +00003127bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003128 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003129
Anders Carlssonde71adf2007-11-27 05:51:55 +00003130 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003131 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003132 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003133 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003134 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003135 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003136 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003137 } else
3138 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003139 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003140 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003141
Anders Carlssonde71adf2007-11-27 05:51:55 +00003142 return false;
3143}
3144
Nate Begemanc69b7402009-06-26 00:50:28 +00003145bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3146 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Mike Stump11289f42009-09-09 15:08:12 +00003147
Nate Begemanc8961a42009-06-27 22:05:55 +00003148 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3149 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003150 if (SrcTy->isVectorType()) {
3151 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3152 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3153 << DestTy << SrcTy << R;
3154 return false;
3155 }
3156
Nate Begemanbd956c42009-06-28 02:36:38 +00003157 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003158 // conversion will take place first from scalar to elt type, and then
3159 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003160 if (SrcTy->isPointerType())
3161 return Diag(R.getBegin(),
3162 diag::err_invalid_conversion_between_vector_and_scalar)
3163 << DestTy << SrcTy << R;
Nate Begemanc69b7402009-06-26 00:50:28 +00003164 return false;
3165}
3166
Sebastian Redlb5d49352009-01-19 22:31:54 +00003167Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003168Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003169 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003170 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003171
Sebastian Redlb5d49352009-01-19 22:31:54 +00003172 assert((Ty != 0) && (Op.get() != 0) &&
3173 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003174
Nate Begeman5ec4b312009-08-10 23:49:36 +00003175 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003176 //FIXME: Preserve type source info.
3177 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003178
Nate Begeman5ec4b312009-08-10 23:49:36 +00003179 // If the Expr being casted is a ParenListExpr, handle it specially.
3180 if (isa<ParenListExpr>(castExpr))
3181 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003182 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003183 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003184 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003185 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003186
3187 if (Method) {
3188 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
3189 Method, move(Op));
3190
3191 if (CastArg.isInvalid())
3192 return ExprError();
3193
3194 castExpr = CastArg.takeAs<Expr>();
3195 } else {
3196 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003197 }
Mike Stump11289f42009-09-09 15:08:12 +00003198
Sebastian Redl9f831db2009-07-25 15:41:38 +00003199 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003200 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003201 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003202}
3203
Nate Begeman5ec4b312009-08-10 23:49:36 +00003204/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3205/// of comma binary operators.
3206Action::OwningExprResult
3207Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3208 Expr *expr = EA.takeAs<Expr>();
3209 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3210 if (!E)
3211 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003212
Nate Begeman5ec4b312009-08-10 23:49:36 +00003213 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003214
Nate Begeman5ec4b312009-08-10 23:49:36 +00003215 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3216 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3217 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003218
Nate Begeman5ec4b312009-08-10 23:49:36 +00003219 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3220}
3221
3222Action::OwningExprResult
3223Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3224 SourceLocation RParenLoc, ExprArg Op,
3225 QualType Ty) {
3226 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003227
3228 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003229 // then handle it as such.
3230 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3231 if (PE->getNumExprs() == 0) {
3232 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3233 return ExprError();
3234 }
3235
3236 llvm::SmallVector<Expr *, 8> initExprs;
3237 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3238 initExprs.push_back(PE->getExpr(i));
3239
3240 // FIXME: This means that pretty-printing the final AST will produce curly
3241 // braces instead of the original commas.
3242 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003243 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003244 initExprs.size(), RParenLoc);
3245 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003246 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003247 Owned(E));
3248 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003249 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003250 // sequence of BinOp comma operators.
3251 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3252 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3253 }
3254}
3255
3256Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3257 SourceLocation R,
3258 MultiExprArg Val) {
3259 unsigned nexprs = Val.size();
3260 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3261 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3262 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3263 return Owned(expr);
3264}
3265
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003266/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3267/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003268/// C99 6.5.15
3269QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3270 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003271 // C++ is sufficiently different to merit its own checker.
3272 if (getLangOptions().CPlusPlus)
3273 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3274
Chris Lattner432cff52009-02-18 04:28:32 +00003275 UsualUnaryConversions(Cond);
3276 UsualUnaryConversions(LHS);
3277 UsualUnaryConversions(RHS);
3278 QualType CondTy = Cond->getType();
3279 QualType LHSTy = LHS->getType();
3280 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003281
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003282 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003283 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3284 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3285 << CondTy;
3286 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003287 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003288
Chris Lattnere2949f42008-01-06 22:42:25 +00003289 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003290 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3291 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003292
Chris Lattnere2949f42008-01-06 22:42:25 +00003293 // If both operands have arithmetic type, do the usual arithmetic conversions
3294 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003295 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3296 UsualArithmeticConversions(LHS, RHS);
3297 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003298 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003299
Chris Lattnere2949f42008-01-06 22:42:25 +00003300 // If both operands are the same structure or union type, the result is that
3301 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003302 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3303 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003304 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003305 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003306 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003307 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003308 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003309 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003310
Chris Lattnere2949f42008-01-06 22:42:25 +00003311 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003312 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003313 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3314 if (!LHSTy->isVoidType())
3315 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3316 << RHS->getSourceRange();
3317 if (!RHSTy->isVoidType())
3318 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3319 << LHS->getSourceRange();
3320 ImpCastExprToType(LHS, Context.VoidTy);
3321 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003322 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003323 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003324 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3325 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003326 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattner432cff52009-02-18 04:28:32 +00003327 RHS->isNullPointerConstant(Context)) {
3328 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3329 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003330 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003331 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattner432cff52009-02-18 04:28:32 +00003332 LHS->isNullPointerConstant(Context)) {
3333 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3334 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003335 }
David Chisnall9f57c292009-08-17 16:35:33 +00003336 // Handle things like Class and struct objc_class*. Here we case the result
3337 // to the pseudo-builtin, because that will be implicitly cast back to the
3338 // redefinition type if an attempt is made to access its fields.
3339 if (LHSTy->isObjCClassType() &&
3340 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3341 ImpCastExprToType(RHS, LHSTy);
3342 return LHSTy;
3343 }
3344 if (RHSTy->isObjCClassType() &&
3345 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3346 ImpCastExprToType(LHS, RHSTy);
3347 return RHSTy;
3348 }
3349 // And the same for struct objc_object* / id
3350 if (LHSTy->isObjCIdType() &&
3351 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3352 ImpCastExprToType(RHS, LHSTy);
3353 return LHSTy;
3354 }
3355 if (RHSTy->isObjCIdType() &&
3356 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3357 ImpCastExprToType(LHS, RHSTy);
3358 return RHSTy;
3359 }
Steve Naroff05efa972009-07-01 14:36:47 +00003360 // Handle block pointer types.
3361 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3362 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3363 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3364 QualType destType = Context.getPointerType(Context.VoidTy);
Mike Stump11289f42009-09-09 15:08:12 +00003365 ImpCastExprToType(LHS, destType);
Steve Naroff05efa972009-07-01 14:36:47 +00003366 ImpCastExprToType(RHS, destType);
3367 return destType;
3368 }
3369 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3370 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3371 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003372 }
Steve Naroff05efa972009-07-01 14:36:47 +00003373 // We have 2 block pointer types.
3374 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3375 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003376 return LHSTy;
3377 }
Steve Naroff05efa972009-07-01 14:36:47 +00003378 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003379 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3380 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003381
Steve Naroff05efa972009-07-01 14:36:47 +00003382 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3383 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003384 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3385 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3386 // In this situation, we assume void* type. No especially good
3387 // reason, but this is what gcc does, and we do have to pick
3388 // to get a consistent AST.
3389 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3390 ImpCastExprToType(LHS, incompatTy);
3391 ImpCastExprToType(RHS, incompatTy);
3392 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003393 }
Steve Naroff05efa972009-07-01 14:36:47 +00003394 // The block pointer types are compatible.
3395 ImpCastExprToType(LHS, LHSTy);
3396 ImpCastExprToType(RHS, LHSTy);
Steve Naroffea4c7802009-04-08 17:05:15 +00003397 return LHSTy;
3398 }
Steve Naroff05efa972009-07-01 14:36:47 +00003399 // Check constraints for Objective-C object pointers types.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003400 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003401
Steve Naroff05efa972009-07-01 14:36:47 +00003402 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3403 // Two identical object pointer types are always compatible.
3404 return LHSTy;
3405 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00003406 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3407 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff05efa972009-07-01 14:36:47 +00003408 QualType compositeType = LHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003409
Steve Naroff05efa972009-07-01 14:36:47 +00003410 // If both operands are interfaces and either operand can be
3411 // assigned to the other, use that type as the composite
3412 // type. This allows
3413 // xxx ? (A*) a : (B*) b
3414 // where B is a subclass of A.
3415 //
3416 // Additionally, as for assignment, if either type is 'id'
3417 // allow silent coercion. Finally, if the types are
3418 // incompatible then make sure to use 'id' as the composite
3419 // type so the result is acceptable for sending messages to.
3420
3421 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3422 // It could return the composite type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003423 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003424 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003425 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003426 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003427 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00003428 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff8e6aee52009-07-23 01:01:38 +00003429 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump11289f42009-09-09 15:08:12 +00003430 // Need to handle "id<xx>" explicitly.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003431 // GCC allows qualified id and any Objective-C type to devolve to
3432 // id. Currently localizing to here until clear this should be
3433 // part of ObjCQualifiedIdTypesAreCompatible.
3434 compositeType = Context.getObjCIdType();
3435 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff05efa972009-07-01 14:36:47 +00003436 compositeType = Context.getObjCIdType();
3437 } else {
3438 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3439 << LHSTy << RHSTy
3440 << LHS->getSourceRange() << RHS->getSourceRange();
3441 QualType incompatTy = Context.getObjCIdType();
3442 ImpCastExprToType(LHS, incompatTy);
3443 ImpCastExprToType(RHS, incompatTy);
3444 return incompatTy;
3445 }
3446 // The object pointer types are compatible.
3447 ImpCastExprToType(LHS, compositeType);
3448 ImpCastExprToType(RHS, compositeType);
3449 return compositeType;
3450 }
Steve Naroff85d97152009-07-29 15:09:39 +00003451 // Check Objective-C object pointer types and 'void *'
3452 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003453 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff85d97152009-07-29 15:09:39 +00003454 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3455 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3456 QualType destType = Context.getPointerType(destPointee);
3457 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3458 ImpCastExprToType(RHS, destType); // promote to void*
3459 return destType;
3460 }
3461 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3462 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003463 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff85d97152009-07-29 15:09:39 +00003464 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3465 QualType destType = Context.getPointerType(destPointee);
3466 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3467 ImpCastExprToType(LHS, destType); // promote to void*
3468 return destType;
3469 }
Steve Naroff05efa972009-07-01 14:36:47 +00003470 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3471 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3472 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003473 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3474 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00003475
3476 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3477 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3478 // Figure out necessary qualifiers (C99 6.5.15p6)
3479 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3480 QualType destType = Context.getPointerType(destPointee);
3481 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3482 ImpCastExprToType(RHS, destType); // promote to void*
3483 return destType;
3484 }
3485 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3486 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3487 QualType destType = Context.getPointerType(destPointee);
3488 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3489 ImpCastExprToType(RHS, destType); // promote to void*
3490 return destType;
3491 }
3492
3493 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3494 // Two identical pointer types are always compatible.
3495 return LHSTy;
3496 }
3497 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3498 rhptee.getUnqualifiedType())) {
3499 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3500 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3501 // In this situation, we assume void* type. No especially good
3502 // reason, but this is what gcc does, and we do have to pick
3503 // to get a consistent AST.
3504 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3505 ImpCastExprToType(LHS, incompatTy);
3506 ImpCastExprToType(RHS, incompatTy);
3507 return incompatTy;
3508 }
3509 // The pointer types are compatible.
3510 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3511 // differently qualified versions of compatible types, the result type is
3512 // a pointer to an appropriately qualified version of the *composite*
3513 // type.
3514 // FIXME: Need to calculate the composite type.
3515 // FIXME: Need to add qualifiers
3516 ImpCastExprToType(LHS, LHSTy);
3517 ImpCastExprToType(RHS, LHSTy);
3518 return LHSTy;
3519 }
Mike Stump11289f42009-09-09 15:08:12 +00003520
Steve Naroff05efa972009-07-01 14:36:47 +00003521 // GCC compatibility: soften pointer/integer mismatch.
3522 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3523 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3524 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3525 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3526 return RHSTy;
3527 }
3528 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3529 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3530 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3531 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3532 return LHSTy;
3533 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00003534
Chris Lattnere2949f42008-01-06 22:42:25 +00003535 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00003536 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3537 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003538 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00003539}
3540
Steve Naroff83895f72007-09-16 03:34:24 +00003541/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00003542/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003543Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3544 SourceLocation ColonLoc,
3545 ExprArg Cond, ExprArg LHS,
3546 ExprArg RHS) {
3547 Expr *CondExpr = (Expr *) Cond.get();
3548 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00003549
3550 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3551 // was the condition.
3552 bool isLHSNull = LHSExpr == 0;
3553 if (isLHSNull)
3554 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00003555
3556 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00003557 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00003558 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003559 return ExprError();
3560
3561 Cond.release();
3562 LHS.release();
3563 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00003564 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00003565 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00003566 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00003567}
3568
Steve Naroff3f597292007-05-11 22:18:03 +00003569// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00003570// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00003571// routine is it effectively iqnores the qualifiers on the top level pointee.
3572// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3573// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003574Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003575Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00003576 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003577
David Chisnall9f57c292009-08-17 16:35:33 +00003578 if ((lhsType->isObjCClassType() &&
3579 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3580 (rhsType->isObjCClassType() &&
3581 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3582 return Compatible;
3583 }
3584
Steve Naroff1f4d7272007-05-11 04:00:31 +00003585 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003586 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3587 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003588
Steve Naroff1f4d7272007-05-11 04:00:31 +00003589 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00003590 lhptee = Context.getCanonicalType(lhptee);
3591 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00003592
Chris Lattner9bad62c2008-01-04 18:04:52 +00003593 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003594
3595 // C99 6.5.16.1p1: This following citation is common to constraints
3596 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3597 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00003598 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00003599 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00003600 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00003601
Mike Stump4e1f26a2009-02-19 03:04:26 +00003602 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3603 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00003604 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00003605 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003606 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003607 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003608
Chris Lattner0a788432008-01-03 22:56:36 +00003609 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003610 assert(rhptee->isFunctionType());
3611 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003612 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003613
Chris Lattner0a788432008-01-03 22:56:36 +00003614 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003615 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003616 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00003617
3618 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003619 assert(lhptee->isFunctionType());
3620 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003621 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003622 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00003623 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00003624 lhptee = lhptee.getUnqualifiedType();
3625 rhptee = rhptee.getUnqualifiedType();
3626 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3627 // Check if the pointee types are compatible ignoring the sign.
3628 // We explicitly check for char so that we catch "char" vs
3629 // "unsigned char" on systems where "char" is unsigned.
3630 if (lhptee->isCharType()) {
3631 lhptee = Context.UnsignedCharTy;
3632 } else if (lhptee->isSignedIntegerType()) {
3633 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3634 }
3635 if (rhptee->isCharType()) {
3636 rhptee = Context.UnsignedCharTy;
3637 } else if (rhptee->isSignedIntegerType()) {
3638 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3639 }
3640 if (lhptee == rhptee) {
3641 // Types are compatible ignoring the sign. Qualifier incompatibility
3642 // takes priority over sign incompatibility because the sign
3643 // warning can be disabled.
3644 if (ConvTy != Compatible)
3645 return ConvTy;
3646 return IncompatiblePointerSign;
3647 }
3648 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00003649 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00003650 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00003651 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00003652}
3653
Steve Naroff081c7422008-09-04 15:10:53 +00003654/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3655/// block pointer types are compatible or whether a block and normal pointer
3656/// are compatible. It is more restrict than comparing two function pointer
3657// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003658Sema::AssignConvertType
3659Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00003660 QualType rhsType) {
3661 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003662
Steve Naroff081c7422008-09-04 15:10:53 +00003663 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003664 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3665 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003666
Steve Naroff081c7422008-09-04 15:10:53 +00003667 // make sure we operate on the canonical type
3668 lhptee = Context.getCanonicalType(lhptee);
3669 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003670
Steve Naroff081c7422008-09-04 15:10:53 +00003671 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003672
Steve Naroff081c7422008-09-04 15:10:53 +00003673 // For blocks we enforce that qualifiers are identical.
3674 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3675 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003676
Eli Friedmana6638ca2009-06-08 05:08:54 +00003677 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00003678 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00003679 return ConvTy;
3680}
3681
Mike Stump4e1f26a2009-02-19 03:04:26 +00003682/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3683/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00003684/// pointers. Here are some objectionable examples that GCC considers warnings:
3685///
3686/// int a, *pint;
3687/// short *pshort;
3688/// struct foo *pfoo;
3689///
3690/// pint = pshort; // warning: assignment from incompatible pointer type
3691/// a = pint; // warning: assignment makes integer from pointer without a cast
3692/// pint = a; // warning: assignment makes pointer from integer without a cast
3693/// pint = pfoo; // warning: assignment from incompatible pointer type
3694///
3695/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00003696/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00003697///
Chris Lattner9bad62c2008-01-04 18:04:52 +00003698Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003699Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00003700 // Get canonical types. We're not formatting these types, just comparing
3701 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00003702 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3703 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00003704
3705 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00003706 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00003707
David Chisnall9f57c292009-08-17 16:35:33 +00003708 if ((lhsType->isObjCClassType() &&
3709 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3710 (rhsType->isObjCClassType() &&
3711 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3712 return Compatible;
3713 }
3714
Douglas Gregor6b754842008-10-28 00:22:11 +00003715 // If the left-hand side is a reference type, then we are in a
3716 // (rare!) case where we've allowed the use of references in C,
3717 // e.g., as a parameter type in a built-in function. In this case,
3718 // just make sure that the type referenced is compatible with the
3719 // right-hand side type. The caller is responsible for adjusting
3720 // lhsType so that the resulting expression does not have reference
3721 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003722 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00003723 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00003724 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003725 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00003726 }
Nate Begemanbd956c42009-06-28 02:36:38 +00003727 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3728 // to the same ExtVector type.
3729 if (lhsType->isExtVectorType()) {
3730 if (rhsType->isExtVectorType())
3731 return lhsType == rhsType ? Compatible : Incompatible;
3732 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3733 return Compatible;
3734 }
Mike Stump11289f42009-09-09 15:08:12 +00003735
Nate Begeman191a6b12008-07-14 18:02:46 +00003736 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003737 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00003738 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00003739 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00003740 if (getLangOptions().LaxVectorConversions &&
3741 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003742 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00003743 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00003744 }
3745 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003746 }
Eli Friedman3360d892008-05-30 18:07:22 +00003747
Chris Lattner881a2122008-01-04 23:32:24 +00003748 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00003749 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00003750
Chris Lattnerec646832008-04-07 06:49:41 +00003751 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003752 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003753 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00003754
Chris Lattnerec646832008-04-07 06:49:41 +00003755 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003756 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003757
Steve Naroffaccc4882009-07-20 17:56:53 +00003758 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003759 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003760 if (lhsType->isVoidPointerType()) // an exception to the rule.
3761 return Compatible;
3762 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003763 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003764 if (rhsType->getAs<BlockPointerType>()) {
3765 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003766 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00003767
3768 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003769 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003770 return Compatible;
3771 }
Steve Naroff081c7422008-09-04 15:10:53 +00003772 return Incompatible;
3773 }
3774
3775 if (isa<BlockPointerType>(lhsType)) {
3776 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00003777 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003778
Steve Naroff32d072c2008-09-29 18:10:17 +00003779 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003780 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003781 return Compatible;
3782
Steve Naroff081c7422008-09-04 15:10:53 +00003783 if (rhsType->isBlockPointerType())
3784 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003785
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003786 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00003787 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003788 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00003789 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00003790 return Incompatible;
3791 }
3792
Steve Naroff7cae42b2009-07-10 23:34:53 +00003793 if (isa<ObjCObjectPointerType>(lhsType)) {
3794 if (rhsType->isIntegerType())
3795 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00003796
Steve Naroffaccc4882009-07-20 17:56:53 +00003797 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003798 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003799 if (rhsType->isVoidPointerType()) // an exception to the rule.
3800 return Compatible;
3801 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003802 }
3803 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003804 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3805 return Compatible;
Steve Naroffaccc4882009-07-20 17:56:53 +00003806 if (Context.typesAreCompatible(lhsType, rhsType))
3807 return Compatible;
Steve Naroff8e6aee52009-07-23 01:01:38 +00003808 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3809 return IncompatibleObjCQualifiedId;
Steve Naroffaccc4882009-07-20 17:56:53 +00003810 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003811 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003812 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003813 if (RHSPT->getPointeeType()->isVoidType())
3814 return Compatible;
3815 }
3816 // Treat block pointers as objects.
3817 if (rhsType->isBlockPointerType())
3818 return Compatible;
3819 return Incompatible;
3820 }
Chris Lattnerec646832008-04-07 06:49:41 +00003821 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003822 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00003823 if (lhsType == Context.BoolTy)
3824 return Compatible;
3825
3826 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003827 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00003828
Mike Stump4e1f26a2009-02-19 03:04:26 +00003829 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003830 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003831
3832 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003833 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003834 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003835 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003836 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00003837 if (isa<ObjCObjectPointerType>(rhsType)) {
3838 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3839 if (lhsType == Context.BoolTy)
3840 return Compatible;
3841
3842 if (lhsType->isIntegerType())
3843 return PointerToInt;
3844
Steve Naroffaccc4882009-07-20 17:56:53 +00003845 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003846 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003847 if (lhsType->isVoidPointerType()) // an exception to the rule.
3848 return Compatible;
3849 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003850 }
3851 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003852 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00003853 return Compatible;
3854 return Incompatible;
3855 }
Eli Friedman3360d892008-05-30 18:07:22 +00003856
Chris Lattnera52c2f22008-01-04 23:18:45 +00003857 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00003858 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003859 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00003860 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00003861 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00003862}
3863
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003864/// \brief Constructs a transparent union from an expression that is
3865/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00003866static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003867 QualType UnionType, FieldDecl *Field) {
3868 // Build an initializer list that designates the appropriate member
3869 // of the transparent union.
3870 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3871 &E, 1,
3872 SourceLocation());
3873 Initializer->setType(UnionType);
3874 Initializer->setInitializedFieldInUnion(Field);
3875
3876 // Build a compound literal constructing a value of the transparent
3877 // union type from this initializer list.
3878 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3879 false);
3880}
3881
3882Sema::AssignConvertType
3883Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3884 QualType FromType = rExpr->getType();
3885
Mike Stump11289f42009-09-09 15:08:12 +00003886 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003887 // transparent_union GCC extension.
3888 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003889 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003890 return Incompatible;
3891
3892 // The field to initialize within the transparent union.
3893 RecordDecl *UD = UT->getDecl();
3894 FieldDecl *InitField = 0;
3895 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003896 for (RecordDecl::field_iterator it = UD->field_begin(),
3897 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003898 it != itend; ++it) {
3899 if (it->getType()->isPointerType()) {
3900 // If the transparent union contains a pointer type, we allow:
3901 // 1) void pointer
3902 // 2) null pointer constant
3903 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003904 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003905 ImpCastExprToType(rExpr, it->getType());
3906 InitField = *it;
3907 break;
3908 }
Mike Stump11289f42009-09-09 15:08:12 +00003909
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003910 if (rExpr->isNullPointerConstant(Context)) {
3911 ImpCastExprToType(rExpr, it->getType());
3912 InitField = *it;
3913 break;
3914 }
3915 }
3916
3917 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3918 == Compatible) {
3919 InitField = *it;
3920 break;
3921 }
3922 }
3923
3924 if (!InitField)
3925 return Incompatible;
3926
3927 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3928 return Compatible;
3929}
3930
Chris Lattner9bad62c2008-01-04 18:04:52 +00003931Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00003932Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003933 if (getLangOptions().CPlusPlus) {
3934 if (!lhsType->isRecordType()) {
3935 // C++ 5.17p3: If the left operand is not of class type, the
3936 // expression is implicitly converted (C++ 4) to the
3937 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00003938 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3939 "assigning"))
Douglas Gregor9a657932008-10-21 23:43:52 +00003940 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00003941 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00003942 }
3943
3944 // FIXME: Currently, we fall through and treat C++ classes like C
3945 // structures.
3946 }
3947
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00003948 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3949 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00003950 if ((lhsType->isPointerType() ||
3951 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00003952 lhsType->isBlockPointerType())
Fariborz Jahanian5cc21a72008-01-03 18:46:52 +00003953 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnera65e1f32008-01-16 19:17:22 +00003954 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00003955 return Compatible;
3956 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003957
Chris Lattnere6dcd502007-10-16 02:55:40 +00003958 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00003959 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff30d242c2007-09-15 18:49:24 +00003960 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00003961 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00003962 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00003963 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00003964 if (!lhsType->isReferenceType())
3965 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00003966
Chris Lattner9bad62c2008-01-04 18:04:52 +00003967 Sema::AssignConvertType result =
3968 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00003969
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00003970 // C99 6.5.16.1p2: The value of the right operand is converted to the
3971 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00003972 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3973 // so that we can use references in built-in functions even in C.
3974 // The getNonReferenceType() call makes sure that the resulting expression
3975 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003976 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor6b754842008-10-28 00:22:11 +00003977 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00003978 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00003979}
3980
Chris Lattner326f7572008-11-18 01:30:42 +00003981QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00003982 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00003983 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00003984 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00003985 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003986}
3987
Mike Stump4e1f26a2009-02-19 03:04:26 +00003988inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00003989 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003990 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00003991 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00003992 QualType lhsType =
3993 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3994 QualType rhsType =
3995 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003996
Nate Begeman191a6b12008-07-14 18:02:46 +00003997 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00003998 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00003999 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004000
Nate Begeman191a6b12008-07-14 18:02:46 +00004001 // Handle the case of a vector & extvector type of the same size and element
4002 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004003 if (getLangOptions().LaxVectorConversions) {
4004 // FIXME: Should we warn here?
4005 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004006 if (const VectorType *RV = rhsType->getAsVectorType())
4007 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004008 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004009 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004010 }
4011 }
4012 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004013
Nate Begemanbd956c42009-06-28 02:36:38 +00004014 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4015 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4016 bool swapped = false;
4017 if (rhsType->isExtVectorType()) {
4018 swapped = true;
4019 std::swap(rex, lex);
4020 std::swap(rhsType, lhsType);
4021 }
Mike Stump11289f42009-09-09 15:08:12 +00004022
Nate Begeman886448d2009-06-28 19:12:57 +00004023 // Handle the case of an ext vector and scalar.
Nate Begemanbd956c42009-06-28 02:36:38 +00004024 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
4025 QualType EltTy = LV->getElementType();
4026 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4027 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begeman886448d2009-06-28 19:12:57 +00004028 ImpCastExprToType(rex, lhsType);
Nate Begemanbd956c42009-06-28 02:36:38 +00004029 if (swapped) std::swap(rex, lex);
4030 return lhsType;
4031 }
4032 }
4033 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4034 rhsType->isRealFloatingType()) {
4035 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begeman886448d2009-06-28 19:12:57 +00004036 ImpCastExprToType(rex, lhsType);
Nate Begemanbd956c42009-06-28 02:36:38 +00004037 if (swapped) std::swap(rex, lex);
4038 return lhsType;
4039 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004040 }
4041 }
Mike Stump11289f42009-09-09 15:08:12 +00004042
Nate Begeman886448d2009-06-28 19:12:57 +00004043 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004044 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004045 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004046 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004047 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004048}
4049
Steve Naroff218bc2b2007-05-04 21:54:46 +00004050inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004051 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004052 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004053 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004054
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004055 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004056
Steve Naroffdbd9e892007-07-17 00:58:39 +00004057 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004058 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004059 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004060}
4061
Steve Naroff218bc2b2007-05-04 21:54:46 +00004062inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004063 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004064 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4065 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4066 return CheckVectorOperands(Loc, lex, rex);
4067 return InvalidOperands(Loc, lex, rex);
4068 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004069
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004070 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004071
Steve Naroffdbd9e892007-07-17 00:58:39 +00004072 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004073 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004074 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004075}
4076
4077inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004078 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004079 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4080 QualType compType = CheckVectorOperands(Loc, lex, rex);
4081 if (CompLHSTy) *CompLHSTy = compType;
4082 return compType;
4083 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004084
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004085 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004086
Steve Naroffe4718892007-04-27 18:30:00 +00004087 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004088 if (lex->getType()->isArithmeticType() &&
4089 rex->getType()->isArithmeticType()) {
4090 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004091 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004092 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004093
Eli Friedman8e122982008-05-18 18:08:51 +00004094 // Put any potential pointer into PExp
4095 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004096 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004097 std::swap(PExp, IExp);
4098
Steve Naroff6b712a72009-07-14 18:25:06 +00004099 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004100
Eli Friedman8e122982008-05-18 18:08:51 +00004101 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004102 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004103
Chris Lattner12bdebb2009-04-24 23:50:08 +00004104 // Check for arithmetic on pointers to incomplete types.
4105 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004106 if (getLangOptions().CPlusPlus) {
4107 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004108 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004109 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004110 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004111
4112 // GNU extension: arithmetic on pointer to void
4113 Diag(Loc, diag::ext_gnu_void_ptr)
4114 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004115 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004116 if (getLangOptions().CPlusPlus) {
4117 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4118 << lex->getType() << lex->getSourceRange();
4119 return QualType();
4120 }
4121
4122 // GNU extension: arithmetic on pointer to function
4123 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4124 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004125 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004126 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004127 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004128 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004129 PExp->getType()->isObjCObjectPointerType()) &&
4130 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004131 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4132 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004133 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004134 return QualType();
4135 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004136 // Diagnose bad cases where we step over interface counts.
4137 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4138 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4139 << PointeeTy << PExp->getSourceRange();
4140 return QualType();
4141 }
Mike Stump11289f42009-09-09 15:08:12 +00004142
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004143 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004144 QualType LHSTy = Context.isPromotableBitField(lex);
4145 if (LHSTy.isNull()) {
4146 LHSTy = lex->getType();
4147 if (LHSTy->isPromotableIntegerType())
4148 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004149 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004150 *CompLHSTy = LHSTy;
4151 }
Eli Friedman8e122982008-05-18 18:08:51 +00004152 return PExp->getType();
4153 }
4154 }
4155
Chris Lattner326f7572008-11-18 01:30:42 +00004156 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004157}
4158
Chris Lattner2a3569b2008-04-07 05:30:13 +00004159// C99 6.5.6
4160QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004161 SourceLocation Loc, QualType* CompLHSTy) {
4162 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4163 QualType compType = CheckVectorOperands(Loc, lex, rex);
4164 if (CompLHSTy) *CompLHSTy = compType;
4165 return compType;
4166 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004167
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004168 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004169
Chris Lattner4d62f422007-12-09 21:53:25 +00004170 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004171
Chris Lattner4d62f422007-12-09 21:53:25 +00004172 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004173 if (lex->getType()->isArithmeticType()
4174 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004175 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004176 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004177 }
Mike Stump11289f42009-09-09 15:08:12 +00004178
Chris Lattner4d62f422007-12-09 21:53:25 +00004179 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004180 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004181 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004182
Douglas Gregorac1fb652009-03-24 19:52:54 +00004183 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004184
Douglas Gregorac1fb652009-03-24 19:52:54 +00004185 bool ComplainAboutVoid = false;
4186 Expr *ComplainAboutFunc = 0;
4187 if (lpointee->isVoidType()) {
4188 if (getLangOptions().CPlusPlus) {
4189 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4190 << lex->getSourceRange() << rex->getSourceRange();
4191 return QualType();
4192 }
4193
4194 // GNU C extension: arithmetic on pointer to void
4195 ComplainAboutVoid = true;
4196 } else if (lpointee->isFunctionType()) {
4197 if (getLangOptions().CPlusPlus) {
4198 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004199 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004200 return QualType();
4201 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004202
4203 // GNU C extension: arithmetic on pointer to function
4204 ComplainAboutFunc = lex;
4205 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004206 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004207 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004208 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004209 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004210 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004211
Chris Lattner12bdebb2009-04-24 23:50:08 +00004212 // Diagnose bad cases where we step over interface counts.
4213 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4214 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4215 << lpointee << lex->getSourceRange();
4216 return QualType();
4217 }
Mike Stump11289f42009-09-09 15:08:12 +00004218
Chris Lattner4d62f422007-12-09 21:53:25 +00004219 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004220 if (rex->getType()->isIntegerType()) {
4221 if (ComplainAboutVoid)
4222 Diag(Loc, diag::ext_gnu_void_ptr)
4223 << lex->getSourceRange() << rex->getSourceRange();
4224 if (ComplainAboutFunc)
4225 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004226 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004227 << ComplainAboutFunc->getSourceRange();
4228
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004229 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004230 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004231 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004232
Chris Lattner4d62f422007-12-09 21:53:25 +00004233 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004234 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004235 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004236
Douglas Gregorac1fb652009-03-24 19:52:54 +00004237 // RHS must be a completely-type object type.
4238 // Handle the GNU void* extension.
4239 if (rpointee->isVoidType()) {
4240 if (getLangOptions().CPlusPlus) {
4241 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4242 << lex->getSourceRange() << rex->getSourceRange();
4243 return QualType();
4244 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004245
Douglas Gregorac1fb652009-03-24 19:52:54 +00004246 ComplainAboutVoid = true;
4247 } else if (rpointee->isFunctionType()) {
4248 if (getLangOptions().CPlusPlus) {
4249 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004250 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004251 return QualType();
4252 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004253
4254 // GNU extension: arithmetic on pointer to function
4255 if (!ComplainAboutFunc)
4256 ComplainAboutFunc = rex;
4257 } else if (!rpointee->isDependentType() &&
4258 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004259 PDiag(diag::err_typecheck_sub_ptr_object)
4260 << rex->getSourceRange()
4261 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004262 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004263
Eli Friedman168fe152009-05-16 13:54:38 +00004264 if (getLangOptions().CPlusPlus) {
4265 // Pointee types must be the same: C++ [expr.add]
4266 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4267 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4268 << lex->getType() << rex->getType()
4269 << lex->getSourceRange() << rex->getSourceRange();
4270 return QualType();
4271 }
4272 } else {
4273 // Pointee types must be compatible C99 6.5.6p3
4274 if (!Context.typesAreCompatible(
4275 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4276 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4277 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4278 << lex->getType() << rex->getType()
4279 << lex->getSourceRange() << rex->getSourceRange();
4280 return QualType();
4281 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004282 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004283
Douglas Gregorac1fb652009-03-24 19:52:54 +00004284 if (ComplainAboutVoid)
4285 Diag(Loc, diag::ext_gnu_void_ptr)
4286 << lex->getSourceRange() << rex->getSourceRange();
4287 if (ComplainAboutFunc)
4288 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004289 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004290 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004291
4292 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004293 return Context.getPointerDiffType();
4294 }
4295 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004296
Chris Lattner326f7572008-11-18 01:30:42 +00004297 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004298}
4299
Chris Lattner2a3569b2008-04-07 05:30:13 +00004300// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004301QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004302 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00004303 // C99 6.5.7p2: Each of the operands shall have integer type.
4304 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00004305 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004306
Chris Lattner5c11c412007-12-12 05:47:28 +00004307 // Shifts don't perform usual arithmetic conversions, they just do integer
4308 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00004309 QualType LHSTy = Context.isPromotableBitField(lex);
4310 if (LHSTy.isNull()) {
4311 LHSTy = lex->getType();
4312 if (LHSTy->isPromotableIntegerType())
4313 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004314 }
Chris Lattner3c133402007-12-13 07:28:16 +00004315 if (!isCompAssign)
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004316 ImpCastExprToType(lex, LHSTy);
4317
Chris Lattner5c11c412007-12-12 05:47:28 +00004318 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004319
Ryan Flynnf53fab82009-08-07 16:20:20 +00004320 // Sanity-check shift operands
4321 llvm::APSInt Right;
4322 // Check right/shifter operand
4323 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00004324 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00004325 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4326 else {
4327 llvm::APInt LeftBits(Right.getBitWidth(),
4328 Context.getTypeSize(lex->getType()));
4329 if (Right.uge(LeftBits))
4330 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4331 }
4332 }
4333
Chris Lattner5c11c412007-12-12 05:47:28 +00004334 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004335 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004336}
4337
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004338// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00004339QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004340 unsigned OpaqueOpc, bool isRelational) {
4341 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4342
Nate Begeman191a6b12008-07-14 18:02:46 +00004343 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004344 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004345
Chris Lattnerb620c342007-08-26 01:18:55 +00004346 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00004347 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4348 UsualArithmeticConversions(lex, rex);
4349 else {
4350 UsualUnaryConversions(lex);
4351 UsualUnaryConversions(rex);
4352 }
Steve Naroff31090012007-07-16 21:54:35 +00004353 QualType lType = lex->getType();
4354 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004355
Mike Stumpf70bcf72009-05-07 18:43:07 +00004356 if (!lType->isFloatingType()
4357 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004358 // For non-floating point types, check for self-comparisons of the form
4359 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4360 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00004361 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00004362 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004363 Expr *LHSStripped = lex->IgnoreParens();
4364 Expr *RHSStripped = rex->IgnoreParens();
4365 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4366 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00004367 if (DRL->getDecl() == DRR->getDecl() &&
4368 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004369 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00004370
Chris Lattner222b8bd2009-03-08 19:39:53 +00004371 if (isa<CastExpr>(LHSStripped))
4372 LHSStripped = LHSStripped->IgnoreParenCasts();
4373 if (isa<CastExpr>(RHSStripped))
4374 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004375
Chris Lattner222b8bd2009-03-08 19:39:53 +00004376 // Warn about comparisons against a string constant (unless the other
4377 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004378 Expr *literalString = 0;
4379 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00004380 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004381 !RHSStripped->isNullPointerConstant(Context)) {
4382 literalString = lex;
4383 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00004384 } else if ((isa<StringLiteral>(RHSStripped) ||
4385 isa<ObjCEncodeExpr>(RHSStripped)) &&
4386 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004387 literalString = rex;
4388 literalStringStripped = RHSStripped;
4389 }
4390
4391 if (literalString) {
4392 std::string resultComparison;
4393 switch (Opc) {
4394 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4395 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4396 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4397 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4398 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4399 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4400 default: assert(false && "Invalid comparison operator");
4401 }
4402 Diag(Loc, diag::warn_stringcompare)
4403 << isa<ObjCEncodeExpr>(literalStringStripped)
4404 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00004405 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4406 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4407 "strcmp(")
4408 << CodeModificationHint::CreateInsertion(
4409 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004410 resultComparison);
4411 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00004412 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004413
Douglas Gregorca63811b2008-11-19 03:25:36 +00004414 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004415 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00004416
Chris Lattnerb620c342007-08-26 01:18:55 +00004417 if (isRelational) {
4418 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004419 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004420 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00004421 // Check for comparisons of floating point operands using != and ==.
Ted Kremeneke2763b02007-10-29 17:13:39 +00004422 if (lType->isFloatingType()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004423 assert(rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004424 CheckFloatComparison(Loc,lex,rex);
Ted Kremenekd4ecc6d2007-10-29 16:40:01 +00004425 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004426
Chris Lattnerb620c342007-08-26 01:18:55 +00004427 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004428 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004429 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004430
Chris Lattner1895e582007-08-26 01:10:14 +00004431 bool LHSIsNull = lex->isNullPointerConstant(Context);
4432 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004433
Chris Lattnerb620c342007-08-26 01:18:55 +00004434 // All of the following pointer related warnings are GCC extensions, except
4435 // when handling null pointer constants. One day, we can consider making them
4436 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00004437 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00004438 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004439 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00004440 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004441 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004442
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004443 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00004444 if (LCanPointeeTy == RCanPointeeTy)
4445 return ResultTy;
4446
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004447 // C++ [expr.rel]p2:
4448 // [...] Pointer conversions (4.10) and qualification
4449 // conversions (4.4) are performed on pointer operands (or on
4450 // a pointer operand and a null pointer constant) to bring
4451 // them to their composite pointer type. [...]
4452 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004453 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004454 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00004455 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004456 if (T.isNull()) {
4457 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4458 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4459 return QualType();
4460 }
4461
4462 ImpCastExprToType(lex, T);
4463 ImpCastExprToType(rex, T);
4464 return ResultTy;
4465 }
Eli Friedman16c209612009-08-23 00:27:47 +00004466 // C99 6.5.9p2 and C99 6.5.8p2
4467 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4468 RCanPointeeTy.getUnqualifiedType())) {
4469 // Valid unless a relational comparison of function pointers
4470 if (isRelational && LCanPointeeTy->isFunctionType()) {
4471 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4472 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4473 }
4474 } else if (!isRelational &&
4475 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4476 // Valid unless comparison between non-null pointer and function pointer
4477 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4478 && !LHSIsNull && !RHSIsNull) {
4479 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4480 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4481 }
4482 } else {
4483 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00004484 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004485 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00004486 }
Eli Friedman16c209612009-08-23 00:27:47 +00004487 if (LCanPointeeTy != RCanPointeeTy)
4488 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004489 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004490 }
Mike Stump11289f42009-09-09 15:08:12 +00004491
Sebastian Redl576fd422009-05-10 18:38:11 +00004492 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00004493 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004494 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00004495 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004496 (lType->isPointerType() ||
4497 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004498 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004499 return ResultTy;
4500 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004501 if (LHSIsNull &&
4502 (rType->isPointerType() ||
4503 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004504 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004505 return ResultTy;
4506 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004507
4508 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00004509 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004510 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4511 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004512 // In addition, pointers to members can be compared, or a pointer to
4513 // member and a null pointer constant. Pointer to member conversions
4514 // (4.11) and qualification conversions (4.4) are performed to bring
4515 // them to a common type. If one operand is a null pointer constant,
4516 // the common type is the type of the other operand. Otherwise, the
4517 // common type is a pointer to member type similar (4.4) to the type
4518 // of one of the operands, with a cv-qualification signature (4.4)
4519 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004520 // types.
4521 QualType T = FindCompositePointerType(lex, rex);
4522 if (T.isNull()) {
4523 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4524 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4525 return QualType();
4526 }
Mike Stump11289f42009-09-09 15:08:12 +00004527
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004528 ImpCastExprToType(lex, T);
4529 ImpCastExprToType(rex, T);
4530 return ResultTy;
4531 }
Mike Stump11289f42009-09-09 15:08:12 +00004532
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004533 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00004534 if (lType->isNullPtrType() && rType->isNullPtrType())
4535 return ResultTy;
4536 }
Mike Stump11289f42009-09-09 15:08:12 +00004537
Steve Naroff081c7422008-09-04 15:10:53 +00004538 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00004539 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004540 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4541 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004542
Steve Naroff081c7422008-09-04 15:10:53 +00004543 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00004544 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004545 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004546 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00004547 }
4548 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004549 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00004550 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00004551 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00004552 if (!isRelational
4553 && ((lType->isBlockPointerType() && rType->isPointerType())
4554 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00004555 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004556 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004557 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004558 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004559 ->getPointeeType()->isVoidType())))
4560 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4561 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00004562 }
4563 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004564 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00004565 }
Steve Naroff081c7422008-09-04 15:10:53 +00004566
Steve Naroff7cae42b2009-07-10 23:34:53 +00004567 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004568 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004569 const PointerType *LPT = lType->getAs<PointerType>();
4570 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004571 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004572 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004573 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004574 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004575
Steve Naroff753567f2008-11-17 19:49:16 +00004576 if (!LPtrToVoid && !RPtrToVoid &&
4577 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004578 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004579 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004580 }
Daniel Dunbar340b5dd2008-10-23 23:30:52 +00004581 ImpCastExprToType(rex, lType);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004582 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00004583 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004584 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004585 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004586 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4587 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffb788d9b2008-06-03 14:04:54 +00004588 ImpCastExprToType(rex, lType);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004589 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00004590 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00004591 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004592 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004593 unsigned DiagID = 0;
4594 if (RHSIsNull) {
4595 if (isRelational)
4596 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4597 } else if (isRelational)
4598 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4599 else
4600 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004601
Chris Lattnerd99bd522009-08-23 00:03:44 +00004602 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004603 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004604 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004605 }
Chris Lattnera65e1f32008-01-16 19:17:22 +00004606 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004607 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004608 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004609 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004610 unsigned DiagID = 0;
4611 if (LHSIsNull) {
4612 if (isRelational)
4613 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4614 } else if (isRelational)
4615 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4616 else
4617 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004618
Chris Lattnerd99bd522009-08-23 00:03:44 +00004619 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004620 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004621 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004622 }
Chris Lattnera65e1f32008-01-16 19:17:22 +00004623 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004624 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00004625 }
Steve Naroff4b191572008-09-04 16:56:14 +00004626 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00004627 if (!isRelational && RHSIsNull
4628 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4b191572008-09-04 16:56:14 +00004629 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004630 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004631 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00004632 if (!isRelational && LHSIsNull
4633 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4b191572008-09-04 16:56:14 +00004634 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregorca63811b2008-11-19 03:25:36 +00004635 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004636 }
Chris Lattner326f7572008-11-18 01:30:42 +00004637 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004638}
4639
Nate Begeman191a6b12008-07-14 18:02:46 +00004640/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00004641/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00004642/// like a scalar comparison, a vector comparison produces a vector of integer
4643/// types.
4644QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00004645 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00004646 bool isRelational) {
4647 // Check to make sure we're operating on vectors of the same type and width,
4648 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00004649 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004650 if (vType.isNull())
4651 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004652
Nate Begeman191a6b12008-07-14 18:02:46 +00004653 QualType lType = lex->getType();
4654 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004655
Nate Begeman191a6b12008-07-14 18:02:46 +00004656 // For non-floating point types, check for self-comparisons of the form
4657 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4658 // often indicate logic errors in the program.
4659 if (!lType->isFloatingType()) {
4660 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4661 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4662 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004663 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00004664 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004665
Nate Begeman191a6b12008-07-14 18:02:46 +00004666 // Check for comparisons of floating point operands using != and ==.
4667 if (!isRelational && lType->isFloatingType()) {
4668 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004669 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004670 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004671
Nate Begeman191a6b12008-07-14 18:02:46 +00004672 // Return the type for the comparison, which is the same as vector type for
4673 // integer vectors, or an integer type of identical size and number of
4674 // elements for floating point vectors.
4675 if (lType->isIntegerType())
4676 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004677
Nate Begeman191a6b12008-07-14 18:02:46 +00004678 const VectorType *VTy = lType->getAsVectorType();
Nate Begeman191a6b12008-07-14 18:02:46 +00004679 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004680 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00004681 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00004682 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004683 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4684
Mike Stump4e1f26a2009-02-19 03:04:26 +00004685 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004686 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00004687 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4688}
4689
Steve Naroff218bc2b2007-05-04 21:54:46 +00004690inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004691 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00004692 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004693 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004694
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004695 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004696
Steve Naroffdbd9e892007-07-17 00:58:39 +00004697 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004698 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004699 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004700}
4701
Steve Naroff218bc2b2007-05-04 21:54:46 +00004702inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00004703 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroff31090012007-07-16 21:54:35 +00004704 UsualUnaryConversions(lex);
4705 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004706
Eli Friedman58639e52008-05-13 20:16:47 +00004707 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Steve Naroff218bc2b2007-05-04 21:54:46 +00004708 return Context.IntTy;
Chris Lattner326f7572008-11-18 01:30:42 +00004709 return InvalidOperands(Loc, lex, rex);
Steve Naroffae4143e2007-04-26 20:39:23 +00004710}
4711
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004712/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4713/// is a read-only property; return true if so. A readonly property expression
4714/// depends on various declarations and thus must be treated specially.
4715///
Mike Stump11289f42009-09-09 15:08:12 +00004716static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004717 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4718 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4719 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4720 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004721 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00004722 BaseType->getAsObjCInterfacePointerType())
4723 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4724 if (S.isPropertyReadonly(PDecl, IFace))
4725 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004726 }
4727 }
4728 return false;
4729}
4730
Chris Lattner30bd3272008-11-18 01:22:49 +00004731/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4732/// emit an error and return true. If so, return false.
4733static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004734 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00004735 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004736 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004737 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4738 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00004739 if (IsLV == Expr::MLV_Valid)
4740 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004741
Chris Lattner30bd3272008-11-18 01:22:49 +00004742 unsigned Diag = 0;
4743 bool NeedType = false;
4744 switch (IsLV) { // C99 6.5.16p2
4745 default: assert(0 && "Unknown result from isModifiableLvalue!");
4746 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004747 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004748 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4749 NeedType = true;
4750 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004751 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004752 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4753 NeedType = true;
4754 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00004755 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00004756 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4757 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004758 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00004759 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4760 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004761 case Expr::MLV_IncompleteType:
4762 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00004763 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00004764 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4765 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00004766 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00004767 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4768 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00004769 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00004770 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4771 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00004772 case Expr::MLV_ReadonlyProperty:
4773 Diag = diag::error_readonly_property_assignment;
4774 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00004775 case Expr::MLV_NoSetterProperty:
4776 Diag = diag::error_nosetter_property_assignment;
4777 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004778 }
Steve Naroffad373bd2007-07-31 12:34:36 +00004779
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004780 SourceRange Assign;
4781 if (Loc != OrigLoc)
4782 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00004783 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004784 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004785 else
Mike Stump11289f42009-09-09 15:08:12 +00004786 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004787 return true;
4788}
4789
4790
4791
4792// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00004793QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4794 SourceLocation Loc,
4795 QualType CompoundType) {
4796 // Verify that LHS is a modifiable lvalue, and emit error if not.
4797 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00004798 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00004799
4800 QualType LHSType = LHS->getType();
4801 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004802
Chris Lattner9bad62c2008-01-04 18:04:52 +00004803 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00004804 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00004805 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00004806 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004807 // Special case of NSObject attributes on c-style pointer types.
4808 if (ConvTy == IncompatiblePointer &&
4809 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00004810 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004811 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00004812 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004813 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004814
Chris Lattnerea714382008-08-21 18:04:13 +00004815 // If the RHS is a unary plus or minus, check to see if they = and + are
4816 // right next to each other. If so, the user may have typo'd "x =+ 4"
4817 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00004818 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00004819 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4820 RHSCheck = ICE->getSubExpr();
4821 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4822 if ((UO->getOpcode() == UnaryOperator::Plus ||
4823 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00004824 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00004825 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00004826 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4827 // And there is a space or other character before the subexpr of the
4828 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00004829 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4830 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00004831 Diag(Loc, diag::warn_not_compound_assign)
4832 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4833 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00004834 }
Chris Lattnerea714382008-08-21 18:04:13 +00004835 }
4836 } else {
4837 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00004838 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00004839 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004840
Chris Lattner326f7572008-11-18 01:30:42 +00004841 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4842 RHS, "assigning"))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004843 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004844
Steve Naroff98cf3e92007-06-06 18:38:38 +00004845 // C99 6.5.16p3: The type of an assignment expression is the type of the
4846 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00004847 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00004848 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4849 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00004850 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00004851 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00004852 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00004853}
4854
Chris Lattner326f7572008-11-18 01:30:42 +00004855// C99 6.5.17
4856QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00004857 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00004858 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00004859
4860 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4861 // incomplete in C++).
4862
Chris Lattner326f7572008-11-18 01:30:42 +00004863 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00004864}
4865
Steve Naroff7a5af782007-07-13 16:58:59 +00004866/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4867/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00004868QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4869 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004870 if (Op->isTypeDependent())
4871 return Context.DependentTy;
4872
Chris Lattner6b0cf142008-11-21 07:05:48 +00004873 QualType ResType = Op->getType();
4874 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00004875
Sebastian Redle10c2c32008-12-20 09:35:34 +00004876 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4877 // Decrement of bool is not allowed.
4878 if (!isInc) {
4879 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4880 return QualType();
4881 }
4882 // Increment of bool sets it to true, but is deprecated.
4883 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4884 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00004885 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00004886 } else if (ResType->isAnyPointerType()) {
4887 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004888
Chris Lattner6b0cf142008-11-21 07:05:48 +00004889 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00004890 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004891 if (getLangOptions().CPlusPlus) {
4892 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4893 << Op->getSourceRange();
4894 return QualType();
4895 }
4896
4897 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00004898 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004899 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004900 if (getLangOptions().CPlusPlus) {
4901 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4902 << Op->getType() << Op->getSourceRange();
4903 return QualType();
4904 }
4905
4906 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004907 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004908 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00004909 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004910 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004911 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00004912 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00004913 // Diagnose bad cases where we step over interface counts.
4914 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4915 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4916 << PointeeTy << Op->getSourceRange();
4917 return QualType();
4918 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00004919 } else if (ResType->isComplexType()) {
4920 // C99 does not support ++/-- on complex types, we allow as an extension.
4921 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004922 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00004923 } else {
4924 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004925 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00004926 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00004927 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004928 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00004929 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00004930 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00004931 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00004932 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004933}
4934
Anders Carlsson806700f2008-02-01 07:15:58 +00004935/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00004936/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00004937/// where the declaration is needed for type checking. We only need to
4938/// handle cases when the expression references a function designator
4939/// or is an lvalue. Here are some examples:
4940/// - &(x) => x
4941/// - &*****f => f for f a function designator.
4942/// - &s.xx => s
4943/// - &s.zz[1].yy -> s, if zz is an array
4944/// - *(x + 1) -> x, if x is an array
4945/// - &"123"[2] -> 0
4946/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004947static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004948 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00004949 case Stmt::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00004950 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004951 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00004952 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00004953 // If this is an arrow operator, the address is an offset from
4954 // the base's value, so the object the base refers to is
4955 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004956 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00004957 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00004958 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004959 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00004960 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00004961 // FIXME: This code shouldn't be necessary! We should catch the implicit
4962 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00004963 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4964 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4965 if (ICE->getSubExpr()->getType()->isArrayType())
4966 return getPrimaryDecl(ICE->getSubExpr());
4967 }
4968 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00004969 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00004970 case Stmt::UnaryOperatorClass: {
4971 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004972
Daniel Dunbarb692ef42008-08-04 20:02:37 +00004973 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00004974 case UnaryOperator::Real:
4975 case UnaryOperator::Imag:
4976 case UnaryOperator::Extension:
4977 return getPrimaryDecl(UO->getSubExpr());
4978 default:
4979 return 0;
4980 }
4981 }
Steve Naroff47500512007-04-19 23:00:49 +00004982 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004983 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00004984 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00004985 // If the result of an implicit cast is an l-value, we care about
4986 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004987 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00004988 default:
4989 return 0;
4990 }
4991}
4992
4993/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00004994/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00004995/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004996/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004997/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004998/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00004999/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005000QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005001 // Make sure to ignore parentheses in subsequent checks
5002 op = op->IgnoreParens();
5003
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005004 if (op->isTypeDependent())
5005 return Context.DependentTy;
5006
Steve Naroff826e91a2008-01-13 17:10:08 +00005007 if (getLangOptions().C99) {
5008 // Implement C99-only parts of addressof rules.
5009 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5010 if (uOp->getOpcode() == UnaryOperator::Deref)
5011 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5012 // (assuming the deref expression is valid).
5013 return uOp->getSubExpr()->getType();
5014 }
5015 // Technically, there should be a check for array subscript
5016 // expressions here, but the result of one is always an lvalue anyway.
5017 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005018 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005019 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005020
Eli Friedmance7f9002009-05-16 23:27:50 +00005021 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5022 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005023 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005024 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005025 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005026 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5027 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005028 return QualType();
5029 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005030 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005031 // The operand cannot be a bit-field
5032 Diag(OpLoc, diag::err_typecheck_address_of)
5033 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005034 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005035 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5036 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005037 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005038 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005039 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005040 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005041 } else if (isa<ObjCPropertyRefExpr>(op)) {
5042 // cannot take address of a property expression.
5043 Diag(OpLoc, diag::err_typecheck_address_of)
5044 << "property expression" << op->getSourceRange();
5045 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005046 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005047 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005048 // with the register storage-class specifier.
5049 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005050 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005051 Diag(OpLoc, diag::err_typecheck_address_of)
5052 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005053 return QualType();
5054 }
Douglas Gregor9b146582009-07-08 20:55:45 +00005055 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5056 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005057 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005058 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005059 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005060 // Could be a pointer to member, though, if there is an explicit
5061 // scope qualifier for the class.
5062 if (isa<QualifiedDeclRefExpr>(op)) {
5063 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005064 if (Ctx && Ctx->isRecord()) {
5065 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005066 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005067 diag::err_cannot_form_pointer_to_member_of_reference_type)
5068 << FD->getDeclName() << FD->getType();
5069 return QualType();
5070 }
Mike Stump11289f42009-09-09 15:08:12 +00005071
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005072 return Context.getMemberPointerType(op->getType(),
5073 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005074 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005075 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005076 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005077 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005078 // As above.
Anders Carlsson5b535762009-05-16 21:43:42 +00005079 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5080 return Context.getMemberPointerType(op->getType(),
5081 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5082 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005083 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005084 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005085
Eli Friedmance7f9002009-05-16 23:27:50 +00005086 if (lval == Expr::LV_IncompleteVoidType) {
5087 // Taking the address of a void variable is technically illegal, but we
5088 // allow it in cases which are otherwise valid.
5089 // Example: "extern void x; void* y = &x;".
5090 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5091 }
5092
Steve Naroff47500512007-04-19 23:00:49 +00005093 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005094 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005095}
5096
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005097QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005098 if (Op->isTypeDependent())
5099 return Context.DependentTy;
5100
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005101 UsualUnaryConversions(Op);
5102 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005103
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005104 // Note that per both C89 and C99, this is always legal, even if ptype is an
5105 // incomplete type or void. It would be possible to warn about dereferencing
5106 // a void pointer, but it's completely well-defined, and such a warning is
5107 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005108 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005109 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005110
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005111 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5112 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005113
Chris Lattner29e812b2008-11-20 06:06:08 +00005114 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005115 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005116 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005117}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005118
5119static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5120 tok::TokenKind Kind) {
5121 BinaryOperator::Opcode Opc;
5122 switch (Kind) {
5123 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005124 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5125 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005126 case tok::star: Opc = BinaryOperator::Mul; break;
5127 case tok::slash: Opc = BinaryOperator::Div; break;
5128 case tok::percent: Opc = BinaryOperator::Rem; break;
5129 case tok::plus: Opc = BinaryOperator::Add; break;
5130 case tok::minus: Opc = BinaryOperator::Sub; break;
5131 case tok::lessless: Opc = BinaryOperator::Shl; break;
5132 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5133 case tok::lessequal: Opc = BinaryOperator::LE; break;
5134 case tok::less: Opc = BinaryOperator::LT; break;
5135 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5136 case tok::greater: Opc = BinaryOperator::GT; break;
5137 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5138 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5139 case tok::amp: Opc = BinaryOperator::And; break;
5140 case tok::caret: Opc = BinaryOperator::Xor; break;
5141 case tok::pipe: Opc = BinaryOperator::Or; break;
5142 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5143 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5144 case tok::equal: Opc = BinaryOperator::Assign; break;
5145 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5146 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5147 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5148 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5149 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5150 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5151 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5152 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5153 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5154 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5155 case tok::comma: Opc = BinaryOperator::Comma; break;
5156 }
5157 return Opc;
5158}
5159
Steve Naroff35d85152007-05-07 00:24:15 +00005160static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5161 tok::TokenKind Kind) {
5162 UnaryOperator::Opcode Opc;
5163 switch (Kind) {
5164 default: assert(0 && "Unknown unary op!");
5165 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5166 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5167 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5168 case tok::star: Opc = UnaryOperator::Deref; break;
5169 case tok::plus: Opc = UnaryOperator::Plus; break;
5170 case tok::minus: Opc = UnaryOperator::Minus; break;
5171 case tok::tilde: Opc = UnaryOperator::Not; break;
5172 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005173 case tok::kw___real: Opc = UnaryOperator::Real; break;
5174 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00005175 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005176 }
5177 return Opc;
5178}
5179
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005180/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5181/// operator @p Opc at location @c TokLoc. This routine only supports
5182/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005183Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5184 unsigned Op,
5185 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005186 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005187 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005188 // The following two variables are used for compound assignment operators
5189 QualType CompLHSTy; // Type of LHS after promotions for computation
5190 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005191
5192 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005193 case BinaryOperator::Assign:
5194 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5195 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005196 case BinaryOperator::PtrMemD:
5197 case BinaryOperator::PtrMemI:
5198 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5199 Opc == BinaryOperator::PtrMemI);
5200 break;
5201 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005202 case BinaryOperator::Div:
5203 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5204 break;
5205 case BinaryOperator::Rem:
5206 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5207 break;
5208 case BinaryOperator::Add:
5209 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5210 break;
5211 case BinaryOperator::Sub:
5212 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5213 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005214 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005215 case BinaryOperator::Shr:
5216 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5217 break;
5218 case BinaryOperator::LE:
5219 case BinaryOperator::LT:
5220 case BinaryOperator::GE:
5221 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005222 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005223 break;
5224 case BinaryOperator::EQ:
5225 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005226 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005227 break;
5228 case BinaryOperator::And:
5229 case BinaryOperator::Xor:
5230 case BinaryOperator::Or:
5231 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5232 break;
5233 case BinaryOperator::LAnd:
5234 case BinaryOperator::LOr:
5235 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5236 break;
5237 case BinaryOperator::MulAssign:
5238 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005239 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5240 CompLHSTy = CompResultTy;
5241 if (!CompResultTy.isNull())
5242 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005243 break;
5244 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005245 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5246 CompLHSTy = CompResultTy;
5247 if (!CompResultTy.isNull())
5248 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005249 break;
5250 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005251 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5252 if (!CompResultTy.isNull())
5253 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005254 break;
5255 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005256 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5257 if (!CompResultTy.isNull())
5258 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005259 break;
5260 case BinaryOperator::ShlAssign:
5261 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005262 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5263 CompLHSTy = CompResultTy;
5264 if (!CompResultTy.isNull())
5265 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005266 break;
5267 case BinaryOperator::AndAssign:
5268 case BinaryOperator::XorAssign:
5269 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005270 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5271 CompLHSTy = CompResultTy;
5272 if (!CompResultTy.isNull())
5273 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005274 break;
5275 case BinaryOperator::Comma:
5276 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5277 break;
5278 }
5279 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005280 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005281 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00005282 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5283 else
5284 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005285 CompLHSTy, CompResultTy,
5286 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005287}
5288
Steve Naroff218bc2b2007-05-04 21:54:46 +00005289// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005290Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5291 tok::TokenKind Kind,
5292 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00005293 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00005294 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00005295
Steve Naroff83895f72007-09-16 03:34:24 +00005296 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5297 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00005298
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005299 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00005300 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005301 rhs->getType()->isOverloadableType())) {
5302 // Find all of the overloaded operators visible from this
5303 // point. We perform both an operator-name lookup from the local
5304 // scope and an argument-dependent lookup based on the types of
5305 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005306 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005307 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5308 if (OverOp != OO_None) {
5309 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5310 Functions);
5311 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00005312 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005313 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5314 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00005315 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005316
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005317 // Build the (potentially-overloaded, potentially-dependent)
5318 // binary operation.
5319 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00005320 }
5321
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005322 // Build a built-in binary operation.
5323 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005324}
5325
Douglas Gregor084d8552009-03-13 23:49:33 +00005326Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005327 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00005328 ExprArg InputArg) {
5329 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00005330
Mike Stump87c57ac2009-05-16 07:39:55 +00005331 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00005332 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00005333 QualType resultType;
5334 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005335 case UnaryOperator::OffsetOf:
5336 assert(false && "Invalid unary operator");
5337 break;
5338
Steve Naroff35d85152007-05-07 00:24:15 +00005339 case UnaryOperator::PreInc:
5340 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00005341 case UnaryOperator::PostInc:
5342 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00005343 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00005344 Opc == UnaryOperator::PreInc ||
5345 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00005346 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005347 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00005348 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005349 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005350 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00005351 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00005352 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005353 break;
5354 case UnaryOperator::Plus:
5355 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00005356 UsualUnaryConversions(Input);
5357 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005358 if (resultType->isDependentType())
5359 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005360 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5361 break;
5362 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5363 resultType->isEnumeralType())
5364 break;
5365 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5366 Opc == UnaryOperator::Plus &&
5367 resultType->isPointerType())
5368 break;
5369
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005370 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5371 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005372 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00005373 UsualUnaryConversions(Input);
5374 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005375 if (resultType->isDependentType())
5376 break;
Chris Lattner0d707612008-07-25 23:52:49 +00005377 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5378 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5379 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00005380 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005381 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00005382 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005383 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5384 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005385 break;
5386 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00005387 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00005388 DefaultFunctionArrayConversion(Input);
5389 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005390 if (resultType->isDependentType())
5391 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005392 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005393 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5394 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00005395 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005396 // In C++, it's bool. C++ 5.3.1p8
5397 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00005398 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00005399 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00005400 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00005401 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00005402 break;
Chris Lattner86554282007-06-08 22:32:33 +00005403 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00005404 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00005405 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005406 }
5407 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005408 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00005409
5410 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00005411 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00005412}
Chris Lattnereefa10e2007-05-28 06:56:27 +00005413
Douglas Gregor084d8552009-03-13 23:49:33 +00005414// Unary Operators. 'Tok' is the token for the operator.
5415Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5416 tok::TokenKind Op, ExprArg input) {
5417 Expr *Input = (Expr*)input.get();
5418 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5419
5420 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5421 // Find all of the overloaded operators visible from this
5422 // point. We perform both an operator-name lookup from the local
5423 // scope and an argument-dependent lookup based on the types of
5424 // the arguments.
5425 FunctionSet Functions;
5426 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5427 if (OverOp != OO_None) {
5428 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5429 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00005430 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00005431 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5432 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5433 }
5434
5435 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5436 }
5437
5438 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5439}
5440
Steve Naroff66356bd2007-09-16 14:56:35 +00005441/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005442Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5443 SourceLocation LabLoc,
5444 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00005445 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00005446 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00005447
Daniel Dunbar88402ce2008-08-04 16:51:22 +00005448 // If we haven't seen this label yet, create a forward reference. It
5449 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00005450 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00005451 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005452
Chris Lattnereefa10e2007-05-28 06:56:27 +00005453 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005454 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5455 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00005456}
5457
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005458Sema::OwningExprResult
5459Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5460 SourceLocation RPLoc) { // "({..})"
5461 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00005462 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5463 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5464
Eli Friedman52cc0162009-01-24 23:09:00 +00005465 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00005466 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005467 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00005468
Chris Lattner366727f2007-07-24 16:58:17 +00005469 // FIXME: there are a variety of strange constraints to enforce here, for
5470 // example, it is not possible to goto into a stmt expression apparently.
5471 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005472
Chris Lattner366727f2007-07-24 16:58:17 +00005473 // If there are sub stmts in the compound stmt, take the type of the last one
5474 // as the type of the stmtexpr.
5475 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005476
Chris Lattner944d3062008-07-26 19:51:01 +00005477 if (!Compound->body_empty()) {
5478 Stmt *LastStmt = Compound->body_back();
5479 // If LastStmt is a label, skip down through into the body.
5480 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5481 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005482
Chris Lattner944d3062008-07-26 19:51:01 +00005483 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00005484 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00005485 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005486
Eli Friedmanba961a92009-03-23 00:24:07 +00005487 // FIXME: Check that expression type is complete/non-abstract; statement
5488 // expressions are not lvalues.
5489
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005490 substmt.release();
5491 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00005492}
Steve Naroff78864672007-08-01 22:05:33 +00005493
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005494Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5495 SourceLocation BuiltinLoc,
5496 SourceLocation TypeLoc,
5497 TypeTy *argty,
5498 OffsetOfComponent *CompPtr,
5499 unsigned NumComponents,
5500 SourceLocation RPLoc) {
5501 // FIXME: This function leaks all expressions in the offset components on
5502 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005503 // FIXME: Preserve type source info.
5504 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00005505 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005506
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005507 bool Dependent = ArgTy->isDependentType();
5508
Chris Lattnerf17bd422007-08-30 17:45:32 +00005509 // We must have at least one component that refers to the type, and the first
5510 // one is known to be a field designator. Verify that the ArgTy represents
5511 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005512 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005513 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005514
Eli Friedmanba961a92009-03-23 00:24:07 +00005515 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5516 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00005517
Eli Friedman988a16b2009-02-27 06:44:11 +00005518 // Otherwise, create a null pointer as the base, and iteratively process
5519 // the offsetof designators.
5520 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5521 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005522 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00005523 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00005524
Chris Lattner78502cf2007-08-31 21:49:13 +00005525 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5526 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00005527 // FIXME: This diagnostic isn't actually visible because the location is in
5528 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00005529 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00005530 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5531 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005532
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005533 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00005534 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00005535
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005536 // FIXME: Dependent case loses a lot of information here. And probably
5537 // leaks like a sieve.
5538 for (unsigned i = 0; i != NumComponents; ++i) {
5539 const OffsetOfComponent &OC = CompPtr[i];
5540 if (OC.isBrackets) {
5541 // Offset of an array sub-field. TODO: Should we allow vector elements?
5542 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5543 if (!AT) {
5544 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005545 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5546 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005547 }
5548
5549 // FIXME: C++: Verify that operator[] isn't overloaded.
5550
Eli Friedman988a16b2009-02-27 06:44:11 +00005551 // Promote the array so it looks more like a normal array subscript
5552 // expression.
5553 DefaultFunctionArrayConversion(Res);
5554
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005555 // C99 6.5.2.1p1
5556 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005557 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005558 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005559 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00005560 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005561 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005562
5563 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5564 OC.LocEnd);
5565 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00005566 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005567
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005568 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005569 if (!RC) {
5570 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005571 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5572 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005573 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00005574
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005575 // Get the decl corresponding to this.
5576 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005577 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005578 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlsson8b98d022009-05-02 17:45:47 +00005579 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5580 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5581 << Res->getType());
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005582 DidWarnAboutNonPOD = true;
5583 }
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005584 }
Mike Stump11289f42009-09-09 15:08:12 +00005585
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005586 FieldDecl *MemberDecl
5587 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5588 LookupMemberName)
5589 .getAsDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005590 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005591 if (!MemberDecl)
Anders Carlsson896c2302009-08-30 00:54:35 +00005592 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005593 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00005594
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005595 // FIXME: C++: Verify that MemberDecl isn't a static field.
5596 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00005597 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00005598 Res = BuildAnonymousStructUnionMemberReference(
5599 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00005600 } else {
5601 // MemberDecl->getType() doesn't get the right qualifiers, but it
5602 // doesn't matter here.
5603 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5604 MemberDecl->getType().getNonReferenceType());
5605 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005606 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00005607 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005608
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005609 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5610 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00005611}
5612
5613
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005614Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5615 TypeTy *arg1,TypeTy *arg2,
5616 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005617 // FIXME: Preserve type source info.
5618 QualType argT1 = GetTypeFromParser(arg1);
5619 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005620
Steve Naroff78864672007-08-01 22:05:33 +00005621 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005622
Douglas Gregorf907cbf2009-05-19 22:28:02 +00005623 if (getLangOptions().CPlusPlus) {
5624 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5625 << SourceRange(BuiltinLoc, RPLoc);
5626 return ExprError();
5627 }
5628
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005629 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5630 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00005631}
5632
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005633Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5634 ExprArg cond,
5635 ExprArg expr1, ExprArg expr2,
5636 SourceLocation RPLoc) {
5637 Expr *CondExpr = static_cast<Expr*>(cond.get());
5638 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5639 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005640
Steve Naroff9efdabc2007-08-03 21:21:27 +00005641 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5642
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005643 QualType resType;
Douglas Gregor0df91122009-05-19 22:43:30 +00005644 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005645 resType = Context.DependentTy;
5646 } else {
5647 // The conditional expression is required to be a constant expression.
5648 llvm::APSInt condEval(32);
5649 SourceLocation ExpLoc;
5650 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005651 return ExprError(Diag(ExpLoc,
5652 diag::err_typecheck_choose_expr_requires_constant)
5653 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00005654
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005655 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5656 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5657 }
5658
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005659 cond.release(); expr1.release(); expr2.release();
5660 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5661 resType, RPLoc));
Steve Naroff9efdabc2007-08-03 21:21:27 +00005662}
5663
Steve Naroffc540d662008-09-03 18:15:37 +00005664//===----------------------------------------------------------------------===//
5665// Clang Extensions.
5666//===----------------------------------------------------------------------===//
5667
5668/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005669void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00005670 // Analyze block parameters.
5671 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005672
Steve Naroffc540d662008-09-03 18:15:37 +00005673 // Add BSI to CurBlock.
5674 BSI->PrevBlockInfo = CurBlock;
5675 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005676
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005677 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00005678 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00005679 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00005680 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00005681 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5682 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005683
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005684 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00005685 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005686}
5687
Mike Stump82f071f2009-02-04 22:31:32 +00005688void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00005689 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00005690
5691 if (ParamInfo.getNumTypeObjects() == 0
5692 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00005693 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00005694 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5695
Mike Stumpd456c482009-04-28 01:10:27 +00005696 if (T->isArrayType()) {
5697 Diag(ParamInfo.getSourceRange().getBegin(),
5698 diag::err_block_returns_array);
5699 return;
5700 }
5701
Mike Stump82f071f2009-02-04 22:31:32 +00005702 // The parameter list is optional, if there was none, assume ().
5703 if (!T->isFunctionType())
5704 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5705
5706 CurBlock->hasPrototype = true;
5707 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005708 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005709 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00005710 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00005711 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005712 // FIXME: remove the attribute.
5713 }
Chris Lattner6de05082009-04-11 19:27:54 +00005714 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00005715
Chris Lattner6de05082009-04-11 19:27:54 +00005716 // Do not allow returning a objc interface by-value.
5717 if (RetTy->isObjCInterfaceType()) {
5718 Diag(ParamInfo.getSourceRange().getBegin(),
5719 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5720 return;
5721 }
Mike Stump82f071f2009-02-04 22:31:32 +00005722 return;
5723 }
5724
Steve Naroffc540d662008-09-03 18:15:37 +00005725 // Analyze arguments to block.
5726 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5727 "Not a function declarator!");
5728 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005729
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005730 CurBlock->hasPrototype = FTI.hasPrototype;
5731 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005732
Steve Naroffc540d662008-09-03 18:15:37 +00005733 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5734 // no arguments, not a function that takes a single void argument.
5735 if (FTI.hasPrototype &&
5736 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00005737 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5738 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00005739 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005740 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00005741 } else if (FTI.hasPrototype) {
5742 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00005743 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005744 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00005745 }
Jay Foad7d0479f2009-05-21 09:52:38 +00005746 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00005747 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00005748 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00005749 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005750 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5751 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5752 // If this has an identifier, add it to the scope stack.
5753 if ((*AI)->getIdentifier())
5754 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00005755
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005756 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00005757 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005758 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00005759 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00005760 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005761 // FIXME: remove the attribute.
5762 }
Mike Stump11289f42009-09-09 15:08:12 +00005763
Chris Lattner6de05082009-04-11 19:27:54 +00005764 // Analyze the return type.
5765 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5766 QualType RetTy = T->getAsFunctionType()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00005767
Chris Lattner6de05082009-04-11 19:27:54 +00005768 // Do not allow returning a objc interface by-value.
5769 if (RetTy->isObjCInterfaceType()) {
5770 Diag(ParamInfo.getSourceRange().getBegin(),
5771 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5772 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005773 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00005774}
5775
5776/// ActOnBlockError - If there is an error parsing a block, this callback
5777/// is invoked to pop the information about the block from the action impl.
5778void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5779 // Ensure that CurBlock is deleted.
5780 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005781
Chris Lattner45542ea2009-04-19 05:28:12 +00005782 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5783
Steve Naroffc540d662008-09-03 18:15:37 +00005784 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00005785 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00005786 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00005787 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00005788}
5789
5790/// ActOnBlockStmtExpr - This is called when the body of a block statement
5791/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005792Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5793 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00005794 // If blocks are disabled, emit an error.
5795 if (!LangOpts.Blocks)
5796 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00005797
Steve Naroffc540d662008-09-03 18:15:37 +00005798 // Ensure that CurBlock is deleted.
5799 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00005800
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005801 PopDeclContext();
5802
Steve Naroffc540d662008-09-03 18:15:37 +00005803 // Pop off CurBlock, handle nested blocks.
5804 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005805
Steve Naroffc540d662008-09-03 18:15:37 +00005806 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005807 if (!BSI->ReturnType.isNull())
5808 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005809
Steve Naroffc540d662008-09-03 18:15:37 +00005810 llvm::SmallVector<QualType, 8> ArgTypes;
5811 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5812 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005813
Mike Stump3bf1ab42009-07-28 22:04:01 +00005814 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00005815 QualType BlockTy;
5816 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00005817 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5818 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00005819 else
Jay Foad7d0479f2009-05-21 09:52:38 +00005820 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00005821 BSI->isVariadic, 0, false, false, 0, 0,
5822 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005823
Eli Friedmanba961a92009-03-23 00:24:07 +00005824 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005825 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00005826 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005827
Chris Lattner45542ea2009-04-19 05:28:12 +00005828 // If needed, diagnose invalid gotos and switches in the block.
5829 if (CurFunctionNeedsScopeChecking)
5830 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5831 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00005832
Anders Carlssonb781bcd2009-05-01 19:49:17 +00005833 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00005834 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005835 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5836 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00005837}
5838
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005839Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5840 ExprArg expr, TypeTy *type,
5841 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005842 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00005843 Expr *E = static_cast<Expr*>(expr.get());
5844 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00005845
Anders Carlsson7e13ab82007-10-15 20:28:48 +00005846 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00005847
5848 // Get the va_list type
5849 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00005850 if (VaListType->isArrayType()) {
5851 // Deal with implicit array decay; for example, on x86-64,
5852 // va_list is an array, but it's supposed to decay to
5853 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00005854 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00005855 // Make sure the input expression also decays appropriately.
5856 UsualUnaryConversions(E);
5857 } else {
5858 // Otherwise, the va_list argument must be an l-value because
5859 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00005860 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00005861 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00005862 return ExprError();
5863 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00005864
Douglas Gregorad3150c2009-05-19 23:10:31 +00005865 if (!E->isTypeDependent() &&
5866 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005867 return ExprError(Diag(E->getLocStart(),
5868 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00005869 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00005870 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005871
Eli Friedmanba961a92009-03-23 00:24:07 +00005872 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00005873 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005874
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005875 expr.release();
5876 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5877 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00005878}
5879
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005880Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00005881 // The type of __null will be int or long, depending on the size of
5882 // pointers on the target.
5883 QualType Ty;
5884 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5885 Ty = Context.IntTy;
5886 else
5887 Ty = Context.LongTy;
5888
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005889 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00005890}
5891
Chris Lattner9bad62c2008-01-04 18:04:52 +00005892bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5893 SourceLocation Loc,
5894 QualType DstType, QualType SrcType,
5895 Expr *SrcExpr, const char *Flavor) {
5896 // Decode the result (notice that AST's are still created for extensions).
5897 bool isInvalid = false;
5898 unsigned DiagKind;
5899 switch (ConvTy) {
5900 default: assert(0 && "Unknown conversion type");
5901 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005902 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00005903 DiagKind = diag::ext_typecheck_convert_pointer_int;
5904 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005905 case IntToPointer:
5906 DiagKind = diag::ext_typecheck_convert_int_pointer;
5907 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005908 case IncompatiblePointer:
5909 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5910 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00005911 case IncompatiblePointerSign:
5912 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5913 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005914 case FunctionVoidPointer:
5915 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5916 break;
5917 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00005918 // If the qualifiers lost were because we were applying the
5919 // (deprecated) C++ conversion from a string literal to a char*
5920 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5921 // Ideally, this check would be performed in
5922 // CheckPointerTypesForAssignment. However, that would require a
5923 // bit of refactoring (so that the second argument is an
5924 // expression, rather than a type), which should be done as part
5925 // of a larger effort to fix CheckPointerTypesForAssignment for
5926 // C++ semantics.
5927 if (getLangOptions().CPlusPlus &&
5928 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5929 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005930 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5931 break;
Steve Naroff081c7422008-09-04 15:10:53 +00005932 case IntToBlockPointer:
5933 DiagKind = diag::err_int_to_block_pointer;
5934 break;
5935 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00005936 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00005937 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00005938 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00005939 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00005940 // it can give a more specific diagnostic.
5941 DiagKind = diag::warn_incompatible_qualified_id;
5942 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005943 case IncompatibleVectors:
5944 DiagKind = diag::warn_incompatible_vectors;
5945 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005946 case Incompatible:
5947 DiagKind = diag::err_typecheck_convert_incompatible;
5948 isInvalid = true;
5949 break;
5950 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005951
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005952 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5953 << SrcExpr->getSourceRange();
Chris Lattner9bad62c2008-01-04 18:04:52 +00005954 return isInvalid;
5955}
Anders Carlssone54e8a12008-11-30 19:50:32 +00005956
Chris Lattnerc71d08b2009-04-25 21:59:05 +00005957bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00005958 llvm::APSInt ICEResult;
5959 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5960 if (Result)
5961 *Result = ICEResult;
5962 return false;
5963 }
5964
Anders Carlssone54e8a12008-11-30 19:50:32 +00005965 Expr::EvalResult EvalResult;
5966
Mike Stump4e1f26a2009-02-19 03:04:26 +00005967 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00005968 EvalResult.HasSideEffects) {
5969 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5970
5971 if (EvalResult.Diag) {
5972 // We only show the note if it's not the usual "invalid subexpression"
5973 // or if it's actually in a subexpression.
5974 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5975 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5976 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5977 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005978
Anders Carlssone54e8a12008-11-30 19:50:32 +00005979 return true;
5980 }
5981
Eli Friedmanbb967cc2009-04-25 22:26:58 +00005982 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5983 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00005984
Eli Friedmanbb967cc2009-04-25 22:26:58 +00005985 if (EvalResult.Diag &&
5986 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5987 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005988
Anders Carlssone54e8a12008-11-30 19:50:32 +00005989 if (Result)
5990 *Result = EvalResult.Val.getInt();
5991 return false;
5992}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005993
Mike Stump11289f42009-09-09 15:08:12 +00005994Sema::ExpressionEvaluationContext
5995Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00005996 // Introduce a new set of potentially referenced declarations to the stack.
5997 if (NewContext == PotentiallyPotentiallyEvaluated)
5998 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump11289f42009-09-09 15:08:12 +00005999
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006000 std::swap(ExprEvalContext, NewContext);
6001 return NewContext;
6002}
6003
Mike Stump11289f42009-09-09 15:08:12 +00006004void
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006005Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6006 ExpressionEvaluationContext NewContext) {
6007 ExprEvalContext = NewContext;
6008
6009 if (OldContext == PotentiallyPotentiallyEvaluated) {
6010 // Mark any remaining declarations in the current position of the stack
6011 // as "referenced". If they were not meant to be referenced, semantic
6012 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6013 PotentiallyReferencedDecls RemainingDecls;
6014 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6015 PotentiallyReferencedDeclStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00006016
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006017 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6018 IEnd = RemainingDecls.end();
6019 I != IEnd; ++I)
6020 MarkDeclarationReferenced(I->first, I->second);
6021 }
6022}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006023
6024/// \brief Note that the given declaration was referenced in the source code.
6025///
6026/// This routine should be invoke whenever a given declaration is referenced
6027/// in the source code, and where that reference occurred. If this declaration
6028/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6029/// C99 6.9p3), then the declaration will be marked as used.
6030///
6031/// \param Loc the location where the declaration was referenced.
6032///
6033/// \param D the declaration that has been referenced by the source code.
6034void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6035 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00006036
Douglas Gregor77b50e12009-06-22 23:06:13 +00006037 if (D->isUsed())
6038 return;
Mike Stump11289f42009-09-09 15:08:12 +00006039
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006040 // Mark a parameter declaration "used", regardless of whether we're in a
6041 // template or not.
6042 if (isa<ParmVarDecl>(D))
6043 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00006044
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006045 // Do not mark anything as "used" within a dependent context; wait for
6046 // an instantiation.
6047 if (CurContext->isDependentContext())
6048 return;
Mike Stump11289f42009-09-09 15:08:12 +00006049
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006050 switch (ExprEvalContext) {
6051 case Unevaluated:
6052 // We are in an expression that is not potentially evaluated; do nothing.
6053 return;
Mike Stump11289f42009-09-09 15:08:12 +00006054
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006055 case PotentiallyEvaluated:
6056 // We are in a potentially-evaluated expression, so this declaration is
6057 // "used"; handle this below.
6058 break;
Mike Stump11289f42009-09-09 15:08:12 +00006059
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006060 case PotentiallyPotentiallyEvaluated:
6061 // We are in an expression that may be potentially evaluated; queue this
6062 // declaration reference until we know whether the expression is
6063 // potentially evaluated.
6064 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6065 return;
6066 }
Mike Stump11289f42009-09-09 15:08:12 +00006067
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006068 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00006069 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006070 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006071 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6072 if (!Constructor->isUsed())
6073 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00006074 } else if (Constructor->isImplicit() &&
Mike Stump12b8ce12009-08-04 21:02:39 +00006075 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006076 if (!Constructor->isUsed())
6077 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6078 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006079 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6080 if (Destructor->isImplicit() && !Destructor->isUsed())
6081 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00006082
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006083 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6084 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6085 MethodDecl->getOverloadedOperator() == OO_Equal) {
6086 if (!MethodDecl->isUsed())
6087 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6088 }
6089 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00006090 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00006091 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00006092 // class templates.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00006093 if (!Function->getBody()) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00006094 // FIXME: distinguish between implicit instantiations of function
6095 // templates and explicit specializations (the latter don't get
6096 // instantiated, naturally).
6097 if (Function->getInstantiatedFromMemberFunction() ||
6098 Function->getPrimaryTemplate())
Douglas Gregordda7ced2009-06-30 17:20:14 +00006099 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor77b50e12009-06-22 23:06:13 +00006100 }
Mike Stump11289f42009-09-09 15:08:12 +00006101
6102
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006103 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006104 Function->setUsed(true);
6105 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00006106 }
Mike Stump11289f42009-09-09 15:08:12 +00006107
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006108 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006109 // Implicit instantiation of static data members of class templates.
6110 // FIXME: distinguish between implicit instantiations (which we need to
6111 // actually instantiate) and explicit specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006112 if (Var->isStaticDataMember() &&
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006113 Var->getInstantiatedFromStaticDataMember())
6114 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
Mike Stump11289f42009-09-09 15:08:12 +00006115
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006116 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006117
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006118 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006119 return;
6120}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006121}
6122