blob: 01fbdbe5fa6c8ef00977475ee3e9cc3c4108611e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000022#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000023#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000026#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000030#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000032#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Designator.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ParsedTemplate.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
37
David Chisnall0f436562009-08-17 16:35:33 +000038
Douglas Gregor48f3bb92009-02-18 21:56:37 +000039/// \brief Determine whether the use of this declaration is valid, and
40/// emit any corresponding diagnostics.
41///
42/// This routine diagnoses various problems with referencing
43/// declarations that can occur when using a declaration. For example,
44/// it might warn if a deprecated or unavailable declaration is being
45/// used, or produce an error (and return true) if a C++0x deleted
46/// function is being used.
47///
Chris Lattner52338262009-10-25 22:31:57 +000048/// If IgnoreDeprecated is set to true, this should not want about deprecated
49/// decls.
50///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000051/// \returns true if there was an error (this declaration cannot be
52/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000053///
John McCall54abf7d2009-11-04 02:18:39 +000054bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000055 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000056 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000057 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000058 }
59
Chris Lattnerffb93682009-10-25 17:21:40 +000060 // See if the decl is unavailable
61 if (D->getAttr<UnavailableAttr>()) {
Ted Kremenek042411c2010-07-21 20:43:11 +000062 Diag(Loc, diag::err_unavailable) << D->getDeclName();
Chris Lattnerffb93682009-10-25 17:21:40 +000063 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
64 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000065
Douglas Gregor48f3bb92009-02-18 21:56:37 +000066 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000067 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000068 if (FD->isDeleted()) {
69 Diag(Loc, diag::err_deleted_function_use);
70 Diag(D->getLocation(), diag::note_unavailable_here) << true;
71 return true;
72 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000073 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000074
Douglas Gregor48f3bb92009-02-18 21:56:37 +000075 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000076}
77
Fariborz Jahanian5b530052009-05-13 18:09:35 +000078/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000079/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000080/// attribute. It warns if call does not have the sentinel argument.
81///
82void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000083 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000084 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000085 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000086 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +000087
88 // FIXME: In C++0x, if any of the arguments are parameter pack
89 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000090 int sentinelPos = attr->getSentinel();
91 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000092
Mike Stump390b4cc2009-05-16 07:39:55 +000093 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
94 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000095 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000096 bool warnNotEnoughArgs = false;
97 int isMethod = 0;
98 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99 // skip over named parameters.
100 ObjCMethodDecl::param_iterator P, E = MD->param_end();
101 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
102 if (nullPos)
103 --nullPos;
104 else
105 ++i;
106 }
107 warnNotEnoughArgs = (P != E || i >= NumArgs);
108 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000109 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = FD->param_end();
112 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000119 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000120 // block or function pointer call.
121 QualType Ty = V->getType();
122 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000123 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000124 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
125 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000126 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
127 unsigned NumArgsInProto = Proto->getNumArgs();
128 unsigned k;
129 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
130 if (nullPos)
131 --nullPos;
132 else
133 ++i;
134 }
135 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
136 }
137 if (Ty->isBlockPointerType())
138 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000139 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000140 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000141 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000142 return;
143
144 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000145 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000146 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000147 return;
148 }
149 int sentinel = i;
150 while (sentinelPos > 0 && i < NumArgs-1) {
151 --sentinelPos;
152 ++i;
153 }
154 if (sentinelPos > 0) {
155 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000156 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000157 return;
158 }
159 while (i < NumArgs-1) {
160 ++i;
161 ++sentinel;
162 }
163 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000164 if (!sentinelExpr) return;
165 if (sentinelExpr->isTypeDependent()) return;
166 if (sentinelExpr->isValueDependent()) return;
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000167 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000168 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
169 Expr::NPC_ValueDependentIsNull))
170 return;
171
172 // Unfortunately, __null has type 'int'.
173 if (isa<GNUNullExpr>(sentinelExpr)) return;
174
175 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
176 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000177}
178
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000179SourceRange Sema::getExprRange(ExprTy *E) const {
180 Expr *Ex = (Expr *)E;
181 return Ex? Ex->getSourceRange() : SourceRange();
182}
183
Chris Lattnere7a2e912008-07-25 21:10:04 +0000184//===----------------------------------------------------------------------===//
185// Standard Promotions and Conversions
186//===----------------------------------------------------------------------===//
187
Chris Lattnere7a2e912008-07-25 21:10:04 +0000188/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
189void Sema::DefaultFunctionArrayConversion(Expr *&E) {
190 QualType Ty = E->getType();
191 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
192
Chris Lattnere7a2e912008-07-25 21:10:04 +0000193 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000194 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000195 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000196 else if (Ty->isArrayType()) {
197 // In C90 mode, arrays only promote to pointers if the array expression is
198 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
199 // type 'array of type' is converted to an expression that has type 'pointer
200 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
201 // that has type 'array of type' ...". The relevant change is "an lvalue"
202 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000203 //
204 // C++ 4.2p1:
205 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
206 // T" can be converted to an rvalue of type "pointer to T".
207 //
208 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
209 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000210 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
211 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000212 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000213}
214
Douglas Gregora873dfc2010-02-03 00:27:59 +0000215void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
216 DefaultFunctionArrayConversion(E);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000217
Douglas Gregora873dfc2010-02-03 00:27:59 +0000218 QualType Ty = E->getType();
219 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
220 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
221 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
222 E->isLvalue(Context) == Expr::LV_Valid) {
223 // C++ [conv.lval]p1:
224 // [...] If T is a non-class type, the type of the rvalue is the
225 // cv-unqualified version of T. Otherwise, the type of the
226 // rvalue is T
227 //
228 // C99 6.3.2.1p2:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000229 // If the lvalue has qualified type, the value has the unqualified
230 // version of the type of the lvalue; otherwise, the value has the
Douglas Gregora873dfc2010-02-03 00:27:59 +0000231 // type of the lvalue.
232 ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
233 }
234}
235
236
Chris Lattnere7a2e912008-07-25 21:10:04 +0000237/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000238/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000239/// sometimes surpressed. For example, the array->pointer conversion doesn't
240/// apply if the array is an argument to the sizeof or address (&) operators.
241/// In these instances, this routine should *not* be called.
242Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
243 QualType Ty = Expr->getType();
244 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Douglas Gregorfc24e442009-05-01 20:41:21 +0000246 // C99 6.3.1.1p2:
247 //
248 // The following may be used in an expression wherever an int or
249 // unsigned int may be used:
250 // - an object or expression with an integer type whose integer
251 // conversion rank is less than or equal to the rank of int
252 // and unsigned int.
253 // - A bit-field of type _Bool, int, signed int, or unsigned int.
254 //
255 // If an int can represent all values of the original type, the
256 // value is converted to an int; otherwise, it is converted to an
257 // unsigned int. These are called the integer promotions. All
258 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000259 QualType PTy = Context.isPromotableBitField(Expr);
260 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000261 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000262 return Expr;
263 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000264 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000265 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000266 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000267 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000268 }
269
Douglas Gregora873dfc2010-02-03 00:27:59 +0000270 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000271 return Expr;
272}
273
Chris Lattner05faf172008-07-25 22:25:12 +0000274/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000275/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000276/// double. All other argument types are converted by UsualUnaryConversions().
277void Sema::DefaultArgumentPromotion(Expr *&Expr) {
278 QualType Ty = Expr->getType();
279 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattner05faf172008-07-25 22:25:12 +0000281 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000282 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
283 return ImpCastExprToType(Expr, Context.DoubleTy,
284 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Chris Lattner05faf172008-07-25 22:25:12 +0000286 UsualUnaryConversions(Expr);
287}
288
Chris Lattner312531a2009-04-12 08:11:20 +0000289/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
290/// will warn if the resulting type is not a POD type, and rejects ObjC
291/// interfaces passed by value. This returns true if the argument type is
292/// completely illegal.
Chris Lattner40378332010-05-16 04:01:30 +0000293bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
294 FunctionDecl *FDecl) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000295 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Chris Lattner40378332010-05-16 04:01:30 +0000297 // __builtin_va_start takes the second argument as a "varargs" argument, but
298 // it doesn't actually do anything with it. It doesn't need to be non-pod
299 // etc.
300 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
301 return false;
302
John McCallc12c5bb2010-05-15 11:32:37 +0000303 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000304 DiagRuntimeBehavior(Expr->getLocStart(),
305 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
306 << Expr->getType() << CT))
307 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000308
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000309 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000310 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000311 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
312 << Expr->getType() << CT))
313 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000314
315 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000316}
317
318
Chris Lattnere7a2e912008-07-25 21:10:04 +0000319/// UsualArithmeticConversions - Performs various conversions that are common to
320/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000321/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000322/// responsible for emitting appropriate error diagnostics.
323/// FIXME: verify the conversion rules for "complex int" are consistent with
324/// GCC.
325QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
326 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000327 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000328 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000329
330 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000331
Mike Stump1eb44332009-09-09 15:08:12 +0000332 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000333 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000334 QualType lhs =
335 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000336 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000337 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000338
339 // If both types are identical, no conversion is needed.
340 if (lhs == rhs)
341 return lhs;
342
343 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
344 // The caller can deal with this (e.g. pointer + int).
345 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
346 return lhs;
347
Douglas Gregor2d833e32009-05-02 00:36:19 +0000348 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000349 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000350 if (!LHSBitfieldPromoteTy.isNull())
351 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000352 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000353 if (!RHSBitfieldPromoteTy.isNull())
354 rhs = RHSBitfieldPromoteTy;
355
Eli Friedmana95d7572009-08-19 07:44:53 +0000356 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000357 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000358 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
359 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000360 return destType;
361}
362
Chris Lattnere7a2e912008-07-25 21:10:04 +0000363//===----------------------------------------------------------------------===//
364// Semantic Analysis for various Expression Types
365//===----------------------------------------------------------------------===//
366
367
Steve Narofff69936d2007-09-16 03:34:24 +0000368/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000369/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
370/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
371/// multiple tokens. However, the common case is that StringToks points to one
372/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000373///
374Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000375Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 assert(NumStringToks && "Must have at least one string!");
377
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000378 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000380 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000381
382 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
383 for (unsigned i = 0; i != NumStringToks; ++i)
384 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000385
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000386 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000387 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000388 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000389
390 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000391 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000392 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000393
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000394 // Get an array type for the string, according to C99 6.4.5. This includes
395 // the nul terminator character as well as the string length for pascal
396 // strings.
397 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000398 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000399 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000402 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000403 Literal.GetStringLength(),
404 Literal.AnyWide, StrTy,
405 &StringTokLocs[0],
406 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000407}
408
Chris Lattner639e2d32008-10-20 05:16:36 +0000409/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
410/// CurBlock to VD should cause it to be snapshotted (as we do for auto
411/// variables defined outside the block) or false if this is not needed (e.g.
412/// for values inside the block or for globals).
413///
Douglas Gregor076ceb02010-03-01 20:44:28 +0000414/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000415/// up-to-date.
416///
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000417static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner639e2d32008-10-20 05:16:36 +0000418 ValueDecl *VD) {
419 // If the value is defined inside the block, we couldn't snapshot it even if
420 // we wanted to.
421 if (CurBlock->TheDecl == VD->getDeclContext())
422 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattner639e2d32008-10-20 05:16:36 +0000424 // If this is an enum constant or function, it is constant, don't snapshot.
425 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
426 return false;
427
428 // If this is a reference to an extern, static, or global variable, no need to
429 // snapshot it.
430 // FIXME: What about 'const' variables in C++?
431 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000432 if (!Var->hasLocalStorage())
433 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000435 // Blocks that have these can't be constant.
436 CurBlock->hasBlockDeclRefExprs = true;
437
438 // If we have nested blocks, the decl may be declared in an outer block (in
439 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
440 // be defined outside all of the current blocks (in which case the blocks do
441 // all get the bit). Walk the nesting chain.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000442 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
443 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000444
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000445 if (!NextBlock)
446 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000447
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000448 // If we found the defining block for the variable, don't mark the block as
449 // having a reference outside it.
450 if (NextBlock->TheDecl == VD->getDeclContext())
451 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000453 // Otherwise, the DeclRef from the inner block causes the outer one to need
454 // a snapshot as well.
455 NextBlock->hasBlockDeclRefExprs = true;
456 }
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Chris Lattner639e2d32008-10-20 05:16:36 +0000458 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000459}
460
Chris Lattner639e2d32008-10-20 05:16:36 +0000461
Anders Carlssone41590d2009-06-24 00:10:43 +0000462Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000463Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000464 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000465 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
466 return BuildDeclRefExpr(D, Ty, NameInfo, SS);
467}
468
469/// BuildDeclRefExpr - Build a DeclRefExpr.
470Sema::OwningExprResult
471Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
472 const DeclarationNameInfo &NameInfo,
473 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000474 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000475 Diag(NameInfo.getLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +0000476 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000477 << D->getDeclName();
478 return ExprError();
479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Anders Carlssone41590d2009-06-24 00:10:43 +0000481 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15dedf02010-04-27 21:10:04 +0000482 if (isa<NonTypeTemplateParmDecl>(VD)) {
483 // Non-type template parameters can be referenced anywhere they are
484 // visible.
Douglas Gregor63982352010-07-13 18:40:04 +0000485 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15dedf02010-04-27 21:10:04 +0000486 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlssone41590d2009-06-24 00:10:43 +0000487 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
488 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000489 Diag(NameInfo.getLoc(),
490 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000491 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000492 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000493 << D->getIdentifier();
494 return ExprError();
495 }
496 }
497 }
498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Abramo Bagnara25777432010-08-11 22:01:17 +0000500 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000502 return Owned(DeclRefExpr::Create(Context,
503 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
504 SS? SS->getRange() : SourceRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000505 D, NameInfo, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000506}
507
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000508/// \brief Given a field that represents a member of an anonymous
509/// struct/union, build the path from that field's context to the
510/// actual member.
511///
512/// Construct the sequence of field member references we'll have to
513/// perform to get to the field in the anonymous union/struct. The
514/// list of members is built from the field outward, so traverse it
515/// backwards to go from an object in the current context to the field
516/// we found.
517///
518/// \returns The variable from which the field access should begin,
519/// for an anonymous struct/union that is not a member of another
520/// class. Otherwise, returns NULL.
521VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
522 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000523 assert(Field->getDeclContext()->isRecord() &&
524 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
525 && "Field must be stored inside an anonymous struct or union");
526
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000527 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000528 VarDecl *BaseObject = 0;
529 DeclContext *Ctx = Field->getDeclContext();
530 do {
531 RecordDecl *Record = cast<RecordDecl>(Ctx);
John McCallbc365c52010-05-21 01:17:40 +0000532 ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000533 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000534 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000535 else {
536 BaseObject = cast<VarDecl>(AnonObject);
537 break;
538 }
539 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000540 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000541 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000542
543 return BaseObject;
544}
545
546Sema::OwningExprResult
547Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
548 FieldDecl *Field,
549 Expr *BaseObjectExpr,
550 SourceLocation OpLoc) {
551 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000552 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000553 AnonFields);
554
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000555 // Build the expression that refers to the base object, from
556 // which we will build a sequence of member references to each
557 // of the anonymous union objects and, eventually, the field we
558 // found via name lookup.
559 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000560 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000561 if (BaseObject) {
562 // BaseObject is an anonymous struct/union variable (and is,
563 // therefore, not part of another non-anonymous record).
Douglas Gregore0762c92009-06-19 23:52:42 +0000564 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000566 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000567 BaseQuals
568 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000569 } else if (BaseObjectExpr) {
570 // The caller provided the base object expression. Determine
571 // whether its a pointer and whether it adds any qualifiers to the
572 // anonymous struct/union fields we're looking into.
573 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000574 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000575 BaseObjectIsPointer = true;
576 ObjectType = ObjectPtr->getPointeeType();
577 }
John McCall0953e762009-09-24 19:53:00 +0000578 BaseQuals
579 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000580 } else {
581 // We've found a member of an anonymous struct/union that is
582 // inside a non-anonymous struct/union, so in a well-formed
583 // program our base object expression is "this".
John McCallea1471e2010-05-20 01:18:31 +0000584 DeclContext *DC = getFunctionLevelDeclContext();
585 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000586 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000587 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000588 = Context.getTagDeclType(
589 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
590 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000591 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000592 == Context.getCanonicalType(ThisType)) ||
593 IsDerivedFrom(ThisType, AnonFieldType)) {
594 // Our base object expression is "this".
Douglas Gregor8aa5f402009-12-24 20:23:34 +0000595 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000596 MD->getThisType(Context),
597 /*isImplicit=*/true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000598 BaseObjectIsPointer = true;
599 }
600 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000601 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
602 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000603 }
John McCall0953e762009-09-24 19:53:00 +0000604 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000605 }
606
Mike Stump1eb44332009-09-09 15:08:12 +0000607 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000608 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
609 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000610 }
611
612 // Build the implicit member references to the field of the
613 // anonymous struct/union.
614 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000615 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000616 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
617 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
618 FI != FIEnd; ++FI) {
619 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000620 Qualifiers MemberTypeQuals =
621 Context.getCanonicalType(MemberType).getQualifiers();
622
623 // CVR attributes from the base are picked up by members,
624 // except that 'mutable' members don't pick up 'const'.
625 if ((*FI)->isMutable())
626 ResultQuals.removeConst();
627
628 // GC attributes are never picked up by members.
629 ResultQuals.removeObjCGCAttr();
630
631 // TR 18037 does not allow fields to be declared with address spaces.
632 assert(!MemberTypeQuals.hasAddressSpace());
633
634 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
635 if (NewQuals != MemberTypeQuals)
636 MemberType = Context.getQualifiedType(MemberType, NewQuals);
637
Douglas Gregore0762c92009-06-19 23:52:42 +0000638 MarkDeclarationReferenced(Loc, *FI);
John McCall6bb80172010-03-30 21:47:33 +0000639 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000640 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000641 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
642 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000643 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000644 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000645 }
646
Sebastian Redlcd965b92009-01-18 18:53:16 +0000647 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000648}
649
Abramo Bagnara25777432010-08-11 22:01:17 +0000650/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +0000651/// possibly a list of template arguments.
652///
653/// If this produces template arguments, it is permitted to call
654/// DecomposeTemplateName.
655///
656/// This actually loses a lot of source location information for
657/// non-standard name kinds; we should consider preserving that in
658/// some way.
659static void DecomposeUnqualifiedId(Sema &SemaRef,
660 const UnqualifiedId &Id,
661 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +0000662 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +0000663 const TemplateArgumentListInfo *&TemplateArgs) {
664 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
665 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
666 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
667
668 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
669 Id.TemplateId->getTemplateArgs(),
670 Id.TemplateId->NumArgs);
671 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
672 TemplateArgsPtr.release();
673
674 TemplateName TName =
675 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
Abramo Bagnara25777432010-08-11 22:01:17 +0000676 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
677 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +0000678 TemplateArgs = &Buffer;
679 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +0000680 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +0000681 TemplateArgs = 0;
682 }
683}
684
John McCall4c72d3e2010-02-08 19:26:07 +0000685/// Determines whether the given record is "fully-formed" at the given
686/// location, i.e. whether a qualified lookup into it is assured of
687/// getting consistent results already.
John McCall129e2df2009-11-30 22:42:35 +0000688static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall4c72d3e2010-02-08 19:26:07 +0000689 if (!Record->hasDefinition())
690 return false;
691
John McCall129e2df2009-11-30 22:42:35 +0000692 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
693 E = Record->bases_end(); I != E; ++I) {
694 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
695 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
696 if (!BaseRT) return false;
697
698 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall4c72d3e2010-02-08 19:26:07 +0000699 if (!BaseRecord->hasDefinition() ||
John McCall129e2df2009-11-30 22:42:35 +0000700 !IsFullyFormedScope(SemaRef, BaseRecord))
701 return false;
702 }
703
704 return true;
705}
706
John McCallaa81e162009-12-01 22:10:20 +0000707/// Determines if the given class is provably not derived from all of
708/// the prospective base classes.
709static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
710 CXXRecordDecl *Record,
711 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000712 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000713 return false;
714
Douglas Gregor952b0172010-02-11 01:04:33 +0000715 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +0000716 if (!RD) return false;
717 Record = cast<CXXRecordDecl>(RD);
718
John McCallaa81e162009-12-01 22:10:20 +0000719 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
720 E = Record->bases_end(); I != E; ++I) {
721 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
722 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
723 if (!BaseRT) return false;
724
725 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000726 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
727 return false;
728 }
729
730 return true;
731}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000732
John McCallaa81e162009-12-01 22:10:20 +0000733enum IMAKind {
734 /// The reference is definitely not an instance member access.
735 IMA_Static,
736
737 /// The reference may be an implicit instance member access.
738 IMA_Mixed,
739
740 /// The reference may be to an instance member, but it is invalid if
741 /// so, because the context is not an instance method.
742 IMA_Mixed_StaticContext,
743
744 /// The reference may be to an instance member, but it is invalid if
745 /// so, because the context is from an unrelated class.
746 IMA_Mixed_Unrelated,
747
748 /// The reference is definitely an implicit instance member access.
749 IMA_Instance,
750
751 /// The reference may be to an unresolved using declaration.
752 IMA_Unresolved,
753
754 /// The reference may be to an unresolved using declaration and the
755 /// context is not an instance method.
756 IMA_Unresolved_StaticContext,
757
758 /// The reference is to a member of an anonymous structure in a
759 /// non-class context.
760 IMA_AnonymousMember,
761
762 /// All possible referrents are instance members and the current
763 /// context is not an instance method.
764 IMA_Error_StaticContext,
765
766 /// All possible referrents are instance members of an unrelated
767 /// class.
768 IMA_Error_Unrelated
769};
770
771/// The given lookup names class member(s) and is not being used for
772/// an address-of-member expression. Classify the type of access
773/// according to whether it's possible that this reference names an
774/// instance member. This is best-effort; it is okay to
775/// conservatively answer "yes", in which case some errors will simply
776/// not be caught until template-instantiation.
777static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
778 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000779 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000780
John McCallea1471e2010-05-20 01:18:31 +0000781 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +0000782 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +0000783 (!isa<CXXMethodDecl>(DC) ||
784 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +0000785
786 if (R.isUnresolvableResult())
787 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
788
789 // Collect all the declaring classes of instance members we find.
790 bool hasNonInstance = false;
791 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
792 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +0000793 NamedDecl *D = *I;
794 if (D->isCXXInstanceMember()) {
John McCallaa81e162009-12-01 22:10:20 +0000795 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
796
797 // If this is a member of an anonymous record, move out to the
798 // innermost non-anonymous struct or union. If there isn't one,
799 // that's a special case.
800 while (R->isAnonymousStructOrUnion()) {
801 R = dyn_cast<CXXRecordDecl>(R->getParent());
802 if (!R) return IMA_AnonymousMember;
803 }
804 Classes.insert(R->getCanonicalDecl());
805 }
806 else
807 hasNonInstance = true;
808 }
809
810 // If we didn't find any instance members, it can't be an implicit
811 // member reference.
812 if (Classes.empty())
813 return IMA_Static;
814
815 // If the current context is not an instance method, it can't be
816 // an implicit member reference.
817 if (isStaticContext)
818 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
819
820 // If we can prove that the current context is unrelated to all the
821 // declaring classes, it can't be an implicit member reference (in
822 // which case it's an error if any of those members are selected).
823 if (IsProvablyNotDerivedFrom(SemaRef,
John McCallea1471e2010-05-20 01:18:31 +0000824 cast<CXXMethodDecl>(DC)->getParent(),
John McCallaa81e162009-12-01 22:10:20 +0000825 Classes))
826 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
827
828 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
829}
830
831/// Diagnose a reference to a field with no object available.
832static void DiagnoseInstanceReference(Sema &SemaRef,
833 const CXXScopeSpec &SS,
834 const LookupResult &R) {
835 SourceLocation Loc = R.getNameLoc();
836 SourceRange Range(Loc);
837 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
838
839 if (R.getAsSingle<FieldDecl>()) {
840 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
841 if (MD->isStatic()) {
842 // "invalid use of member 'x' in static member function"
843 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
844 << Range << R.getLookupName();
845 return;
846 }
847 }
848
849 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
850 << R.getLookupName() << Range;
851 return;
852 }
853
854 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000855}
856
John McCall578b69b2009-12-16 08:11:27 +0000857/// Diagnose an empty lookup.
858///
859/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +0000860bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
861 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +0000862 DeclarationName Name = R.getLookupName();
863
John McCall578b69b2009-12-16 08:11:27 +0000864 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000865 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +0000866 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
867 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000868 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +0000869 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000870 diagnostic_suggest = diag::err_undeclared_use_suggest;
871 }
John McCall578b69b2009-12-16 08:11:27 +0000872
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000873 // If the original lookup was an unqualified lookup, fake an
874 // unqualified lookup. This is useful when (for example) the
875 // original lookup would not have found something because it was a
876 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +0000877 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000878 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +0000879 if (isa<CXXRecordDecl>(DC)) {
880 LookupQualifiedName(R, DC);
881
882 if (!R.empty()) {
883 // Don't give errors about ambiguities in this lookup.
884 R.suppressDiagnostics();
885
886 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
887 bool isInstance = CurMethod &&
888 CurMethod->isInstance() &&
889 DC == CurMethod->getParent();
890
891 // Give a code modification hint to insert 'this->'.
892 // TODO: fixit for inserting 'Base<T>::' in the other cases.
893 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +0000894 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000895 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
896 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +0000897 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +0000898 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +0000899 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +0000900 Diag(R.getNameLoc(), diagnostic) << Name
901 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
902 QualType DepThisType = DepMethod->getThisType(Context);
903 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
904 R.getNameLoc(), DepThisType, false);
905 TemplateArgumentListInfo TList;
906 if (ULE->hasExplicitTemplateArgs())
907 ULE->copyTemplateArgumentsInto(TList);
908 CXXDependentScopeMemberExpr *DepExpr =
909 CXXDependentScopeMemberExpr::Create(
910 Context, DepThis, DepThisType, true, SourceLocation(),
911 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
912 R.getLookupNameInfo(), &TList);
913 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +0000914 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +0000915 // FIXME: we should be able to handle this case too. It is correct
916 // to add this-> here. This is a workaround for PR7947.
917 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +0000918 }
Nick Lewycky03d98c52010-07-06 19:51:49 +0000919 } else {
John McCall578b69b2009-12-16 08:11:27 +0000920 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000921 }
John McCall578b69b2009-12-16 08:11:27 +0000922
923 // Do we really want to note all of these?
924 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
925 Diag((*I)->getLocation(), diag::note_dependent_var_use);
926
927 // Tell the callee to try to recover.
928 return false;
929 }
Douglas Gregore26f0432010-08-09 22:38:14 +0000930
931 R.clear();
John McCall578b69b2009-12-16 08:11:27 +0000932 }
933 }
934
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000935 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +0000936 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +0000937 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000938 if (!R.empty()) {
939 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
940 if (SS.isEmpty())
941 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
942 << FixItHint::CreateReplacement(R.getNameLoc(),
943 R.getLookupName().getAsString());
944 else
945 Diag(R.getNameLoc(), diag::err_no_member_suggest)
946 << Name << computeDeclContext(SS, false) << R.getLookupName()
947 << SS.getRange()
948 << FixItHint::CreateReplacement(R.getNameLoc(),
949 R.getLookupName().getAsString());
950 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
951 Diag(ND->getLocation(), diag::note_previous_decl)
952 << ND->getDeclName();
953
954 // Tell the callee to try to recover.
955 return false;
956 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +0000957
Douglas Gregoraaf87162010-04-14 20:04:41 +0000958 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
959 // FIXME: If we ended up with a typo for a type name or
960 // Objective-C class name, we're in trouble because the parser
961 // is in the wrong place to recover. Suggest the typo
962 // correction, but don't make it a fix-it since we're not going
963 // to recover well anyway.
964 if (SS.isEmpty())
965 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
966 else
967 Diag(R.getNameLoc(), diag::err_no_member_suggest)
968 << Name << computeDeclContext(SS, false) << R.getLookupName()
969 << SS.getRange();
970
971 // Don't try to recover; it won't work.
972 return true;
973 }
974 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +0000975 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +0000976 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +0000977 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +0000978 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000979 else
Douglas Gregord203a162010-01-01 00:15:04 +0000980 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +0000981 << Name << computeDeclContext(SS, false) << Corrected
982 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +0000983 return true;
984 }
Douglas Gregord203a162010-01-01 00:15:04 +0000985 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000986 }
987
988 // Emit a special diagnostic for failed member lookups.
989 // FIXME: computing the declaration context might fail here (?)
990 if (!SS.isEmpty()) {
991 Diag(R.getNameLoc(), diag::err_no_member)
992 << Name << computeDeclContext(SS, false)
993 << SS.getRange();
994 return true;
995 }
996
John McCall578b69b2009-12-16 08:11:27 +0000997 // Give up, we can't recover.
998 Diag(R.getNameLoc(), diagnostic) << Name;
999 return true;
1000}
1001
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001002static ObjCPropertyDecl *OkToSynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001003 IdentifierInfo *II,
1004 SourceLocation NameLoc) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001005 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1006 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1007 if (!IDecl)
1008 return 0;
1009 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1010 if (!ClassImpDecl)
1011 return 0;
1012 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1013 if (!property)
1014 return 0;
1015 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1016 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
1017 return 0;
1018 return property;
1019}
1020
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001021static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001022 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001023 IdentifierInfo *II,
1024 SourceLocation NameLoc) {
1025 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001026 bool LookForIvars;
1027 if (Lookup.empty())
1028 LookForIvars = true;
1029 else if (CurMeth->isClassMethod())
1030 LookForIvars = false;
1031 else
1032 LookForIvars = (Lookup.isSingleResult() &&
1033 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1034 if (!LookForIvars)
1035 return 0;
1036
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001037 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1038 if (!IDecl)
1039 return 0;
1040 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001041 if (!ClassImpDecl)
1042 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001043 bool DynamicImplSeen = false;
1044 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1045 if (!property)
1046 return 0;
1047 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1048 DynamicImplSeen =
1049 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1050 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001051 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1052 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001053 NameLoc,
1054 II, PropType, /*Dinfo=*/0,
1055 ObjCIvarDecl::Protected,
1056 (Expr *)0, true);
1057 ClassImpDecl->addDecl(Ivar);
1058 IDecl->makeDeclVisibleInContext(Ivar, false);
1059 property->setPropertyIvarDecl(Ivar);
1060 return Ivar;
1061 }
1062 return 0;
1063}
1064
John McCallf7a1a742009-11-24 19:00:30 +00001065Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001066 CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001067 UnqualifiedId &Id,
1068 bool HasTrailingLParen,
1069 bool isAddressOfOperand) {
1070 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1071 "cannot be direct & operand and have a trailing lparen");
1072
1073 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001074 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001075
John McCall129e2df2009-11-30 22:42:35 +00001076 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001077
1078 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001079 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001080 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001081 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001082
Abramo Bagnara25777432010-08-11 22:01:17 +00001083 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001084 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001085 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001086
John McCallf7a1a742009-11-24 19:00:30 +00001087 // C++ [temp.dep.expr]p3:
1088 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001089 // -- an identifier that was declared with a dependent type,
1090 // (note: handled after lookup)
1091 // -- a template-id that is dependent,
1092 // (note: handled in BuildTemplateIdExpr)
1093 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001094 // -- a nested-name-specifier that contains a class-name that
1095 // names a dependent type.
1096 // Determine whether this is a member of an unknown specialization;
1097 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001098 bool DependentID = false;
1099 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1100 Name.getCXXNameType()->isDependentType()) {
1101 DependentID = true;
1102 } else if (SS.isSet()) {
1103 DeclContext *DC = computeDeclContext(SS, false);
1104 if (DC) {
1105 if (RequireCompleteDeclContext(SS, DC))
1106 return ExprError();
1107 // FIXME: We should be checking whether DC is the current instantiation.
1108 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1109 DependentID = !IsFullyFormedScope(*this, RD);
1110 } else {
1111 DependentID = true;
1112 }
1113 }
1114
1115 if (DependentID) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001116 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001117 TemplateArgs);
1118 }
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001119 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001120 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001121 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001122 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001123 // Lookup the template name again to correctly establish the context in
1124 // which it was found. This is really unfortunate as we already did the
1125 // lookup to determine that it was a template name in the first place. If
1126 // this becomes a performance hit, we can work harder to preserve those
1127 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001128 bool MemberOfUnknownSpecialization;
1129 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1130 MemberOfUnknownSpecialization);
John McCallf7a1a742009-11-24 19:00:30 +00001131 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001132 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001133 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001134
John McCallf7a1a742009-11-24 19:00:30 +00001135 // If this reference is in an Objective-C method, then we need to do
1136 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001137 if (IvarLookupFollowUp) {
1138 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001139 if (E.isInvalid())
1140 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001141
John McCallf7a1a742009-11-24 19:00:30 +00001142 Expr *Ex = E.takeAs<Expr>();
1143 if (Ex) return Owned(Ex);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001144 // Synthesize ivars lazily
1145 if (getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001146 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc))
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001147 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1148 isAddressOfOperand);
1149 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001150 // for further use, this must be set to false if in class method.
1151 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001152 }
Chris Lattner8a934232008-03-31 00:36:02 +00001153 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001154
John McCallf7a1a742009-11-24 19:00:30 +00001155 if (R.isAmbiguous())
1156 return ExprError();
1157
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001158 // Determine whether this name might be a candidate for
1159 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001160 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001161
John McCallf7a1a742009-11-24 19:00:30 +00001162 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001164 // in C90, extension in C99, forbidden in C++).
1165 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1166 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1167 if (D) R.addDecl(D);
1168 }
1169
1170 // If this name wasn't predeclared and if this is not a function
1171 // call, diagnose the problem.
1172 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001173 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001174 return ExprError();
1175
1176 assert(!R.empty() &&
1177 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001178
1179 // If we found an Objective-C instance variable, let
1180 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001181 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001182 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1183 R.clear();
1184 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1185 assert(E.isInvalid() || E.get());
1186 return move(E);
1187 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 }
1189 }
Mike Stump1eb44332009-09-09 15:08:12 +00001190
John McCallf7a1a742009-11-24 19:00:30 +00001191 // This is guaranteed from this point on.
1192 assert(!R.empty() || ADL);
1193
1194 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001195 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianb1d58e32010-07-29 16:53:53 +00001196 !getLangOptions().ObjCNonFragileABI2 &&
1197 Var->isFileVarDecl()) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001198 ObjCPropertyDecl *Property =
1199 OkToSynthesizeProvisionalIvar(*this, II, NameLoc);
1200 if (Property) {
1201 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1202 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001203 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001204 }
1205 }
John McCallf7a1a742009-11-24 19:00:30 +00001206 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001207 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1208 // C99 DR 316 says that, if a function type comes from a
1209 // function definition (without a prototype), that type is only
1210 // used for checking compatibility. Therefore, when referencing
1211 // the function, we pretend that we don't have the full function
1212 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001213 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001214 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001215
Douglas Gregor751f9a42009-06-30 15:47:41 +00001216 QualType T = Func->getType();
1217 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001218 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedman9a0fcfe2010-05-17 02:50:18 +00001219 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1220 Proto->getExtInfo());
John McCallf7a1a742009-11-24 19:00:30 +00001221 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001222 }
1223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
John McCallaa81e162009-12-01 22:10:20 +00001225 // Check whether this might be a C++ implicit instance member access.
1226 // C++ [expr.prim.general]p6:
1227 // Within the definition of a non-static member function, an
1228 // identifier that names a non-static member is transformed to a
1229 // class member access expression.
1230 // But note that &SomeClass::foo is grammatically distinct, even
1231 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001232 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001233 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001234 if (!isAbstractMemberPointer)
1235 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001236 }
1237
John McCallf7a1a742009-11-24 19:00:30 +00001238 if (TemplateArgs)
1239 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001240
John McCallf7a1a742009-11-24 19:00:30 +00001241 return BuildDeclarationNameExpr(SS, R, ADL);
1242}
1243
John McCall3b4294e2009-12-16 12:17:52 +00001244/// Builds an expression which might be an implicit member expression.
1245Sema::OwningExprResult
1246Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1247 LookupResult &R,
1248 const TemplateArgumentListInfo *TemplateArgs) {
1249 switch (ClassifyImplicitMemberAccess(*this, R)) {
1250 case IMA_Instance:
1251 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1252
1253 case IMA_AnonymousMember:
1254 assert(R.isSingleResult());
1255 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1256 R.getAsSingle<FieldDecl>());
1257
1258 case IMA_Mixed:
1259 case IMA_Mixed_Unrelated:
1260 case IMA_Unresolved:
1261 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1262
1263 case IMA_Static:
1264 case IMA_Mixed_StaticContext:
1265 case IMA_Unresolved_StaticContext:
1266 if (TemplateArgs)
1267 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1268 return BuildDeclarationNameExpr(SS, R, false);
1269
1270 case IMA_Error_StaticContext:
1271 case IMA_Error_Unrelated:
1272 DiagnoseInstanceReference(*this, SS, R);
1273 return ExprError();
1274 }
1275
1276 llvm_unreachable("unexpected instance member access kind");
1277 return ExprError();
1278}
1279
John McCall129e2df2009-11-30 22:42:35 +00001280/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1281/// declaration name, generally during template instantiation.
1282/// There's a large number of things which don't need to be done along
1283/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001284Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001285Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001286 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001287 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001288 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001289 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001290
John McCall77bb1aa2010-05-01 00:40:08 +00001291 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001292 return ExprError();
1293
Abramo Bagnara25777432010-08-11 22:01:17 +00001294 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001295 LookupQualifiedName(R, DC);
1296
1297 if (R.isAmbiguous())
1298 return ExprError();
1299
1300 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001301 Diag(NameInfo.getLoc(), diag::err_no_member)
1302 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001303 return ExprError();
1304 }
1305
1306 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1307}
1308
1309/// LookupInObjCMethod - The parser has read a name in, and Sema has
1310/// detected that we're currently inside an ObjC method. Perform some
1311/// additional lookup.
1312///
1313/// Ideally, most of this would be done by lookup, but there's
1314/// actually quite a lot of extra work involved.
1315///
1316/// Returns a null sentinel to indicate trivial success.
1317Sema::OwningExprResult
1318Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001319 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001320 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001321 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001322
John McCallf7a1a742009-11-24 19:00:30 +00001323 // There are two cases to handle here. 1) scoped lookup could have failed,
1324 // in which case we should look for an ivar. 2) scoped lookup could have
1325 // found a decl, but that decl is outside the current instance method (i.e.
1326 // a global variable). In these two cases, we do a lookup for an ivar with
1327 // this name, if the lookup sucedes, we replace it our current decl.
1328
1329 // If we're in a class method, we don't normally want to look for
1330 // ivars. But if we don't find anything else, and there's an
1331 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001332 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001333
1334 bool LookForIvars;
1335 if (Lookup.empty())
1336 LookForIvars = true;
1337 else if (IsClassMethod)
1338 LookForIvars = false;
1339 else
1340 LookForIvars = (Lookup.isSingleResult() &&
1341 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001342 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001343 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001344 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001345 ObjCInterfaceDecl *ClassDeclared;
1346 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1347 // Diagnose using an ivar in a class method.
1348 if (IsClassMethod)
1349 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1350 << IV->getDeclName());
1351
1352 // If we're referencing an invalid decl, just return this as a silent
1353 // error node. The error diagnostic was already emitted on the decl.
1354 if (IV->isInvalidDecl())
1355 return ExprError();
1356
1357 // Check if referencing a field with __attribute__((deprecated)).
1358 if (DiagnoseUseOfDecl(IV, Loc))
1359 return ExprError();
1360
1361 // Diagnose the use of an ivar outside of the declaring class.
1362 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1363 ClassDeclared != IFace)
1364 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1365
1366 // FIXME: This should use a new expr for a direct reference, don't
1367 // turn this into Self->ivar, just return a BareIVarExpr or something.
1368 IdentifierInfo &II = Context.Idents.get("self");
1369 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001370 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001371 CXXScopeSpec SelfScopeSpec;
1372 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1373 SelfName, false, false);
1374 MarkDeclarationReferenced(Loc, IV);
1375 return Owned(new (Context)
1376 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1377 SelfExpr.takeAs<Expr>(), true, true));
1378 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001379 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001380 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001381 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001382 ObjCInterfaceDecl *ClassDeclared;
1383 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1384 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1385 IFace == ClassDeclared)
1386 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1387 }
1388 }
1389
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001390 if (Lookup.empty() && II && AllowBuiltinCreation) {
1391 // FIXME. Consolidate this with similar code in LookupName.
1392 if (unsigned BuiltinID = II->getBuiltinID()) {
1393 if (!(getLangOptions().CPlusPlus &&
1394 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1395 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1396 S, Lookup.isForRedeclaration(),
1397 Lookup.getNameLoc());
1398 if (D) Lookup.addDecl(D);
1399 }
1400 }
1401 }
John McCallf7a1a742009-11-24 19:00:30 +00001402 // Sentinel value saying that we didn't do anything special.
1403 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001404}
John McCallba135432009-11-21 08:51:07 +00001405
John McCall6bb80172010-03-30 21:47:33 +00001406/// \brief Cast a base object to a member's actual type.
1407///
1408/// Logically this happens in three phases:
1409///
1410/// * First we cast from the base type to the naming class.
1411/// The naming class is the class into which we were looking
1412/// when we found the member; it's the qualifier type if a
1413/// qualifier was provided, and otherwise it's the base type.
1414///
1415/// * Next we cast from the naming class to the declaring class.
1416/// If the member we found was brought into a class's scope by
1417/// a using declaration, this is that class; otherwise it's
1418/// the class declaring the member.
1419///
1420/// * Finally we cast from the declaring class to the "true"
1421/// declaring class of the member. This conversion does not
1422/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001423bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001424Sema::PerformObjectMemberConversion(Expr *&From,
1425 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001426 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001427 NamedDecl *Member) {
1428 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1429 if (!RD)
1430 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001431
Douglas Gregor5fccd362010-03-03 23:55:11 +00001432 QualType DestRecordType;
1433 QualType DestType;
1434 QualType FromRecordType;
1435 QualType FromType = From->getType();
1436 bool PointerConversions = false;
1437 if (isa<FieldDecl>(Member)) {
1438 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001439
Douglas Gregor5fccd362010-03-03 23:55:11 +00001440 if (FromType->getAs<PointerType>()) {
1441 DestType = Context.getPointerType(DestRecordType);
1442 FromRecordType = FromType->getPointeeType();
1443 PointerConversions = true;
1444 } else {
1445 DestType = DestRecordType;
1446 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001447 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001448 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1449 if (Method->isStatic())
1450 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001451
Douglas Gregor5fccd362010-03-03 23:55:11 +00001452 DestType = Method->getThisType(Context);
1453 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001454
Douglas Gregor5fccd362010-03-03 23:55:11 +00001455 if (FromType->getAs<PointerType>()) {
1456 FromRecordType = FromType->getPointeeType();
1457 PointerConversions = true;
1458 } else {
1459 FromRecordType = FromType;
1460 DestType = DestRecordType;
1461 }
1462 } else {
1463 // No conversion necessary.
1464 return false;
1465 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001466
Douglas Gregor5fccd362010-03-03 23:55:11 +00001467 if (DestType->isDependentType() || FromType->isDependentType())
1468 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001469
Douglas Gregor5fccd362010-03-03 23:55:11 +00001470 // If the unqualified types are the same, no conversion is necessary.
1471 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1472 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001473
John McCall6bb80172010-03-30 21:47:33 +00001474 SourceRange FromRange = From->getSourceRange();
1475 SourceLocation FromLoc = FromRange.getBegin();
1476
Sebastian Redl906082e2010-07-20 04:20:21 +00001477 ImplicitCastExpr::ResultCategory Category = CastCategory(From);
1478
Douglas Gregor5fccd362010-03-03 23:55:11 +00001479 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001480 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001481 // class name.
1482 //
1483 // If the member was a qualified name and the qualified referred to a
1484 // specific base subobject type, we'll cast to that intermediate type
1485 // first and then to the object in which the member is declared. That allows
1486 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1487 //
1488 // class Base { public: int x; };
1489 // class Derived1 : public Base { };
1490 // class Derived2 : public Base { };
1491 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1492 //
1493 // void VeryDerived::f() {
1494 // x = 17; // error: ambiguous base subobjects
1495 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1496 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001497 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001498 QualType QType = QualType(Qualifier->getAsType(), 0);
1499 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1500 assert(QType->isRecordType() && "lookup done with non-record type");
1501
1502 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1503
1504 // In C++98, the qualifier type doesn't actually have to be a base
1505 // type of the object type, in which case we just ignore it.
1506 // Otherwise build the appropriate casts.
1507 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00001508 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001509 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001510 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001511 return true;
1512
Douglas Gregor5fccd362010-03-03 23:55:11 +00001513 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00001514 QType = Context.getPointerType(QType);
John McCall23cba802010-03-30 23:58:03 +00001515 ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
John McCallf871d0c2010-08-07 06:22:56 +00001516 Category, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001517
1518 FromType = QType;
1519 FromRecordType = QRecordType;
1520
1521 // If the qualifier type was the same as the destination type,
1522 // we're done.
1523 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1524 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001525 }
1526 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001527
John McCall6bb80172010-03-30 21:47:33 +00001528 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001529
John McCall6bb80172010-03-30 21:47:33 +00001530 // If we actually found the member through a using declaration, cast
1531 // down to the using declaration's type.
1532 //
1533 // Pointer equality is fine here because only one declaration of a
1534 // class ever has member declarations.
1535 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1536 assert(isa<UsingShadowDecl>(FoundDecl));
1537 QualType URecordType = Context.getTypeDeclType(
1538 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1539
1540 // We only need to do this if the naming-class to declaring-class
1541 // conversion is non-trivial.
1542 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1543 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00001544 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001545 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001546 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001547 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001548
John McCall6bb80172010-03-30 21:47:33 +00001549 QualType UType = URecordType;
1550 if (PointerConversions)
1551 UType = Context.getPointerType(UType);
John McCall23cba802010-03-30 23:58:03 +00001552 ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
John McCallf871d0c2010-08-07 06:22:56 +00001553 Category, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001554 FromType = UType;
1555 FromRecordType = URecordType;
1556 }
1557
1558 // We don't do access control for the conversion from the
1559 // declaring class to the true declaring class.
1560 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001561 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001562
John McCallf871d0c2010-08-07 06:22:56 +00001563 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00001564 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1565 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00001566 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00001567 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001568
John McCall23cba802010-03-30 23:58:03 +00001569 ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
John McCallf871d0c2010-08-07 06:22:56 +00001570 Category, &BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001571 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001572}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001573
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001574/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001575static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001576 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00001577 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00001578 const DeclarationNameInfo &MemberNameInfo,
1579 QualType Ty,
John McCallf7a1a742009-11-24 19:00:30 +00001580 const TemplateArgumentListInfo *TemplateArgs = 0) {
1581 NestedNameSpecifier *Qualifier = 0;
1582 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001583 if (SS.isSet()) {
1584 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1585 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
John McCallf7a1a742009-11-24 19:00:30 +00001588 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001589 Member, FoundDecl, MemberNameInfo,
1590 TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001591}
1592
John McCallaa81e162009-12-01 22:10:20 +00001593/// Builds an implicit member access expression. The current context
1594/// is known to be an instance method, and the given unqualified lookup
1595/// set is known to contain only instance members, at least one of which
1596/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001597Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001598Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1599 LookupResult &R,
1600 const TemplateArgumentListInfo *TemplateArgs,
1601 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001602 assert(!R.empty() && !R.isAmbiguous());
1603
John McCallba135432009-11-21 08:51:07 +00001604 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001605
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001606 // We may have found a field within an anonymous union or struct
1607 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001608 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001609 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001610 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001611 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001612 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001613
John McCallaa81e162009-12-01 22:10:20 +00001614 // If this is known to be an instance access, go ahead and build a
1615 // 'this' expression now.
John McCallea1471e2010-05-20 01:18:31 +00001616 DeclContext *DC = getFunctionLevelDeclContext();
1617 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallaa81e162009-12-01 22:10:20 +00001618 Expr *This = 0; // null signifies implicit access
1619 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00001620 SourceLocation Loc = R.getNameLoc();
1621 if (SS.getRange().isValid())
1622 Loc = SS.getRange().getBegin();
1623 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00001624 }
1625
John McCallaa81e162009-12-01 22:10:20 +00001626 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1627 /*OpLoc*/ SourceLocation(),
1628 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00001629 SS,
1630 /*FirstQualifierInScope*/ 0,
1631 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001632}
1633
John McCallf7a1a742009-11-24 19:00:30 +00001634bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001635 const LookupResult &R,
1636 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001637 // Only when used directly as the postfix-expression of a call.
1638 if (!HasTrailingLParen)
1639 return false;
1640
1641 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001642 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001643 return false;
1644
1645 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001646 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001647 return false;
1648
1649 // Turn off ADL when we find certain kinds of declarations during
1650 // normal lookup:
1651 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1652 NamedDecl *D = *I;
1653
1654 // C++0x [basic.lookup.argdep]p3:
1655 // -- a declaration of a class member
1656 // Since using decls preserve this property, we check this on the
1657 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001658 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001659 return false;
1660
1661 // C++0x [basic.lookup.argdep]p3:
1662 // -- a block-scope function declaration that is not a
1663 // using-declaration
1664 // NOTE: we also trigger this for function templates (in fact, we
1665 // don't check the decl type at all, since all other decl types
1666 // turn off ADL anyway).
1667 if (isa<UsingShadowDecl>(D))
1668 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1669 else if (D->getDeclContext()->isFunctionOrMethod())
1670 return false;
1671
1672 // C++0x [basic.lookup.argdep]p3:
1673 // -- a declaration that is neither a function or a function
1674 // template
1675 // And also for builtin functions.
1676 if (isa<FunctionDecl>(D)) {
1677 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1678
1679 // But also builtin functions.
1680 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1681 return false;
1682 } else if (!isa<FunctionTemplateDecl>(D))
1683 return false;
1684 }
1685
1686 return true;
1687}
1688
1689
John McCallba135432009-11-21 08:51:07 +00001690/// Diagnoses obvious problems with the use of the given declaration
1691/// as an expression. This is only actually called for lookups that
1692/// were not overloaded, and it doesn't promise that the declaration
1693/// will in fact be used.
1694static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1695 if (isa<TypedefDecl>(D)) {
1696 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1697 return true;
1698 }
1699
1700 if (isa<ObjCInterfaceDecl>(D)) {
1701 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1702 return true;
1703 }
1704
1705 if (isa<NamespaceDecl>(D)) {
1706 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1707 return true;
1708 }
1709
1710 return false;
1711}
1712
1713Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001714Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001715 LookupResult &R,
1716 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001717 // If this is a single, fully-resolved result and we don't need ADL,
1718 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00001719 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00001720 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
1721 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001722
1723 // We only need to check the declaration if there's exactly one
1724 // result, because in the overloaded case the results can only be
1725 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001726 if (R.isSingleResult() &&
1727 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001728 return ExprError();
1729
John McCallc373d482010-01-27 01:50:18 +00001730 // Otherwise, just build an unresolved lookup expression. Suppress
1731 // any lookup-related diagnostics; we'll hash these out later, when
1732 // we've picked a target.
1733 R.suppressDiagnostics();
1734
John McCallf7a1a742009-11-24 19:00:30 +00001735 bool Dependent
1736 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001737 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001738 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001739 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnara25777432010-08-11 22:01:17 +00001740 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001741 NeedsADL, R.isOverloadedResult(),
1742 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00001743
1744 return Owned(ULE);
1745}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001746
John McCallba135432009-11-21 08:51:07 +00001747
1748/// \brief Complete semantic analysis for a reference to the given declaration.
1749Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001750Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001751 const DeclarationNameInfo &NameInfo,
1752 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00001753 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001754 assert(!isa<FunctionTemplateDecl>(D) &&
1755 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001756
Abramo Bagnara25777432010-08-11 22:01:17 +00001757 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001758 if (CheckDeclInExpr(*this, Loc, D))
1759 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001760
Douglas Gregor9af2f522009-12-01 16:58:18 +00001761 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1762 // Specifically diagnose references to class templates that are missing
1763 // a template argument list.
1764 Diag(Loc, diag::err_template_decl_ref)
1765 << Template << SS.getRange();
1766 Diag(Template->getLocation(), diag::note_template_decl_here);
1767 return ExprError();
1768 }
1769
1770 // Make sure that we're referring to a value.
1771 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1772 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001773 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00001774 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001775 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001776 return ExprError();
1777 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001778
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001779 // Check whether this declaration can be used. Note that we suppress
1780 // this check when we're going to perform argument-dependent lookup
1781 // on this function name, because this might not be the function
1782 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001783 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001784 return ExprError();
1785
Steve Naroffdd972f22008-09-05 22:11:13 +00001786 // Only create DeclRefExpr's for valid Decl's.
1787 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001788 return ExprError();
1789
Chris Lattner639e2d32008-10-20 05:16:36 +00001790 // If the identifier reference is inside a block, and it refers to a value
1791 // that is outside the block, create a BlockDeclRefExpr instead of a
1792 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1793 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001794 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001795 // We do not do this for things like enum constants, global variables, etc,
1796 // as they do not get snapshotted.
1797 //
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001798 if (getCurBlock() &&
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001799 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00001800 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1801 Diag(Loc, diag::err_ref_vm_type);
1802 Diag(D->getLocation(), diag::note_declared_at);
1803 return ExprError();
1804 }
1805
Fariborz Jahanian8596bbe2010-03-16 23:39:51 +00001806 if (VD->getType()->isArrayType()) {
Mike Stump28497342010-01-05 03:10:36 +00001807 Diag(Loc, diag::err_ref_array_type);
1808 Diag(D->getLocation(), diag::note_declared_at);
1809 return ExprError();
1810 }
1811
Douglas Gregore0762c92009-06-19 23:52:42 +00001812 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001813 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001814 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001815 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001816 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001817 // This is to record that a 'const' was actually synthesize and added.
1818 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001819 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Eli Friedman5fdeae12009-03-22 23:00:19 +00001821 ExprTy.addConst();
Fariborz Jahanian52bc56a2010-07-12 17:26:57 +00001822 QualType T = VD->getType();
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00001823 BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD,
1824 ExprTy, Loc, false,
Fariborz Jahanian84ca0082010-07-12 18:12:03 +00001825 constAdded);
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001826 if (getLangOptions().CPlusPlus) {
1827 if (!T->isDependentType() && !T->isReferenceType()) {
1828 Expr *E = new (Context)
1829 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
1830 SourceLocation());
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00001831
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001832 OwningExprResult Res = PerformCopyInitialization(
1833 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001834 T, false),
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001835 SourceLocation(),
1836 Owned(E));
1837 if (!Res.isInvalid()) {
1838 Res = MaybeCreateCXXExprWithTemporaries(move(Res));
1839 Expr *Init = Res.takeAs<Expr>();
1840 BDRE->setCopyConstructorExpr(Init);
1841 }
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00001842 }
1843 }
1844 return Owned(BDRE);
Steve Naroff090276f2008-10-10 01:28:17 +00001845 }
1846 // If this reference is not in a block or if the referenced variable is
1847 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001848
Abramo Bagnara25777432010-08-11 22:01:17 +00001849 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
1850 NameInfo, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001851}
1852
Sebastian Redlcd965b92009-01-18 18:53:16 +00001853Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1854 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001855 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001856
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001858 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001859 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1860 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1861 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001863
Chris Lattnerfa28b302008-01-12 08:14:25 +00001864 // Pre-defined identifiers are of type char[x], where x is the length of the
1865 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Anders Carlsson3a082d82009-09-08 18:24:21 +00001867 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00001868 if (!currentDecl && getCurBlock())
1869 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00001870 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001871 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001872 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001873 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001874
Anders Carlsson773f3972009-09-11 01:22:35 +00001875 QualType ResTy;
1876 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1877 ResTy = Context.DependentTy;
1878 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00001879 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001880
Anders Carlsson773f3972009-09-11 01:22:35 +00001881 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001882 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001883 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1884 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001885 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001886}
1887
Sebastian Redlcd965b92009-01-18 18:53:16 +00001888Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00001890 bool Invalid = false;
1891 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1892 if (Invalid)
1893 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001894
Benjamin Kramerddeea562010-02-27 13:44:12 +00001895 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1896 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001898 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001899
Chris Lattnere8337df2009-12-30 21:19:39 +00001900 QualType Ty;
1901 if (!getLangOptions().CPlusPlus)
1902 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1903 else if (Literal.isWide())
1904 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00001905 else if (Literal.isMultiChar())
1906 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00001907 else
1908 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001909
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001910 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1911 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00001912 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001913}
1914
Sebastian Redlcd965b92009-01-18 18:53:16 +00001915Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1916 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1918 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001919 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001920 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001921 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001922 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 }
Ted Kremenek28396602009-01-13 23:19:12 +00001924
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001926 // Add padding so that NumericLiteralParser can overread by one character.
1927 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001928 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001929
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00001931 bool Invalid = false;
1932 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1933 if (Invalid)
1934 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001935
Mike Stump1eb44332009-09-09 15:08:12 +00001936 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 Tok.getLocation(), PP);
1938 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001939 return ExprError();
1940
Chris Lattner5d661452007-08-26 03:42:43 +00001941 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001942
Chris Lattner5d661452007-08-26 03:42:43 +00001943 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001944 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001945 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001946 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001947 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001948 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001949 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001950 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001951
1952 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1953
John McCall94c939d2009-12-24 09:08:04 +00001954 using llvm::APFloat;
1955 APFloat Val(Format);
1956
1957 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00001958
1959 // Overflow is always an error, but underflow is only an error if
1960 // we underflowed to zero (APFloat reports denormals as underflow).
1961 if ((result & APFloat::opOverflow) ||
1962 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00001963 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001964 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00001965 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00001966 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00001967 APFloat::getLargest(Format).toString(buffer);
1968 } else {
John McCall2a0d7572010-02-26 23:35:57 +00001969 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00001970 APFloat::getSmallest(Format).toString(buffer);
1971 }
1972
1973 Diag(Tok.getLocation(), diagnostic)
1974 << Ty
1975 << llvm::StringRef(buffer.data(), buffer.size());
1976 }
1977
1978 bool isExact = (result == APFloat::opOK);
Chris Lattner001d64d2009-06-29 17:34:55 +00001979 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001980
Chris Lattner5d661452007-08-26 03:42:43 +00001981 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001982 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001983 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001984 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001985
Neil Boothb9449512007-08-29 22:00:19 +00001986 // long long is a C99 feature.
1987 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001988 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001989 Diag(Tok.getLocation(), diag::ext_longlong);
1990
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001992 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001993
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 if (Literal.GetIntegerValue(ResultVal)) {
1995 // If this value didn't fit into uintmax_t, warn and force to ull.
1996 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001997 Ty = Context.UnsignedLongLongTy;
1998 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001999 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 } else {
2001 // If this value fits into a ULL, try to figure out what else it fits into
2002 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002003
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2005 // be an unsigned int.
2006 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2007
2008 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002009 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002010 if (!Literal.isLong && !Literal.isLongLong) {
2011 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002012 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002013
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 // Does it fit in a unsigned int?
2015 if (ResultVal.isIntN(IntSize)) {
2016 // Does it fit in a signed int?
2017 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002018 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002020 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002021 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002024
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002026 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002027 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002028
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 // Does it fit in a unsigned long?
2030 if (ResultVal.isIntN(LongSize)) {
2031 // Does it fit in a signed long?
2032 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002033 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002034 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002035 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002036 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002038 }
2039
Reid Spencer5f016e22007-07-11 17:01:13 +00002040 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002041 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002042 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002043
Reid Spencer5f016e22007-07-11 17:01:13 +00002044 // Does it fit in a unsigned long long?
2045 if (ResultVal.isIntN(LongLongSize)) {
2046 // Does it fit in a signed long long?
2047 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002048 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002050 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002051 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 }
2053 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002054
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 // If we still couldn't decide a type, we probably have something that
2056 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002057 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002058 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002059 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002060 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002062
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002063 if (ResultVal.getBitWidth() != Width)
2064 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002066 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002068
Chris Lattner5d661452007-08-26 03:42:43 +00002069 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2070 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002071 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002072 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002073
2074 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002075}
2076
Sebastian Redlcd965b92009-01-18 18:53:16 +00002077Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
2078 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00002079 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00002080 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002081 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002082}
2083
2084/// The UsualUnaryConversions() function is *not* called by this routine.
2085/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002086bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002087 SourceLocation OpLoc,
2088 const SourceRange &ExprRange,
2089 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002090 if (exprType->isDependentType())
2091 return false;
2092
Sebastian Redl5d484e82009-11-23 17:18:46 +00002093 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2094 // the result is the size of the referenced type."
2095 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2096 // result shall be the alignment of the referenced type."
2097 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2098 exprType = Ref->getPointeeType();
2099
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002101 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002102 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002103 if (isSizeof)
2104 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2105 return false;
2106 }
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Chris Lattner1efaa952009-04-24 00:30:45 +00002108 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002109 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002110 Diag(OpLoc, diag::ext_sizeof_void_type)
2111 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002112 return false;
2113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Chris Lattner1efaa952009-04-24 00:30:45 +00002115 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002116 PDiag(diag::err_sizeof_alignof_incomplete_type)
2117 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002118 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Chris Lattner1efaa952009-04-24 00:30:45 +00002120 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002121 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002122 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002123 << exprType << isSizeof << ExprRange;
2124 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002125 }
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Douglas Gregor9ba6af82010-05-23 19:43:23 +00002127 if (Context.hasSameUnqualifiedType(exprType, Context.OverloadTy)) {
2128 Diag(OpLoc, diag::err_sizeof_alignof_overloaded_function_type)
2129 << !isSizeof << ExprRange;
2130 return true;
2131 }
2132
Chris Lattner1efaa952009-04-24 00:30:45 +00002133 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002134}
2135
Chris Lattner31e21e02009-01-24 20:17:12 +00002136bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2137 const SourceRange &ExprRange) {
2138 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002139
Mike Stump1eb44332009-09-09 15:08:12 +00002140 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002141 if (isa<DeclRefExpr>(E))
2142 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002143
2144 // Cannot know anything else if the expression is dependent.
2145 if (E->isTypeDependent())
2146 return false;
2147
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002148 if (E->getBitField()) {
2149 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2150 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002151 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002152
2153 // Alignment of a field access is always okay, so long as it isn't a
2154 // bit-field.
2155 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002156 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002157 return false;
2158
Chris Lattner31e21e02009-01-24 20:17:12 +00002159 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2160}
2161
Douglas Gregorba498172009-03-13 21:01:28 +00002162/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002163Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00002164Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002165 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002166 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002167 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002168 return ExprError();
2169
John McCalla93c9342009-12-07 02:54:59 +00002170 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002171
Douglas Gregorba498172009-03-13 21:01:28 +00002172 if (!T->isDependentType() &&
2173 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2174 return ExprError();
2175
2176 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002177 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002178 Context.getSizeType(), OpLoc,
2179 R.getEnd()));
2180}
2181
2182/// \brief Build a sizeof or alignof expression given an expression
2183/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002184Action::OwningExprResult
2185Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002186 bool isSizeOf, SourceRange R) {
2187 // Verify that the operand is valid.
2188 bool isInvalid = false;
2189 if (E->isTypeDependent()) {
2190 // Delay type-checking for type-dependent expressions.
2191 } else if (!isSizeOf) {
2192 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002193 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002194 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2195 isInvalid = true;
2196 } else {
2197 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2198 }
2199
2200 if (isInvalid)
2201 return ExprError();
2202
2203 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2204 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2205 Context.getSizeType(), OpLoc,
2206 R.getEnd()));
2207}
2208
Sebastian Redl05189992008-11-11 17:56:53 +00002209/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2210/// the same for @c alignof and @c __alignof
2211/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002212Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002213Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2214 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002215 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002216 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002217
Sebastian Redl05189992008-11-11 17:56:53 +00002218 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002219 TypeSourceInfo *TInfo;
2220 (void) GetTypeFromParser(TyOrEx, &TInfo);
2221 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002222 }
Sebastian Redl05189992008-11-11 17:56:53 +00002223
Douglas Gregorba498172009-03-13 21:01:28 +00002224 Expr *ArgEx = (Expr *)TyOrEx;
2225 Action::OwningExprResult Result
2226 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2227
2228 if (Result.isInvalid())
2229 DeleteExpr(ArgEx);
2230
2231 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002232}
2233
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002234QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002235 if (V->isTypeDependent())
2236 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Chris Lattnercc26ed72007-08-26 05:39:26 +00002238 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002239 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002240 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Chris Lattnercc26ed72007-08-26 05:39:26 +00002242 // Otherwise they pass through real integer and floating point types here.
2243 if (V->getType()->isArithmeticType())
2244 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Chris Lattnercc26ed72007-08-26 05:39:26 +00002246 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002247 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2248 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002249 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002250}
2251
2252
Reid Spencer5f016e22007-07-11 17:01:13 +00002253
Sebastian Redl0eb23302009-01-19 00:08:26 +00002254Action::OwningExprResult
2255Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2256 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002257 UnaryOperator::Opcode Opc;
2258 switch (Kind) {
2259 default: assert(0 && "Unknown unary op!");
2260 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2261 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2262 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002263
Eli Friedmane4216e92009-11-18 03:38:04 +00002264 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00002265}
2266
Sebastian Redl0eb23302009-01-19 00:08:26 +00002267Action::OwningExprResult
2268Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2269 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002270 // Since this might be a postfix expression, get rid of ParenListExprs.
2271 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2272
Sebastian Redl0eb23302009-01-19 00:08:26 +00002273 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2274 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002275
Douglas Gregor337c6b92008-11-19 17:17:41 +00002276 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002277 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2278 Base.release();
2279 Idx.release();
2280 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2281 Context.DependentTy, RLoc));
2282 }
2283
Mike Stump1eb44332009-09-09 15:08:12 +00002284 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002285 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002286 LHSExp->getType()->isEnumeralType() ||
2287 RHSExp->getType()->isRecordType() ||
2288 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00002289 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00002290 }
2291
Sebastian Redlf322ed62009-10-29 20:17:01 +00002292 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2293}
2294
2295
2296Action::OwningExprResult
2297Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2298 ExprArg Idx, SourceLocation RLoc) {
2299 Expr *LHSExp = static_cast<Expr*>(Base.get());
2300 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2301
Chris Lattner12d9ff62007-07-16 00:14:47 +00002302 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002303 if (!LHSExp->getType()->getAs<VectorType>())
2304 DefaultFunctionArrayLvalueConversion(LHSExp);
2305 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002306
Chris Lattner12d9ff62007-07-16 00:14:47 +00002307 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002308
Reid Spencer5f016e22007-07-11 17:01:13 +00002309 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002310 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002311 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002313 Expr *BaseExpr, *IndexExpr;
2314 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002315 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2316 BaseExpr = LHSExp;
2317 IndexExpr = RHSExp;
2318 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002319 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002320 BaseExpr = LHSExp;
2321 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002322 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002323 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002324 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002325 BaseExpr = RHSExp;
2326 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002327 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002328 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002329 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002330 BaseExpr = LHSExp;
2331 IndexExpr = RHSExp;
2332 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002333 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002334 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002335 // Handle the uncommon case of "123[Ptr]".
2336 BaseExpr = RHSExp;
2337 IndexExpr = LHSExp;
2338 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002339 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002340 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002341 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00002342
Chris Lattner12d9ff62007-07-16 00:14:47 +00002343 // FIXME: need to deal with const...
2344 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002345 } else if (LHSTy->isArrayType()) {
2346 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00002347 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002348 // wasn't promoted because of the C90 rule that doesn't
2349 // allow promoting non-lvalue arrays. Warn, then
2350 // force the promotion here.
2351 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2352 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002353 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2354 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002355 LHSTy = LHSExp->getType();
2356
2357 BaseExpr = LHSExp;
2358 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002359 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002360 } else if (RHSTy->isArrayType()) {
2361 // Same as previous, except for 123[f().a] case
2362 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2363 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002364 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2365 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002366 RHSTy = RHSExp->getType();
2367
2368 BaseExpr = RHSExp;
2369 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002370 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002371 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002372 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2373 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002374 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002375 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00002376 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002377 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2378 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002379
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002380 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002381 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2382 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002383 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2384
Douglas Gregore7450f52009-03-24 19:52:54 +00002385 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002386 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2387 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002388 // incomplete types are not object types.
2389 if (ResultType->isFunctionType()) {
2390 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2391 << ResultType << BaseExpr->getSourceRange();
2392 return ExprError();
2393 }
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Douglas Gregore7450f52009-03-24 19:52:54 +00002395 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002396 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002397 PDiag(diag::err_subscript_incomplete_type)
2398 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002399 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Chris Lattner1efaa952009-04-24 00:30:45 +00002401 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00002402 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002403 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2404 << ResultType << BaseExpr->getSourceRange();
2405 return ExprError();
2406 }
Mike Stump1eb44332009-09-09 15:08:12 +00002407
Sebastian Redl0eb23302009-01-19 00:08:26 +00002408 Base.release();
2409 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002410 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002411 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002412}
2413
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002414QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002415CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002416 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002417 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002418 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2419 // see FIXME there.
2420 //
2421 // FIXME: This logic can be greatly simplified by splitting it along
2422 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002423 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002424
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002425 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002426 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002427
Mike Stumpeed9cac2009-02-19 03:04:26 +00002428 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002429 // special names that indicate a subset of exactly half the elements are
2430 // to be selected.
2431 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002432
Nate Begeman353417a2009-01-18 01:47:54 +00002433 // This flag determines whether or not CompName has an 's' char prefix,
2434 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002435 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002436
2437 // Check that we've found one of the special components, or that the component
2438 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002439 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002440 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2441 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002442 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002443 do
2444 compStr++;
2445 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002446 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002447 do
2448 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002449 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002450 }
Nate Begeman353417a2009-01-18 01:47:54 +00002451
Mike Stumpeed9cac2009-02-19 03:04:26 +00002452 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002453 // We didn't get to the end of the string. This means the component names
2454 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002455 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00002456 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002457 return QualType();
2458 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002459
Nate Begeman353417a2009-01-18 01:47:54 +00002460 // Ensure no component accessor exceeds the width of the vector type it
2461 // operates on.
2462 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002463 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002464
2465 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002466 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002467
2468 while (*compStr) {
2469 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2470 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2471 << baseType << SourceRange(CompLoc);
2472 return QualType();
2473 }
2474 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002475 }
Nate Begeman8a997642008-05-09 06:41:27 +00002476
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002477 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002478 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002479 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002480 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002481 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002482 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002483 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002484 if (HexSwizzle)
2485 CompSize--;
2486
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002487 if (CompSize == 1)
2488 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002489
Nate Begeman213541a2008-04-18 23:10:10 +00002490 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002491 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002492 // diagostics look bad. We want extended vector types to appear built-in.
2493 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2494 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2495 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002496 }
2497 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002498}
2499
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002500static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002501 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002502 const Selector &Sel,
2503 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Anders Carlsson8f28f992009-08-26 18:25:21 +00002505 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002506 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002507 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002508 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002510 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2511 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002512 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002513 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002514 return D;
2515 }
2516 return 0;
2517}
2518
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002519static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002520 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002521 const Selector &Sel,
2522 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002523 // Check protocols on qualified interfaces.
2524 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002525 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002526 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002527 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002528 GDecl = PD;
2529 break;
2530 }
2531 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002532 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002533 GDecl = OMD;
2534 break;
2535 }
2536 }
2537 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002538 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002539 E = QIdTy->qual_end(); I != E; ++I) {
2540 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002541 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002542 if (GDecl)
2543 return GDecl;
2544 }
2545 }
2546 return GDecl;
2547}
Chris Lattner76a642f2009-02-15 22:43:40 +00002548
John McCall129e2df2009-11-30 22:42:35 +00002549Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002550Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2551 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002552 const CXXScopeSpec &SS,
2553 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00002554 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00002555 const TemplateArgumentListInfo *TemplateArgs) {
2556 Expr *BaseExpr = Base.takeAs<Expr>();
2557
2558 // Even in dependent contexts, try to diagnose base expressions with
2559 // obviously wrong types, e.g.:
2560 //
2561 // T* t;
2562 // t.f;
2563 //
2564 // In Obj-C++, however, the above expression is valid, since it could be
2565 // accessing the 'f' property if T is an Obj-C interface. The extra check
2566 // allows this, while still reporting an error if T is a struct pointer.
2567 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002568 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002569 if (PT && (!getLangOptions().ObjC1 ||
2570 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002571 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00002572 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002573 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002574 return ExprError();
2575 }
2576 }
2577
Abramo Bagnara25777432010-08-11 22:01:17 +00002578 assert(BaseType->isDependentType() ||
2579 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00002580 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00002581
2582 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2583 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002584 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002585 IsArrow, OpLoc,
2586 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2587 SS.getRange(),
2588 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00002589 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00002590}
2591
2592/// We know that the given qualified member reference points only to
2593/// declarations which do not belong to the static type of the base
2594/// expression. Diagnose the problem.
2595static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2596 Expr *BaseExpr,
2597 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002598 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002599 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002600 // If this is an implicit member access, use a different set of
2601 // diagnostics.
2602 if (!BaseExpr)
2603 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002604
John McCall110acc12010-04-27 01:43:38 +00002605 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2606 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002607}
2608
2609// Check whether the declarations we found through a nested-name
2610// specifier in a member expression are actually members of the base
2611// type. The restriction here is:
2612//
2613// C++ [expr.ref]p2:
2614// ... In these cases, the id-expression shall name a
2615// member of the class or of one of its base classes.
2616//
2617// So it's perfectly legitimate for the nested-name specifier to name
2618// an unrelated class, and for us to find an overload set including
2619// decls from classes which are not superclasses, as long as the decl
2620// we actually pick through overload resolution is from a superclass.
2621bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2622 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002623 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002624 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002625 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2626 if (!BaseRT) {
2627 // We can't check this yet because the base type is still
2628 // dependent.
2629 assert(BaseType->isDependentType());
2630 return false;
2631 }
2632 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002633
2634 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002635 // If this is an implicit member reference and we find a
2636 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00002637 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00002638 return false;
John McCall129e2df2009-11-30 22:42:35 +00002639
John McCallaa81e162009-12-01 22:10:20 +00002640 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00002641 DeclContext *DC = (*I)->getDeclContext();
2642 while (DC->isTransparentContext())
2643 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00002644
Douglas Gregor9d4bb942010-07-28 22:27:52 +00002645 if (!DC->isRecord())
2646 continue;
2647
John McCallaa81e162009-12-01 22:10:20 +00002648 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00002649 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00002650
2651 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2652 return false;
2653 }
2654
John McCall2f841ba2009-12-02 03:53:29 +00002655 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002656 return true;
2657}
2658
2659static bool
2660LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2661 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00002662 SourceLocation OpLoc, CXXScopeSpec &SS,
2663 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00002664 RecordDecl *RDecl = RTy->getDecl();
2665 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002666 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00002667 << BaseRange))
2668 return true;
2669
John McCallad00b772010-06-16 08:42:20 +00002670 if (HasTemplateArgs) {
2671 // LookupTemplateName doesn't expect these both to exist simultaneously.
2672 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
2673
2674 bool MOUS;
2675 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
2676 return false;
2677 }
2678
John McCallaa81e162009-12-01 22:10:20 +00002679 DeclContext *DC = RDecl;
2680 if (SS.isSet()) {
2681 // If the member name was a qualified-id, look into the
2682 // nested-name-specifier.
2683 DC = SemaRef.computeDeclContext(SS, false);
2684
John McCall77bb1aa2010-05-01 00:40:08 +00002685 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00002686 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2687 << SS.getRange() << DC;
2688 return true;
2689 }
2690
John McCallaa81e162009-12-01 22:10:20 +00002691 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002692
John McCallaa81e162009-12-01 22:10:20 +00002693 if (!isa<TypeDecl>(DC)) {
2694 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2695 << DC << SS.getRange();
2696 return true;
John McCall129e2df2009-11-30 22:42:35 +00002697 }
2698 }
2699
John McCallaa81e162009-12-01 22:10:20 +00002700 // The record definition is complete, now look up the member.
2701 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002702
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002703 if (!R.empty())
2704 return false;
2705
2706 // We didn't find anything with the given name, so try to correct
2707 // for typos.
2708 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002709 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00002710 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002711 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2712 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2713 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00002714 << FixItHint::CreateReplacement(R.getNameLoc(),
2715 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002716 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2717 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2718 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002719 return false;
2720 } else {
2721 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002722 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002723 }
2724
John McCall129e2df2009-11-30 22:42:35 +00002725 return false;
2726}
2727
2728Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002729Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002730 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002731 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002732 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00002733 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00002734 const TemplateArgumentListInfo *TemplateArgs) {
2735 Expr *Base = BaseArg.takeAs<Expr>();
2736
John McCall2f841ba2009-12-02 03:53:29 +00002737 if (BaseType->isDependentType() ||
2738 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002739 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002740 IsArrow, OpLoc,
2741 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00002742 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002743
Abramo Bagnara25777432010-08-11 22:01:17 +00002744 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002745
John McCallaa81e162009-12-01 22:10:20 +00002746 // Implicit member accesses.
2747 if (!Base) {
2748 QualType RecordTy = BaseType;
2749 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2750 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2751 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00002752 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00002753 return ExprError();
2754
2755 // Explicit member accesses.
2756 } else {
2757 OwningExprResult Result =
2758 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00002759 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00002760
2761 if (Result.isInvalid()) {
2762 Owned(Base);
2763 return ExprError();
2764 }
2765
2766 if (Result.get())
2767 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00002768
2769 // LookupMemberExpr can modify Base, and thus change BaseType
2770 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00002771 }
2772
Sebastian Redl0aa866f2010-05-07 09:09:23 +00002773 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCallc2233c52010-01-15 08:34:02 +00002774 OpLoc, IsArrow, SS, FirstQualifierInScope,
2775 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002776}
2777
2778Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002779Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2780 SourceLocation OpLoc, bool IsArrow,
2781 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00002782 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00002783 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00002784 const TemplateArgumentListInfo *TemplateArgs,
2785 bool SuppressQualifierCheck) {
John McCall129e2df2009-11-30 22:42:35 +00002786 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002787 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002788 if (IsArrow) {
2789 assert(BaseType->isPointerType());
2790 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2791 }
John McCall161755a2010-04-06 21:38:20 +00002792 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00002793
2794 NestedNameSpecifier *Qualifier =
2795 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Abramo Bagnara25777432010-08-11 22:01:17 +00002796 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
2797 DeclarationName MemberName = MemberNameInfo.getName();
2798 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00002799
2800 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002801 return ExprError();
2802
John McCall129e2df2009-11-30 22:42:35 +00002803 if (R.empty()) {
2804 // Rederive where we looked up.
2805 DeclContext *DC = (SS.isSet()
2806 ? computeDeclContext(SS, false)
2807 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002808
John McCall129e2df2009-11-30 22:42:35 +00002809 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002810 << MemberName << DC
2811 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002812 return ExprError();
2813 }
2814
John McCallc2233c52010-01-15 08:34:02 +00002815 // Diagnose lookups that find only declarations from a non-base
2816 // type. This is possible for either qualified lookups (which may
2817 // have been qualified with an unrelated type) or implicit member
2818 // expressions (which were found with unqualified lookup and thus
2819 // may have come from an enclosing scope). Note that it's okay for
2820 // lookup to find declarations from a non-base type as long as those
2821 // aren't the ones picked by overload resolution.
2822 if ((SS.isSet() || !BaseExpr ||
2823 (isa<CXXThisExpr>(BaseExpr) &&
2824 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00002825 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00002826 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002827 return ExprError();
2828
2829 // Construct an unresolved result if we in fact got an unresolved
2830 // result.
2831 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002832 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002833 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002834 R.isUnresolvableResult() ||
John McCall7bb12da2010-02-02 06:20:04 +00002835 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002836
John McCallc373d482010-01-27 01:50:18 +00002837 // Suppress any lookup-related diagnostics; we'll do these when we
2838 // pick a member.
2839 R.suppressDiagnostics();
2840
John McCall129e2df2009-11-30 22:42:35 +00002841 UnresolvedMemberExpr *MemExpr
2842 = UnresolvedMemberExpr::Create(Context, Dependent,
2843 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002844 BaseExpr, BaseExprType,
2845 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002846 Qualifier, SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002847 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002848 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00002849
2850 return Owned(MemExpr);
2851 }
2852
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002853 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00002854 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00002855 NamedDecl *MemberDecl = R.getFoundDecl();
2856
2857 // FIXME: diagnose the presence of template arguments now.
2858
2859 // If the decl being referenced had an error, return an error for this
2860 // sub-expr without emitting another error, in order to avoid cascading
2861 // error cases.
2862 if (MemberDecl->isInvalidDecl())
2863 return ExprError();
2864
John McCallaa81e162009-12-01 22:10:20 +00002865 // Handle the implicit-member-access case.
2866 if (!BaseExpr) {
2867 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00002868 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00002869 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00002870
Douglas Gregor828a1972010-01-07 23:12:05 +00002871 SourceLocation Loc = R.getNameLoc();
2872 if (SS.getRange().isValid())
2873 Loc = SS.getRange().getBegin();
2874 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00002875 }
2876
John McCall129e2df2009-11-30 22:42:35 +00002877 bool ShouldCheckUse = true;
2878 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2879 // Don't diagnose the use of a virtual member function unless it's
2880 // explicitly qualified.
2881 if (MD->isVirtual() && !SS.isSet())
2882 ShouldCheckUse = false;
2883 }
2884
2885 // Check the use of this member.
2886 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2887 Owned(BaseExpr);
2888 return ExprError();
2889 }
2890
2891 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2892 // We may have found a field within an anonymous union or struct
2893 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002894 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2895 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002896 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2897 BaseExpr, OpLoc);
2898
2899 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2900 QualType MemberType = FD->getType();
2901 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2902 MemberType = Ref->getPointeeType();
2903 else {
2904 Qualifiers BaseQuals = BaseType.getQualifiers();
2905 BaseQuals.removeObjCGCAttr();
2906 if (FD->isMutable()) BaseQuals.removeConst();
2907
2908 Qualifiers MemberQuals
2909 = Context.getCanonicalType(MemberType).getQualifiers();
2910
2911 Qualifiers Combined = BaseQuals + MemberQuals;
2912 if (Combined != MemberQuals)
2913 MemberType = Context.getQualifiedType(MemberType, Combined);
2914 }
2915
2916 MarkDeclarationReferenced(MemberLoc, FD);
John McCall6bb80172010-03-30 21:47:33 +00002917 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall129e2df2009-11-30 22:42:35 +00002918 return ExprError();
2919 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002920 FD, FoundDecl, MemberNameInfo,
2921 MemberType));
John McCall129e2df2009-11-30 22:42:35 +00002922 }
2923
2924 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2925 MarkDeclarationReferenced(MemberLoc, Var);
2926 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002927 Var, FoundDecl, MemberNameInfo,
John McCall129e2df2009-11-30 22:42:35 +00002928 Var->getType().getNonReferenceType()));
2929 }
2930
2931 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2932 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2933 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002934 MemberFn, FoundDecl, MemberNameInfo,
John McCall129e2df2009-11-30 22:42:35 +00002935 MemberFn->getType()));
2936 }
2937
2938 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2939 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2940 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002941 Enum, FoundDecl, MemberNameInfo,
2942 Enum->getType()));
John McCall129e2df2009-11-30 22:42:35 +00002943 }
2944
2945 Owned(BaseExpr);
2946
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002947 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00002948 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00002949 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002950 << MemberName << BaseType << int(IsArrow);
2951 else
2952 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
2953 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00002954
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002955 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
2956 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00002957 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002958 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002959}
2960
2961/// Look up the given member of the given non-type-dependent
2962/// expression. This can return in one of two ways:
2963/// * If it returns a sentinel null-but-valid result, the caller will
2964/// assume that lookup was performed and the results written into
2965/// the provided structure. It will take over from there.
2966/// * Otherwise, the returned expression will be produced in place of
2967/// an ordinary member expression.
2968///
2969/// The ObjCImpDecl bit is a gross hack that will need to be properly
2970/// fixed for ObjC++.
2971Sema::OwningExprResult
2972Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002973 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002974 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00002975 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002976 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Steve Naroff3cc4af82007-12-16 21:42:28 +00002978 // Perform default conversions.
2979 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002980
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002981 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002982 assert(!BaseType->isDependentType());
2983
2984 DeclarationName MemberName = R.getLookupName();
2985 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002986
2987 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002988 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002989 // function. Suggest the addition of those parentheses, build the
2990 // call, and continue on.
2991 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2992 if (const FunctionProtoType *Fun
2993 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2994 QualType ResultTy = Fun->getResultType();
2995 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002996 ((!IsArrow && ResultTy->isRecordType()) ||
2997 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002998 ResultTy->getAs<PointerType>()->getPointeeType()
2999 ->isRecordType()))) {
3000 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
3001 Diag(Loc, diag::err_member_reference_needs_call)
3002 << QualType(Fun, 0)
Douglas Gregor849b2432010-03-31 17:46:05 +00003003 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003004
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003005 OwningExprResult NewBase
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003006 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003007 MultiExprArg(*this, 0, 0), 0, Loc);
Douglas Gregorf918b832010-06-21 22:46:46 +00003008 BaseExpr = 0;
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003009 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00003010 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003011
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003012 BaseExpr = NewBase.takeAs<Expr>();
3013 DefaultFunctionArrayConversion(BaseExpr);
3014 BaseType = BaseExpr->getType();
3015 }
3016 }
3017 }
3018
David Chisnall0f436562009-08-17 16:35:33 +00003019 // If this is an Objective-C pseudo-builtin and a definition is provided then
3020 // use that.
3021 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00003022 if (IsArrow) {
3023 // Handle the following exceptional case PObj->isa.
3024 if (const ObjCObjectPointerType *OPT =
3025 BaseType->getAs<ObjCObjectPointerType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00003026 if (OPT->getObjectType()->isObjCId() &&
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00003027 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003028 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
3029 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00003030 }
3031 }
David Chisnall0f436562009-08-17 16:35:33 +00003032 // We have an 'id' type. Rather than fall through, we check if this
3033 // is a reference to 'isa'.
3034 if (BaseType != Context.ObjCIdRedefinitionType) {
3035 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003036 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003037 }
David Chisnall0f436562009-08-17 16:35:33 +00003038 }
John McCall129e2df2009-11-30 22:42:35 +00003039
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00003040 // If this is an Objective-C pseudo-builtin and a definition is provided then
3041 // use that.
3042 if (Context.isObjCSelType(BaseType)) {
3043 // We have an 'SEL' type. Rather than fall through, we check if this
3044 // is a reference to 'sel_id'.
3045 if (BaseType != Context.ObjCSelRedefinitionType) {
3046 BaseType = Context.ObjCSelRedefinitionType;
3047 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
3048 }
3049 }
John McCall129e2df2009-11-30 22:42:35 +00003050
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003051 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003052
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003053 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00003054 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003055 // Also must look for a getter name which uses property syntax.
3056 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3057 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3058 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3059 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3060 ObjCMethodDecl *Getter;
3061 // FIXME: need to also look locally in the implementation.
3062 if ((Getter = IFace->lookupClassMethod(Sel))) {
3063 // Check the use of this method.
3064 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3065 return ExprError();
3066 }
3067 // If we found a getter then this may be a valid dot-reference, we
3068 // will look for the matching setter, in case it is needed.
3069 Selector SetterSel =
3070 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3071 PP.getSelectorTable(), Member);
3072 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3073 if (!Setter) {
3074 // If this reference is in an @implementation, also check for 'private'
3075 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00003076 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003077 }
3078 // Look through local category implementations associated with the class.
3079 if (!Setter)
3080 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003081
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003082 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3083 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003084
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003085 if (Getter || Setter) {
3086 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003087
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003088 if (Getter)
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003089 PType = Getter->getSendResultType();
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003090 else
3091 // Get the expression type from Setter's incoming parameter.
3092 PType = (*(Setter->param_end() -1))->getType();
3093 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003094 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003095 PType,
3096 Setter, MemberLoc, BaseExpr));
3097 }
3098 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3099 << MemberName << BaseType);
3100 }
3101 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003102
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003103 if (BaseType->isObjCClassType() &&
3104 BaseType != Context.ObjCClassRedefinitionType) {
3105 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003106 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003107 }
Mike Stump1eb44332009-09-09 15:08:12 +00003108
John McCall129e2df2009-11-30 22:42:35 +00003109 if (IsArrow) {
3110 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003111 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00003112 else if (BaseType->isObjCObjectPointerType())
3113 ;
John McCall812c1542009-12-07 22:46:59 +00003114 else if (BaseType->isRecordType()) {
3115 // Recover from arrow accesses to records, e.g.:
3116 // struct MyRecord foo;
3117 // foo->bar
3118 // This is actually well-formed in C++ if MyRecord has an
3119 // overloaded operator->, but that should have been dealt with
3120 // by now.
3121 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3122 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003123 << FixItHint::CreateReplacement(OpLoc, ".");
John McCall812c1542009-12-07 22:46:59 +00003124 IsArrow = false;
3125 } else {
John McCall129e2df2009-11-30 22:42:35 +00003126 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3127 << BaseType << BaseExpr->getSourceRange();
3128 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00003129 }
John McCall812c1542009-12-07 22:46:59 +00003130 } else {
3131 // Recover from dot accesses to pointers, e.g.:
3132 // type *foo;
3133 // foo.bar
3134 // This is actually well-formed in two cases:
3135 // - 'type' is an Objective C type
3136 // - 'bar' is a pseudo-destructor name which happens to refer to
3137 // the appropriate pointer type
3138 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3139 const PointerType *PT = BaseType->getAs<PointerType>();
3140 if (PT && PT->getPointeeType()->isRecordType()) {
3141 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3142 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003143 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall812c1542009-12-07 22:46:59 +00003144 BaseType = PT->getPointeeType();
3145 IsArrow = true;
3146 }
3147 }
John McCall129e2df2009-11-30 22:42:35 +00003148 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003149
John McCallc12c5bb2010-05-15 11:32:37 +00003150 // Handle field access to simple records.
Ted Kremenek6217b802009-07-29 21:53:49 +00003151 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00003152 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
John McCallad00b772010-06-16 08:42:20 +00003153 RTy, OpLoc, SS, HasTemplateArgs))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003154 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003155 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003156 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003157
Chris Lattnera38e6b12008-07-21 04:59:05 +00003158 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3159 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00003160 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003161 (!IsArrow && BaseType->isObjCObjectType())) {
John McCall183700f2009-09-21 23:43:11 +00003162 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
John McCallc12c5bb2010-05-15 11:32:37 +00003163 ObjCInterfaceDecl *IDecl =
3164 OPT ? OPT->getInterfaceDecl()
3165 : BaseType->getAs<ObjCObjectType>()->getInterface();
3166 if (IDecl) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003167 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3168
Steve Naroffc70e8d92009-07-16 00:25:06 +00003169 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00003170 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003172 if (!IV) {
3173 // Attempt to correct for typos in ivar names.
3174 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3175 LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00003176 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003177 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003178 Diag(R.getNameLoc(),
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003179 diag::err_typecheck_member_reference_ivar_suggest)
3180 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregor849b2432010-03-31 17:46:05 +00003181 << FixItHint::CreateReplacement(R.getNameLoc(),
3182 IV->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003183 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003184 << IV->getDeclName();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003185 } else {
3186 Res.clear();
3187 Res.setLookupName(Member);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003188 }
3189 }
3190
Steve Naroffc70e8d92009-07-16 00:25:06 +00003191 if (IV) {
3192 // If the decl being referenced had an error, return an error for this
3193 // sub-expr without emitting another error, in order to avoid cascading
3194 // error cases.
3195 if (IV->isInvalidDecl())
3196 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003197
Steve Naroffc70e8d92009-07-16 00:25:06 +00003198 // Check whether we can reference this field.
3199 if (DiagnoseUseOfDecl(IV, MemberLoc))
3200 return ExprError();
3201 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3202 IV->getAccessControl() != ObjCIvarDecl::Package) {
3203 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3204 if (ObjCMethodDecl *MD = getCurMethodDecl())
3205 ClassOfMethodDecl = MD->getClassInterface();
3206 else if (ObjCImpDecl && getCurFunctionDecl()) {
3207 // Case of a c-function declared inside an objc implementation.
3208 // FIXME: For a c-style function nested inside an objc implementation
3209 // class, there is no implementation context available, so we pass
3210 // down the context as argument to this routine. Ideally, this context
3211 // need be passed down in the AST node and somehow calculated from the
3212 // AST for a function decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003213 if (ObjCImplementationDecl *IMPD =
John McCalld226f652010-08-21 09:40:31 +00003214 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
Steve Naroffc70e8d92009-07-16 00:25:06 +00003215 ClassOfMethodDecl = IMPD->getClassInterface();
3216 else if (ObjCCategoryImplDecl* CatImplClass =
John McCalld226f652010-08-21 09:40:31 +00003217 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
Steve Naroffc70e8d92009-07-16 00:25:06 +00003218 ClassOfMethodDecl = CatImplClass->getClassInterface();
3219 }
Mike Stump1eb44332009-09-09 15:08:12 +00003220
3221 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3222 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00003223 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00003224 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003225 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003226 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3227 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00003228 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003229 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00003230 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003231
3232 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3233 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00003234 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00003235 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003236 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003237 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00003238 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00003239 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003240 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003241 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00003242 if (!IsArrow && (BaseType->isObjCIdType() ||
3243 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00003244 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003245 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00003246
Steve Naroff14108da2009-07-10 23:34:53 +00003247 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003248 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00003249 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3250 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3251 // Check the use of this declaration
3252 if (DiagnoseUseOfDecl(PD, MemberLoc))
3253 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003254
Steve Naroff14108da2009-07-10 23:34:53 +00003255 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3256 MemberLoc, BaseExpr));
3257 }
3258 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3259 // Check the use of this method.
3260 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3261 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003262
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003263 return Owned(ObjCMessageExpr::Create(Context,
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003264 OMD->getSendResultType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00003265 OpLoc, BaseExpr, Sel,
3266 OMD, NULL, 0, MemberLoc));
Steve Naroff14108da2009-07-10 23:34:53 +00003267 }
3268 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003269
Steve Naroff14108da2009-07-10 23:34:53 +00003270 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003271 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003272 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003273
Chris Lattnera38e6b12008-07-21 04:59:05 +00003274 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3275 // pointer to a (potentially qualified) interface type.
Chris Lattner7f816522010-04-11 07:45:24 +00003276 if (!IsArrow)
3277 if (const ObjCObjectPointerType *OPT =
3278 BaseType->getAsObjCInterfacePointerType())
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00003279 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003280
Steve Narofff242b1b2009-07-24 17:54:45 +00003281 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003282 if (!IsArrow &&
John McCallc12c5bb2010-05-15 11:32:37 +00003283 BaseType->isObjCObjectType() &&
3284 BaseType->getAs<ObjCObjectType>()->isObjCId() &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003285 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003286 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003287 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003288
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003289 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003290 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003291 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003292 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3293 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003294 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003295 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003296 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003297 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003298
Douglas Gregor214f31a2009-03-27 06:00:30 +00003299 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3300 << BaseType << BaseExpr->getSourceRange();
3301
Douglas Gregor214f31a2009-03-27 06:00:30 +00003302 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003303}
3304
John McCall129e2df2009-11-30 22:42:35 +00003305/// The main callback when the parser finds something like
3306/// expression . [nested-name-specifier] identifier
3307/// expression -> [nested-name-specifier] identifier
3308/// where 'identifier' encompasses a fairly broad spectrum of
3309/// possibilities, including destructor and operator references.
3310///
3311/// \param OpKind either tok::arrow or tok::period
3312/// \param HasTrailingLParen whether the next token is '(', which
3313/// is used to diagnose mis-uses of special members that can
3314/// only be called
3315/// \param ObjCImpDecl the current ObjC @implementation decl;
3316/// this is an ugly hack around the fact that ObjC @implementations
3317/// aren't properly put in the context chain
3318Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3319 SourceLocation OpLoc,
3320 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003321 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003322 UnqualifiedId &Id,
John McCalld226f652010-08-21 09:40:31 +00003323 Decl *ObjCImpDecl,
John McCall129e2df2009-11-30 22:42:35 +00003324 bool HasTrailingLParen) {
3325 if (SS.isSet() && SS.isInvalid())
3326 return ExprError();
3327
3328 TemplateArgumentListInfo TemplateArgsBuffer;
3329
3330 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00003331 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00003332 const TemplateArgumentListInfo *TemplateArgs;
3333 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00003334 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003335
Abramo Bagnara25777432010-08-11 22:01:17 +00003336 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00003337 bool IsArrow = (OpKind == tok::arrow);
3338
3339 NamedDecl *FirstQualifierInScope
3340 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3341 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3342
3343 // This is a postfix expression, so get rid of ParenListExprs.
3344 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3345
3346 Expr *Base = BaseArg.takeAs<Expr>();
John McCallca0408f2010-08-23 06:44:23 +00003347 OwningExprResult Result;
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003348 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3349 isDependentScopeSpecifier(SS)) {
John McCallaa81e162009-12-01 22:10:20 +00003350 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003351 IsArrow, OpLoc,
3352 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003353 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003354 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003355 LookupResult R(*this, NameInfo, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00003356 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3357 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003358
John McCallad00b772010-06-16 08:42:20 +00003359 if (Result.isInvalid()) {
3360 Owned(Base);
3361 return ExprError();
3362 }
John McCall129e2df2009-11-30 22:42:35 +00003363
John McCallad00b772010-06-16 08:42:20 +00003364 if (Result.get()) {
3365 // The only way a reference to a destructor can be used is to
3366 // immediately call it, which falls into this case. If the
3367 // next token is not a '(', produce a diagnostic and build the
3368 // call now.
3369 if (!HasTrailingLParen &&
3370 Id.getKind() == UnqualifiedId::IK_DestructorName)
Abramo Bagnara25777432010-08-11 22:01:17 +00003371 return DiagnoseDtorReference(NameInfo.getLoc(), move(Result));
John McCall129e2df2009-11-30 22:42:35 +00003372
John McCallad00b772010-06-16 08:42:20 +00003373 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00003374 }
3375
John McCallaa81e162009-12-01 22:10:20 +00003376 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00003377 OpLoc, IsArrow, SS, FirstQualifierInScope,
3378 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003379 }
3380
3381 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003382}
3383
Anders Carlsson56c5e332009-08-25 03:49:14 +00003384Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3385 FunctionDecl *FD,
3386 ParmVarDecl *Param) {
3387 if (Param->hasUnparsedDefaultArg()) {
3388 Diag (CallLoc,
3389 diag::err_use_of_default_argument_to_function_declared_later) <<
3390 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003391 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003392 diag::note_default_argument_declared_here);
3393 } else {
3394 if (Param->hasUninstantiatedDefaultArg()) {
3395 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3396
3397 // Instantiate the expression.
Douglas Gregor525f96c2010-02-05 07:33:43 +00003398 MultiLevelTemplateArgumentList ArgList
3399 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003400
Douglas Gregor24bae922010-07-08 18:37:38 +00003401 std::pair<const TemplateArgument *, unsigned> Innermost
3402 = ArgList.getInnermost();
3403 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3404 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003405
John McCallce3ff2b2009-08-25 22:02:44 +00003406 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003407 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003408 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003409
Douglas Gregor65222e82009-12-23 18:19:08 +00003410 // Check the expression as an initializer for the parameter.
3411 InitializedEntity Entity
3412 = InitializedEntity::InitializeParameter(Param);
3413 InitializationKind Kind
3414 = InitializationKind::CreateCopy(Param->getLocation(),
3415 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3416 Expr *ResultE = Result.takeAs<Expr>();
3417
3418 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003419 Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003420 MultiExprArg(*this, &ResultE, 1));
Douglas Gregor65222e82009-12-23 18:19:08 +00003421 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003422 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003423
Douglas Gregor65222e82009-12-23 18:19:08 +00003424 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003425 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003426 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003427 }
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Anders Carlsson56c5e332009-08-25 03:49:14 +00003429 // If the default expression creates temporaries, we need to
3430 // push them to the current stack of expression temporaries so they'll
3431 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003432 // FIXME: We should really be rebuilding the default argument with new
3433 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003434 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3435 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003436 }
3437
3438 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003439 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003440}
3441
Douglas Gregor88a35142008-12-22 05:46:06 +00003442/// ConvertArgumentsForCall - Converts the arguments specified in
3443/// Args/NumArgs to the parameter types of the function FDecl with
3444/// function prototype Proto. Call is the call expression itself, and
3445/// Fn is the function expression. For a C++ member function, this
3446/// routine does not attempt to convert the object argument. Returns
3447/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003448bool
3449Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003450 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003451 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003452 Expr **Args, unsigned NumArgs,
3453 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003454 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003455 // assignment, to the types of the corresponding parameter, ...
3456 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003457 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003458
Douglas Gregor88a35142008-12-22 05:46:06 +00003459 // If too few arguments are available (and we don't have default
3460 // arguments for the remaining parameters), don't make the call.
3461 if (NumArgs < NumArgsInProto) {
3462 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3463 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003464 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003465 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003466 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003467 }
3468
3469 // If too many are passed and not variadic, error on the extras and drop
3470 // them.
3471 if (NumArgs > NumArgsInProto) {
3472 if (!Proto->isVariadic()) {
3473 Diag(Args[NumArgsInProto]->getLocStart(),
3474 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003475 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003476 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003477 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3478 Args[NumArgs-1]->getLocEnd());
3479 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003480 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003481 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003482 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003483 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003484 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003485 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003486 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3487 if (Fn->getType()->isBlockPointerType())
3488 CallType = VariadicBlock; // Block
3489 else if (isa<MemberExpr>(Fn))
3490 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003491 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003492 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003493 if (Invalid)
3494 return true;
3495 unsigned TotalNumArgs = AllArgs.size();
3496 for (unsigned i = 0; i < TotalNumArgs; ++i)
3497 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003498
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003499 return false;
3500}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003501
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003502bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3503 FunctionDecl *FDecl,
3504 const FunctionProtoType *Proto,
3505 unsigned FirstProtoArg,
3506 Expr **Args, unsigned NumArgs,
3507 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003508 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003509 unsigned NumArgsInProto = Proto->getNumArgs();
3510 unsigned NumArgsToCheck = NumArgs;
3511 bool Invalid = false;
3512 if (NumArgs != NumArgsInProto)
3513 // Use default arguments for missing arguments
3514 NumArgsToCheck = NumArgsInProto;
3515 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003516 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003517 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003518 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003519
Douglas Gregor88a35142008-12-22 05:46:06 +00003520 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003521 if (ArgIx < NumArgs) {
3522 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003523
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003524 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3525 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003526 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003527 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003528 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003529
Douglas Gregora188ff22009-12-22 16:09:06 +00003530 // Pass the argument
3531 ParmVarDecl *Param = 0;
3532 if (FDecl && i < FDecl->getNumParams())
3533 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003534
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003535
Douglas Gregora188ff22009-12-22 16:09:06 +00003536 InitializedEntity Entity =
3537 Param? InitializedEntity::InitializeParameter(Param)
3538 : InitializedEntity::InitializeParameter(ProtoArgType);
3539 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3540 SourceLocation(),
3541 Owned(Arg));
3542 if (ArgE.isInvalid())
3543 return true;
3544
3545 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003546 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003547 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003548
Mike Stump1eb44332009-09-09 15:08:12 +00003549 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003550 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003551 if (ArgExpr.isInvalid())
3552 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003553
Anders Carlsson56c5e332009-08-25 03:49:14 +00003554 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003555 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003556 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003557 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003558
Douglas Gregor88a35142008-12-22 05:46:06 +00003559 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003560 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003561 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00003562 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003563 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00003564 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003565 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003566 }
3567 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003568 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003569}
3570
Steve Narofff69936d2007-09-16 03:34:24 +00003571/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003572/// This provides the location of the left/right parens and a list of comma
3573/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003574Action::OwningExprResult
3575Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3576 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003577 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003578 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003579
3580 // Since this might be a postfix expression, get rid of ParenListExprs.
3581 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003582
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003583 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003584 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003585 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003586
Douglas Gregor88a35142008-12-22 05:46:06 +00003587 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003588 // If this is a pseudo-destructor expression, build the call immediately.
3589 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3590 if (NumArgs > 0) {
3591 // Pseudo-destructor calls should not have any arguments.
3592 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003593 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003594 SourceRange(Args[0]->getLocStart(),
3595 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003596
Douglas Gregora71d8192009-09-04 17:36:40 +00003597 NumArgs = 0;
3598 }
Mike Stump1eb44332009-09-09 15:08:12 +00003599
Douglas Gregora71d8192009-09-04 17:36:40 +00003600 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3601 RParenLoc));
3602 }
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Douglas Gregor17330012009-02-04 15:01:18 +00003604 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003605 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003606 // FIXME: Will need to cache the results of name lookup (including ADL) in
3607 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003608 bool Dependent = false;
3609 if (Fn->isTypeDependent())
3610 Dependent = true;
3611 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3612 Dependent = true;
3613
3614 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003615 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003616 Context.DependentTy, RParenLoc));
3617
3618 // Determine whether this is a call to an object (C++ [over.call.object]).
3619 if (Fn->getType()->isRecordType())
3620 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3621 CommaLocs, RParenLoc));
3622
John McCall129e2df2009-11-30 22:42:35 +00003623 Expr *NakedFn = Fn->IgnoreParens();
3624
3625 // Determine whether this is a call to an unresolved member function.
3626 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3627 // If lookup was unresolved but not dependent (i.e. didn't find
3628 // an unresolved using declaration), it has to be an overloaded
3629 // function set, which means it must contain either multiple
3630 // declarations (all methods or method templates) or a single
3631 // method template.
3632 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00003633 isa<FunctionTemplateDecl>(
3634 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003635 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003636
John McCallaa81e162009-12-01 22:10:20 +00003637 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3638 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003639 }
3640
Douglas Gregorfa047642009-02-04 00:32:51 +00003641 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003642 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003643 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003644 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003645 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3646 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003647 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003648
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003649 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003650 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003651 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3652 BO->getOpcode() == BinaryOperator::PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00003653 if (const FunctionProtoType *FPT
3654 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003655 QualType ResultTy = FPT->getCallResultType(Context);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003656
3657 ExprOwningPtr<CXXMemberCallExpr>
3658 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003659 NumArgs, ResultTy,
3660 RParenLoc));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003661
3662 if (CheckCallReturnType(FPT->getResultType(),
3663 BO->getRHS()->getSourceRange().getBegin(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003664 TheCall.get(), 0))
3665 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003666
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003667 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003668 RParenLoc))
3669 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003670
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003671 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3672 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003673 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003674 diag::err_typecheck_call_not_function)
3675 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003676 }
3677 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003678 }
3679
Douglas Gregorfa047642009-02-04 00:32:51 +00003680 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003681 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003682 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003683
Eli Friedmanefa42f72009-12-26 03:35:45 +00003684 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003685 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3686 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
Douglas Gregor1aae80b2010-04-14 20:27:54 +00003687 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00003688 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003689 }
Chris Lattner04421082008-04-08 04:40:51 +00003690
John McCall3b4294e2009-12-16 12:17:52 +00003691 NamedDecl *NDecl = 0;
3692 if (isa<DeclRefExpr>(NakedFn))
3693 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3694
John McCallaa81e162009-12-01 22:10:20 +00003695 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3696}
3697
John McCall3b4294e2009-12-16 12:17:52 +00003698/// BuildResolvedCallExpr - Build a call to a resolved expression,
3699/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003700/// unary-convert to an expression of function-pointer or
3701/// block-pointer type.
3702///
3703/// \param NDecl the declaration being called, if available
3704Sema::OwningExprResult
3705Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3706 SourceLocation LParenLoc,
3707 Expr **Args, unsigned NumArgs,
3708 SourceLocation RParenLoc) {
3709 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3710
Chris Lattner04421082008-04-08 04:40:51 +00003711 // Promote the function operand.
3712 UsualUnaryConversions(Fn);
3713
Chris Lattner925e60d2007-12-28 05:29:59 +00003714 // Make the call expr early, before semantic checks. This guarantees cleanup
3715 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003716 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3717 Args, NumArgs,
3718 Context.BoolTy,
3719 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003720
Steve Naroffdd972f22008-09-05 22:11:13 +00003721 const FunctionType *FuncT;
3722 if (!Fn->getType()->isBlockPointerType()) {
3723 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3724 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003725 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003726 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003727 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3728 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003729 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003730 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003731 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003732 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003733 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003734 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003735 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3736 << Fn->getType() << Fn->getSourceRange());
3737
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003738 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003739 if (CheckCallReturnType(FuncT->getResultType(),
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003740 Fn->getSourceRange().getBegin(), TheCall.get(),
3741 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003742 return ExprError();
3743
Chris Lattner925e60d2007-12-28 05:29:59 +00003744 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003745 TheCall->setType(FuncT->getCallResultType(Context));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003746
Douglas Gregor72564e72009-02-26 23:50:07 +00003747 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003748 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003749 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003750 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003751 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003752 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003753
Douglas Gregor74734d52009-04-02 15:37:10 +00003754 if (FDecl) {
3755 // Check if we have too few/too many template arguments, based
3756 // on our knowledge of the function definition.
3757 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003758 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003759 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003760 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003761 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3762 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3763 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3764 }
3765 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003766 }
3767
Steve Naroffb291ab62007-08-28 23:30:39 +00003768 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003769 for (unsigned i = 0; i != NumArgs; i++) {
3770 Expr *Arg = Args[i];
3771 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003772 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3773 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003774 PDiag(diag::err_call_incomplete_argument)
3775 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003776 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003777 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003778 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003779 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003780
Douglas Gregor88a35142008-12-22 05:46:06 +00003781 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3782 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003783 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3784 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003785
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003786 // Check for sentinels
3787 if (NDecl)
3788 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003789
Chris Lattner59907c42007-08-10 20:18:51 +00003790 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003791 if (FDecl) {
3792 if (CheckFunctionCall(FDecl, TheCall.get()))
3793 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003794
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003795 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003796 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3797 } else if (NDecl) {
3798 if (CheckBlockCall(NDecl, TheCall.get()))
3799 return ExprError();
3800 }
Chris Lattner59907c42007-08-10 20:18:51 +00003801
Anders Carlssonec74c592009-08-16 03:06:32 +00003802 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003803}
3804
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003805Action::OwningExprResult
3806Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3807 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003808 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003809 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003810 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003811
3812 TypeSourceInfo *TInfo;
3813 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3814 if (!TInfo)
3815 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3816
3817 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3818}
3819
3820Action::OwningExprResult
3821Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3822 SourceLocation RParenLoc, ExprArg InitExpr) {
3823 QualType literalType = TInfo->getType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003824 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003825
Eli Friedman6223c222008-05-20 05:22:08 +00003826 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003827 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003828 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3829 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003830 } else if (!literalType->isDependentType() &&
3831 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003832 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003833 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003834 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003835 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003836
Douglas Gregor99a2e602009-12-16 01:38:02 +00003837 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003838 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003839 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003840 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00003841 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003842 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3843 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003844 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003845 &literalType);
3846 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003847 return ExprError();
Eli Friedman08544622009-12-22 02:35:53 +00003848 InitExpr.release();
3849 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffe9b12192008-01-14 18:19:28 +00003850
Chris Lattner371f2582008-12-04 23:50:19 +00003851 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003852 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003853 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003854 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003855 }
Eli Friedman08544622009-12-22 02:35:53 +00003856
3857 Result.release();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003858
John McCall1d7d8d62010-01-19 22:33:45 +00003859 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003860 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003861}
3862
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003863Action::OwningExprResult
3864Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003865 SourceLocation RBraceLoc) {
3866 unsigned NumInit = initlist.size();
3867 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003868
Steve Naroff08d92e42007-09-15 18:49:24 +00003869 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003870 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003871
Ted Kremenek709210f2010-04-13 23:39:13 +00003872 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3873 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003874 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003875 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003876}
3877
Anders Carlsson82debc72009-10-18 18:12:03 +00003878static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3879 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003880 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003881 return CastExpr::CK_NoOp;
3882
3883 if (SrcTy->hasPointerRepresentation()) {
3884 if (DestTy->hasPointerRepresentation())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003885 return DestTy->isObjCObjectPointerType() ?
3886 CastExpr::CK_AnyPointerToObjCPointerCast :
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003887 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003888 if (DestTy->isIntegerType())
3889 return CastExpr::CK_PointerToIntegral;
3890 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003891
Anders Carlsson82debc72009-10-18 18:12:03 +00003892 if (SrcTy->isIntegerType()) {
3893 if (DestTy->isIntegerType())
3894 return CastExpr::CK_IntegralCast;
3895 if (DestTy->hasPointerRepresentation())
3896 return CastExpr::CK_IntegralToPointer;
3897 if (DestTy->isRealFloatingType())
3898 return CastExpr::CK_IntegralToFloating;
3899 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003900
Anders Carlsson82debc72009-10-18 18:12:03 +00003901 if (SrcTy->isRealFloatingType()) {
3902 if (DestTy->isRealFloatingType())
3903 return CastExpr::CK_FloatingCast;
3904 if (DestTy->isIntegerType())
3905 return CastExpr::CK_FloatingToIntegral;
3906 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003907
Anders Carlsson82debc72009-10-18 18:12:03 +00003908 // FIXME: Assert here.
3909 // assert(false && "Unhandled cast combination!");
3910 return CastExpr::CK_Unknown;
3911}
3912
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003913/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003914bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003915 CastExpr::CastKind& Kind,
John McCallf871d0c2010-08-07 06:22:56 +00003916 CXXCastPath &BasePath,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003917 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003918 if (getLangOptions().CPlusPlus)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003919 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
3920 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003921
Douglas Gregora873dfc2010-02-03 00:27:59 +00003922 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003923
3924 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3925 // type needs to be scalar.
3926 if (castType->isVoidType()) {
3927 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003928 Kind = CastExpr::CK_ToVoid;
3929 return false;
3930 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003931
Eli Friedman8d438082010-07-17 20:43:49 +00003932 if (RequireCompleteType(TyR.getBegin(), castType,
3933 diag::err_typecheck_cast_to_incomplete))
3934 return true;
3935
Anders Carlssonebeaf202009-10-16 02:35:04 +00003936 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003937 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003938 (castType->isStructureType() || castType->isUnionType())) {
3939 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003940 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003941 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3942 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003943 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003944 return false;
3945 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003946
Anders Carlssonc3516322009-10-16 02:48:28 +00003947 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003948 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003949 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003950 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003951 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003952 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003953 if (Context.hasSameUnqualifiedType(Field->getType(),
Douglas Gregora4923eb2009-11-16 21:35:15 +00003954 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003955 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3956 << castExpr->getSourceRange();
3957 break;
3958 }
3959 }
3960 if (Field == FieldEnd)
3961 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3962 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003963 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003964 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003965 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003966
Anders Carlssonc3516322009-10-16 02:48:28 +00003967 // Reject any other conversions to non-scalar types.
3968 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3969 << castType << castExpr->getSourceRange();
3970 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003971
3972 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00003973 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003974 return Diag(castExpr->getLocStart(),
3975 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003976 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003977 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003978
3979 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00003980 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003981
Anders Carlssonc3516322009-10-16 02:48:28 +00003982 if (castType->isVectorType())
3983 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3984 if (castExpr->getType()->isVectorType())
3985 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3986
Anders Carlsson16a89042009-10-16 05:23:41 +00003987 if (isa<ObjCSelectorExpr>(castExpr))
3988 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003989
Anders Carlssonc3516322009-10-16 02:48:28 +00003990 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003991 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00003992 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003993 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00003994 return Diag(castExpr->getLocStart(),
3995 diag::err_cast_pointer_from_non_pointer_int)
3996 << castExprType << castExpr->getSourceRange();
3997 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00003998 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00003999 return Diag(castExpr->getLocStart(),
4000 diag::err_cast_pointer_to_non_pointer_int)
4001 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004002 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004003
4004 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
John McCallb7f4ffe2010-08-12 21:44:57 +00004005
4006 if (Kind == CastExpr::CK_Unknown || Kind == CastExpr::CK_BitCast)
4007 CheckCastAlign(castExpr, castType, TyR);
4008
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004009 return false;
4010}
4011
Anders Carlssonc3516322009-10-16 02:48:28 +00004012bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4013 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004014 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004015
Anders Carlssona64db8f2007-11-27 05:51:55 +00004016 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004017 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004018 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004019 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004020 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004021 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004022 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004023 } else
4024 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004025 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004026 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004027
Anders Carlssonc3516322009-10-16 02:48:28 +00004028 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004029 return false;
4030}
4031
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004032bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
Anders Carlsson16a89042009-10-16 05:23:41 +00004033 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004034 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004035
Anders Carlsson16a89042009-10-16 05:23:41 +00004036 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004037
Nate Begeman9b10da62009-06-27 22:05:55 +00004038 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4039 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004040 if (SrcTy->isVectorType()) {
4041 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4042 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4043 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00004044 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00004045 return false;
4046 }
4047
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004048 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004049 // conversion will take place first from scalar to elt type, and then
4050 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004051 if (SrcTy->isPointerType())
4052 return Diag(R.getBegin(),
4053 diag::err_invalid_conversion_between_vector_and_scalar)
4054 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004055
4056 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4057 ImpCastExprToType(CastExpr, DestElemTy,
4058 getScalarCastKind(Context, SrcTy, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004059
Anders Carlsson16a89042009-10-16 05:23:41 +00004060 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00004061 return false;
4062}
4063
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004064Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00004065Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004066 SourceLocation RParenLoc, ExprArg Op) {
4067 assert((Ty != 0) && (Op.get() != 0) &&
4068 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004069
John McCall9d125032010-01-15 18:39:57 +00004070 TypeSourceInfo *castTInfo;
4071 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4072 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00004073 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00004074
Nate Begeman2ef13e52009-08-10 23:49:36 +00004075 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallb042fdf2010-01-15 18:56:44 +00004076 Expr *castExpr = (Expr *)Op.get();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004077 if (isa<ParenListExpr>(castExpr))
John McCall42f56b52010-01-18 19:35:47 +00004078 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
4079 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00004080
4081 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
4082}
4083
4084Action::OwningExprResult
4085Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
4086 SourceLocation RParenLoc, ExprArg Op) {
4087 Expr *castExpr = static_cast<Expr*>(Op.get());
4088
John McCallb042fdf2010-01-15 18:56:44 +00004089 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00004090 CXXCastPath BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00004091 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004092 Kind, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004093 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004094
Douglas Gregord6e44a32010-04-16 22:09:46 +00004095 Op.release();
John McCallf871d0c2010-08-07 06:22:56 +00004096 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +00004097 Ty->getType().getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +00004098 Kind, castExpr, &BasePath, Ty,
4099 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004100}
4101
Nate Begeman2ef13e52009-08-10 23:49:36 +00004102/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4103/// of comma binary operators.
4104Action::OwningExprResult
4105Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
4106 Expr *expr = EA.takeAs<Expr>();
4107 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4108 if (!E)
4109 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004110
John McCallca0408f2010-08-23 06:44:23 +00004111 OwningExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Nate Begeman2ef13e52009-08-10 23:49:36 +00004113 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4114 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
4115 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Nate Begeman2ef13e52009-08-10 23:49:36 +00004117 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
4118}
4119
4120Action::OwningExprResult
4121Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4122 SourceLocation RParenLoc, ExprArg Op,
John McCall42f56b52010-01-18 19:35:47 +00004123 TypeSourceInfo *TInfo) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004124 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCall42f56b52010-01-18 19:35:47 +00004125 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00004126 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004127
John Thompson8bb59a82010-06-30 22:55:51 +00004128 // Check for an altivec literal,
4129 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004130 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4131 if (PE->getNumExprs() == 0) {
4132 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4133 return ExprError();
4134 }
John Thompson8bb59a82010-06-30 22:55:51 +00004135 if (PE->getNumExprs() == 1) {
4136 if (!PE->getExpr(0)->getType()->isVectorType())
4137 isAltiVecLiteral = true;
4138 }
4139 else
4140 isAltiVecLiteral = true;
4141 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00004142
John Thompson8bb59a82010-06-30 22:55:51 +00004143 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4144 // then handle it as such.
4145 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004146 llvm::SmallVector<Expr *, 8> initExprs;
4147 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4148 initExprs.push_back(PE->getExpr(i));
4149
4150 // FIXME: This means that pretty-printing the final AST will produce curly
4151 // braces instead of the original commas.
4152 Op.release();
Ted Kremenek709210f2010-04-13 23:39:13 +00004153 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4154 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00004155 initExprs.size(), RParenLoc);
4156 E->setType(Ty);
John McCall42f56b52010-01-18 19:35:47 +00004157 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004158 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004159 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004160 // sequence of BinOp comma operators.
4161 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCall42f56b52010-01-18 19:35:47 +00004162 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004163 }
4164}
4165
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004166Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004167 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004168 MultiExprArg Val,
4169 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004170 unsigned nexprs = Val.size();
4171 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004172 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4173 Expr *expr;
4174 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4175 expr = new (Context) ParenExpr(L, R, exprs[0]);
4176 else
4177 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004178 return Owned(expr);
4179}
4180
Sebastian Redl28507842009-02-26 14:39:58 +00004181/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4182/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004183/// C99 6.5.15
4184QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4185 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004186 // C++ is sufficiently different to merit its own checker.
4187 if (getLangOptions().CPlusPlus)
4188 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4189
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004190 UsualUnaryConversions(Cond);
4191 UsualUnaryConversions(LHS);
4192 UsualUnaryConversions(RHS);
4193 QualType CondTy = Cond->getType();
4194 QualType LHSTy = LHS->getType();
4195 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004196
Reid Spencer5f016e22007-07-11 17:01:13 +00004197 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004198 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4199 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4200 << CondTy;
4201 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004202 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004203
Chris Lattner70d67a92008-01-06 22:42:25 +00004204 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004205 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4206 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004207
Chris Lattner70d67a92008-01-06 22:42:25 +00004208 // If both operands have arithmetic type, do the usual arithmetic conversions
4209 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004210 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4211 UsualArithmeticConversions(LHS, RHS);
4212 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004213 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004214
Chris Lattner70d67a92008-01-06 22:42:25 +00004215 // If both operands are the same structure or union type, the result is that
4216 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004217 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4218 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004219 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004220 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004221 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004222 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004223 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004224 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004225
Chris Lattner70d67a92008-01-06 22:42:25 +00004226 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004227 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004228 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4229 if (!LHSTy->isVoidType())
4230 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4231 << RHS->getSourceRange();
4232 if (!RHSTy->isVoidType())
4233 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4234 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004235 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4236 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004237 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004238 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004239 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4240 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004241 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004242 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004243 // promote the null to a pointer.
4244 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004245 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004246 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004247 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004248 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004249 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004250 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004251 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004252
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004253 // All objective-c pointer type analysis is done here.
4254 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4255 QuestionLoc);
4256 if (!compositeType.isNull())
4257 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004258
4259
Steve Naroff7154a772009-07-01 14:36:47 +00004260 // Handle block pointer types.
4261 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4262 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4263 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4264 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004265 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4266 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004267 return destType;
4268 }
4269 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004270 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004271 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004272 }
Steve Naroff7154a772009-07-01 14:36:47 +00004273 // We have 2 block pointer types.
4274 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4275 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004276 return LHSTy;
4277 }
Steve Naroff7154a772009-07-01 14:36:47 +00004278 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004279 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4280 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004281
Steve Naroff7154a772009-07-01 14:36:47 +00004282 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4283 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004284 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004285 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004286 // In this situation, we assume void* type. No especially good
4287 // reason, but this is what gcc does, and we do have to pick
4288 // to get a consistent AST.
4289 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004290 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4291 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004292 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004293 }
Steve Naroff7154a772009-07-01 14:36:47 +00004294 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004295 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4296 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004297 return LHSTy;
4298 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004299
Steve Naroff7154a772009-07-01 14:36:47 +00004300 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4301 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4302 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004303 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4304 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004305
4306 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4307 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4308 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004309 QualType destPointee
4310 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004311 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004312 // Add qualifiers if necessary.
4313 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4314 // Promote to void*.
4315 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004316 return destType;
4317 }
4318 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004319 QualType destPointee
4320 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004321 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004322 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004323 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004324 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004325 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004326 return destType;
4327 }
4328
4329 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4330 // Two identical pointer types are always compatible.
4331 return LHSTy;
4332 }
4333 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4334 rhptee.getUnqualifiedType())) {
4335 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4336 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4337 // In this situation, we assume void* type. No especially good
4338 // reason, but this is what gcc does, and we do have to pick
4339 // to get a consistent AST.
4340 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004341 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4342 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004343 return incompatTy;
4344 }
4345 // The pointer types are compatible.
4346 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4347 // differently qualified versions of compatible types, the result type is
4348 // a pointer to an appropriately qualified version of the *composite*
4349 // type.
4350 // FIXME: Need to calculate the composite type.
4351 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004352 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4353 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004354 return LHSTy;
4355 }
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Steve Naroff7154a772009-07-01 14:36:47 +00004357 // GCC compatibility: soften pointer/integer mismatch.
4358 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4359 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4360 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004361 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004362 return RHSTy;
4363 }
4364 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4365 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4366 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004367 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004368 return LHSTy;
4369 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004370
Chris Lattner70d67a92008-01-06 22:42:25 +00004371 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004372 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4373 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004374 return QualType();
4375}
4376
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004377/// FindCompositeObjCPointerType - Helper method to find composite type of
4378/// two objective-c pointer types of the two input expressions.
4379QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4380 SourceLocation QuestionLoc) {
4381 QualType LHSTy = LHS->getType();
4382 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004383
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004384 // Handle things like Class and struct objc_class*. Here we case the result
4385 // to the pseudo-builtin, because that will be implicitly cast back to the
4386 // redefinition type if an attempt is made to access its fields.
4387 if (LHSTy->isObjCClassType() &&
4388 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4389 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4390 return LHSTy;
4391 }
4392 if (RHSTy->isObjCClassType() &&
4393 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4394 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4395 return RHSTy;
4396 }
4397 // And the same for struct objc_object* / id
4398 if (LHSTy->isObjCIdType() &&
4399 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4400 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4401 return LHSTy;
4402 }
4403 if (RHSTy->isObjCIdType() &&
4404 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4405 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4406 return RHSTy;
4407 }
4408 // And the same for struct objc_selector* / SEL
4409 if (Context.isObjCSelType(LHSTy) &&
4410 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4411 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4412 return LHSTy;
4413 }
4414 if (Context.isObjCSelType(RHSTy) &&
4415 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4416 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4417 return RHSTy;
4418 }
4419 // Check constraints for Objective-C object pointers types.
4420 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004421
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004422 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4423 // Two identical object pointer types are always compatible.
4424 return LHSTy;
4425 }
4426 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4427 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4428 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004429
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004430 // If both operands are interfaces and either operand can be
4431 // assigned to the other, use that type as the composite
4432 // type. This allows
4433 // xxx ? (A*) a : (B*) b
4434 // where B is a subclass of A.
4435 //
4436 // Additionally, as for assignment, if either type is 'id'
4437 // allow silent coercion. Finally, if the types are
4438 // incompatible then make sure to use 'id' as the composite
4439 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004440
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004441 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4442 // It could return the composite type.
4443 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4444 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4445 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4446 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4447 } else if ((LHSTy->isObjCQualifiedIdType() ||
4448 RHSTy->isObjCQualifiedIdType()) &&
4449 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4450 // Need to handle "id<xx>" explicitly.
4451 // GCC allows qualified id and any Objective-C type to devolve to
4452 // id. Currently localizing to here until clear this should be
4453 // part of ObjCQualifiedIdTypesAreCompatible.
4454 compositeType = Context.getObjCIdType();
4455 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4456 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004457 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004458 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4459 ;
4460 else {
4461 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4462 << LHSTy << RHSTy
4463 << LHS->getSourceRange() << RHS->getSourceRange();
4464 QualType incompatTy = Context.getObjCIdType();
4465 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4466 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4467 return incompatTy;
4468 }
4469 // The object pointer types are compatible.
4470 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4471 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4472 return compositeType;
4473 }
4474 // Check Objective-C object pointer types and 'void *'
4475 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4476 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4477 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4478 QualType destPointee
4479 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4480 QualType destType = Context.getPointerType(destPointee);
4481 // Add qualifiers if necessary.
4482 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4483 // Promote to void*.
4484 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4485 return destType;
4486 }
4487 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4488 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4489 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4490 QualType destPointee
4491 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4492 QualType destType = Context.getPointerType(destPointee);
4493 // Add qualifiers if necessary.
4494 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4495 // Promote to void*.
4496 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4497 return destType;
4498 }
4499 return QualType();
4500}
4501
Steve Narofff69936d2007-09-16 03:34:24 +00004502/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004503/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004504Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4505 SourceLocation ColonLoc,
4506 ExprArg Cond, ExprArg LHS,
4507 ExprArg RHS) {
4508 Expr *CondExpr = (Expr *) Cond.get();
4509 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004510
4511 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4512 // was the condition.
4513 bool isLHSNull = LHSExpr == 0;
4514 if (isLHSNull)
4515 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004516
4517 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004518 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004519 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004520 return ExprError();
4521
4522 Cond.release();
4523 LHS.release();
4524 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004525 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004526 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004527 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004528}
4529
Reid Spencer5f016e22007-07-11 17:01:13 +00004530// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004531// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004532// routine is it effectively iqnores the qualifiers on the top level pointee.
4533// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4534// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004535Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004536Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4537 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004538
David Chisnall0f436562009-08-17 16:35:33 +00004539 if ((lhsType->isObjCClassType() &&
4540 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4541 (rhsType->isObjCClassType() &&
4542 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4543 return Compatible;
4544 }
4545
Reid Spencer5f016e22007-07-11 17:01:13 +00004546 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004547 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4548 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004549
Reid Spencer5f016e22007-07-11 17:01:13 +00004550 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004551 lhptee = Context.getCanonicalType(lhptee);
4552 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004553
Chris Lattner5cf216b2008-01-04 18:04:52 +00004554 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004555
4556 // C99 6.5.16.1p1: This following citation is common to constraints
4557 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4558 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004559 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004560 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004561 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004562
Mike Stumpeed9cac2009-02-19 03:04:26 +00004563 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4564 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004565 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004566 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004567 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004568 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004569
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004570 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004571 assert(rhptee->isFunctionType());
4572 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004573 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004574
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004575 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004576 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004577 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004578
4579 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004580 assert(lhptee->isFunctionType());
4581 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004582 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004583 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004584 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004585 lhptee = lhptee.getUnqualifiedType();
4586 rhptee = rhptee.getUnqualifiedType();
4587 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4588 // Check if the pointee types are compatible ignoring the sign.
4589 // We explicitly check for char so that we catch "char" vs
4590 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004591 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004592 lhptee = Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00004593 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004594 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004595
Chris Lattner6a2b9262009-10-17 20:33:28 +00004596 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004597 rhptee = Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00004598 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004599 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004600
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004601 if (lhptee == rhptee) {
4602 // Types are compatible ignoring the sign. Qualifier incompatibility
4603 // takes priority over sign incompatibility because the sign
4604 // warning can be disabled.
4605 if (ConvTy != Compatible)
4606 return ConvTy;
4607 return IncompatiblePointerSign;
4608 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004609
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004610 // If we are a multi-level pointer, it's possible that our issue is simply
4611 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4612 // the eventual target type is the same and the pointers have the same
4613 // level of indirection, this must be the issue.
4614 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4615 do {
4616 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4617 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004618
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004619 lhptee = Context.getCanonicalType(lhptee);
4620 rhptee = Context.getCanonicalType(rhptee);
4621 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004622
Douglas Gregora4923eb2009-11-16 21:35:15 +00004623 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004624 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004625 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004626
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004627 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004628 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004629 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004630 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004631}
4632
Steve Naroff1c7d0672008-09-04 15:10:53 +00004633/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4634/// block pointer types are compatible or whether a block and normal pointer
4635/// are compatible. It is more restrict than comparing two function pointer
4636// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004637Sema::AssignConvertType
4638Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004639 QualType rhsType) {
4640 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004641
Steve Naroff1c7d0672008-09-04 15:10:53 +00004642 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004643 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4644 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004645
Steve Naroff1c7d0672008-09-04 15:10:53 +00004646 // make sure we operate on the canonical type
4647 lhptee = Context.getCanonicalType(lhptee);
4648 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004649
Steve Naroff1c7d0672008-09-04 15:10:53 +00004650 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004651
Steve Naroff1c7d0672008-09-04 15:10:53 +00004652 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004653 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004654 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004655
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004656 if (!getLangOptions().CPlusPlus) {
4657 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4658 return IncompatibleBlockPointer;
4659 }
4660 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004661 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004662 return ConvTy;
4663}
4664
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004665/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4666/// for assignment compatibility.
4667Sema::AssignConvertType
4668Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004669 if (lhsType->isObjCBuiltinType()) {
4670 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004671 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4672 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004673 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004674 return Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004675 }
4676 if (rhsType->isObjCBuiltinType()) {
4677 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004678 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4679 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004680 return IncompatiblePointer;
4681 return Compatible;
4682 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004683 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004684 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004685 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004686 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4687 // make sure we operate on the canonical type
4688 lhptee = Context.getCanonicalType(lhptee);
4689 rhptee = Context.getCanonicalType(rhptee);
4690 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4691 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004692
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004693 if (Context.typesAreCompatible(lhsType, rhsType))
4694 return Compatible;
4695 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4696 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004697 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004698}
4699
Mike Stumpeed9cac2009-02-19 03:04:26 +00004700/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4701/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004702/// pointers. Here are some objectionable examples that GCC considers warnings:
4703///
4704/// int a, *pint;
4705/// short *pshort;
4706/// struct foo *pfoo;
4707///
4708/// pint = pshort; // warning: assignment from incompatible pointer type
4709/// a = pint; // warning: assignment makes integer from pointer without a cast
4710/// pint = a; // warning: assignment makes pointer from integer without a cast
4711/// pint = pfoo; // warning: assignment from incompatible pointer type
4712///
4713/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004714/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004715///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004716Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004717Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004718 // Get canonical types. We're not formatting these types, just comparing
4719 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004720 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4721 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004722
4723 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004724 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004725
David Chisnall0f436562009-08-17 16:35:33 +00004726 if ((lhsType->isObjCClassType() &&
4727 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4728 (rhsType->isObjCClassType() &&
4729 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4730 return Compatible;
4731 }
4732
Douglas Gregor9d293df2008-10-28 00:22:11 +00004733 // If the left-hand side is a reference type, then we are in a
4734 // (rare!) case where we've allowed the use of references in C,
4735 // e.g., as a parameter type in a built-in function. In this case,
4736 // just make sure that the type referenced is compatible with the
4737 // right-hand side type. The caller is responsible for adjusting
4738 // lhsType so that the resulting expression does not have reference
4739 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004740 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004741 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004742 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004743 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004744 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004745 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4746 // to the same ExtVector type.
4747 if (lhsType->isExtVectorType()) {
4748 if (rhsType->isExtVectorType())
4749 return lhsType == rhsType ? Compatible : Incompatible;
Douglas Gregor00619622010-06-22 23:41:02 +00004750 if (rhsType->isArithmeticType())
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004751 return Compatible;
4752 }
Mike Stump1eb44332009-09-09 15:08:12 +00004753
Nate Begemanbe2341d2008-07-14 18:02:46 +00004754 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00004755 if (lhsType->isVectorType() && rhsType->isVectorType()) {
4756 // If we are allowing lax vector conversions, and LHS and RHS are both
4757 // vectors, the total size only needs to be the same. This is a bitcast;
4758 // no bits are changed but the result type is different.
4759 if (getLangOptions().LaxVectorConversions &&
4760 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004761 return IncompatibleVectors;
Douglas Gregor255210e2010-08-06 10:14:59 +00004762
4763 // Allow assignments of an AltiVec vector type to an equivalent GCC
4764 // vector type and vice versa
4765 if (Context.areCompatibleVectorTypes(lhsType, rhsType))
4766 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004767 }
4768 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004769 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004770
Douglas Gregor88623ad2010-05-23 21:53:47 +00004771 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
4772 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType()))
Reid Spencer5f016e22007-07-11 17:01:13 +00004773 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004774
Chris Lattner78eca282008-04-07 06:49:41 +00004775 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004776 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004777 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004778
Chris Lattner78eca282008-04-07 06:49:41 +00004779 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004780 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004781
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004782 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004783 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004784 if (lhsType->isVoidPointerType()) // an exception to the rule.
4785 return Compatible;
4786 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004787 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004788 if (rhsType->getAs<BlockPointerType>()) {
4789 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004790 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004791
4792 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004793 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004794 return Compatible;
4795 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004796 return Incompatible;
4797 }
4798
4799 if (isa<BlockPointerType>(lhsType)) {
4800 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004801 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004802
Steve Naroffb4406862008-09-29 18:10:17 +00004803 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004804 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004805 return Compatible;
4806
Steve Naroff1c7d0672008-09-04 15:10:53 +00004807 if (rhsType->isBlockPointerType())
4808 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004809
Ted Kremenek6217b802009-07-29 21:53:49 +00004810 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004811 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004812 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004813 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004814 return Incompatible;
4815 }
4816
Steve Naroff14108da2009-07-10 23:34:53 +00004817 if (isa<ObjCObjectPointerType>(lhsType)) {
4818 if (rhsType->isIntegerType())
4819 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004820
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004821 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004822 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004823 if (rhsType->isVoidPointerType()) // an exception to the rule.
4824 return Compatible;
4825 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004826 }
4827 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004828 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004829 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004830 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004831 if (RHSPT->getPointeeType()->isVoidType())
4832 return Compatible;
4833 }
4834 // Treat block pointers as objects.
4835 if (rhsType->isBlockPointerType())
4836 return Compatible;
4837 return Incompatible;
4838 }
Chris Lattner78eca282008-04-07 06:49:41 +00004839 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004840 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004841 if (lhsType == Context.BoolTy)
4842 return Compatible;
4843
4844 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004845 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004846
Mike Stumpeed9cac2009-02-19 03:04:26 +00004847 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004848 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004849
4850 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004851 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004852 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004853 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004854 }
Steve Naroff14108da2009-07-10 23:34:53 +00004855 if (isa<ObjCObjectPointerType>(rhsType)) {
4856 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4857 if (lhsType == Context.BoolTy)
4858 return Compatible;
4859
4860 if (lhsType->isIntegerType())
4861 return PointerToInt;
4862
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004863 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004864 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004865 if (lhsType->isVoidPointerType()) // an exception to the rule.
4866 return Compatible;
4867 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004868 }
4869 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004870 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004871 return Compatible;
4872 return Incompatible;
4873 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004874
Chris Lattnerfc144e22008-01-04 23:18:45 +00004875 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004876 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004877 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004878 }
4879 return Incompatible;
4880}
4881
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004882/// \brief Constructs a transparent union from an expression that is
4883/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004884static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004885 QualType UnionType, FieldDecl *Field) {
4886 // Build an initializer list that designates the appropriate member
4887 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00004888 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00004889 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004890 SourceLocation());
4891 Initializer->setType(UnionType);
4892 Initializer->setInitializedFieldInUnion(Field);
4893
4894 // Build a compound literal constructing a value of the transparent
4895 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00004896 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00004897 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall42f56b52010-01-18 19:35:47 +00004898 Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004899}
4900
4901Sema::AssignConvertType
4902Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4903 QualType FromType = rExpr->getType();
4904
Mike Stump1eb44332009-09-09 15:08:12 +00004905 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004906 // transparent_union GCC extension.
4907 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004908 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004909 return Incompatible;
4910
4911 // The field to initialize within the transparent union.
4912 RecordDecl *UD = UT->getDecl();
4913 FieldDecl *InitField = 0;
4914 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004915 for (RecordDecl::field_iterator it = UD->field_begin(),
4916 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004917 it != itend; ++it) {
4918 if (it->getType()->isPointerType()) {
4919 // If the transparent union contains a pointer type, we allow:
4920 // 1) void pointer
4921 // 2) null pointer constant
4922 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004923 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004924 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004925 InitField = *it;
4926 break;
4927 }
Mike Stump1eb44332009-09-09 15:08:12 +00004928
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004929 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004930 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004931 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004932 InitField = *it;
4933 break;
4934 }
4935 }
4936
4937 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4938 == Compatible) {
4939 InitField = *it;
4940 break;
4941 }
4942 }
4943
4944 if (!InitField)
4945 return Incompatible;
4946
4947 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4948 return Compatible;
4949}
4950
Chris Lattner5cf216b2008-01-04 18:04:52 +00004951Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004952Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004953 if (getLangOptions().CPlusPlus) {
4954 if (!lhsType->isRecordType()) {
4955 // C++ 5.17p3: If the left operand is not of class type, the
4956 // expression is implicitly converted (C++ 4) to the
4957 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004958 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004959 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004960 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004961 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004962 }
4963
4964 // FIXME: Currently, we fall through and treat C++ classes like C
4965 // structures.
4966 }
4967
Steve Naroff529a4ad2007-11-27 17:58:44 +00004968 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4969 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004970 if ((lhsType->isPointerType() ||
4971 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004972 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004973 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004974 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004975 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004976 return Compatible;
4977 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004978
Chris Lattner943140e2007-10-16 02:55:40 +00004979 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004980 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004981 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00004982 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004983 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004984 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004985 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00004986 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004987
Chris Lattner5cf216b2008-01-04 18:04:52 +00004988 Sema::AssignConvertType result =
4989 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004990
Steve Narofff1120de2007-08-24 22:33:52 +00004991 // C99 6.5.16.1p2: The value of the right operand is converted to the
4992 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004993 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4994 // so that we can use references in built-in functions even in C.
4995 // The getNonReferenceType() call makes sure that the resulting expression
4996 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004997 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor63982352010-07-13 18:40:04 +00004998 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context),
Eli Friedman73c39ab2009-10-20 08:27:19 +00004999 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00005000 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005001}
5002
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005003QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005004 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00005005 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005006 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005007 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005008}
5009
Chris Lattner7ef655a2010-01-12 21:23:57 +00005010QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005011 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005012 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005013 QualType lhsType =
5014 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5015 QualType rhsType =
5016 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005017
Nate Begemanbe2341d2008-07-14 18:02:46 +00005018 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005019 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00005020 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005021
Nate Begemanbe2341d2008-07-14 18:02:46 +00005022 // Handle the case of a vector & extvector type of the same size and element
5023 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005024 if (getLangOptions().LaxVectorConversions) {
5025 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00005026 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
5027 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00005028 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005029 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00005030 if (lhsType->isExtVectorType()) {
5031 ImpCastExprToType(rex, lhsType, CastExpr::CK_BitCast);
5032 return lhsType;
5033 }
5034
5035 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
5036 return rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005037 }
5038 }
5039 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005040
Douglas Gregor255210e2010-08-06 10:14:59 +00005041 // Handle the case of equivalent AltiVec and GCC vector types
5042 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5043 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5044 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
5045 return rhsType;
5046 }
5047
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005048 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5049 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5050 bool swapped = false;
5051 if (rhsType->isExtVectorType()) {
5052 swapped = true;
5053 std::swap(rex, lex);
5054 std::swap(rhsType, lhsType);
5055 }
Mike Stump1eb44332009-09-09 15:08:12 +00005056
Nate Begemandde25982009-06-28 19:12:57 +00005057 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005058 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005059 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005060 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005061 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005062 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005063 if (swapped) std::swap(rex, lex);
5064 return lhsType;
5065 }
5066 }
5067 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5068 rhsType->isRealFloatingType()) {
5069 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005070 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005071 if (swapped) std::swap(rex, lex);
5072 return lhsType;
5073 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005074 }
5075 }
Mike Stump1eb44332009-09-09 15:08:12 +00005076
Nate Begemandde25982009-06-28 19:12:57 +00005077 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005078 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00005079 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005080 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005081 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005082}
5083
Chris Lattner7ef655a2010-01-12 21:23:57 +00005084QualType Sema::CheckMultiplyDivideOperands(
5085 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00005086 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005087 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005088
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005089 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005090
Chris Lattner7ef655a2010-01-12 21:23:57 +00005091 if (!lex->getType()->isArithmeticType() ||
5092 !rex->getType()->isArithmeticType())
5093 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005094
Chris Lattner7ef655a2010-01-12 21:23:57 +00005095 // Check for division by zero.
5096 if (isDiv &&
5097 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005098 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00005099 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005100
Chris Lattner7ef655a2010-01-12 21:23:57 +00005101 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005102}
5103
Chris Lattner7ef655a2010-01-12 21:23:57 +00005104QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005105 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00005106 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005107 if (lex->getType()->hasIntegerRepresentation() &&
5108 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00005109 return CheckVectorOperands(Loc, lex, rex);
5110 return InvalidOperands(Loc, lex, rex);
5111 }
Steve Naroff90045e82007-07-13 23:32:42 +00005112
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005113 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005114
Chris Lattner7ef655a2010-01-12 21:23:57 +00005115 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5116 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005117
Chris Lattner7ef655a2010-01-12 21:23:57 +00005118 // Check for remainder by zero.
5119 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00005120 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5121 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005122
Chris Lattner7ef655a2010-01-12 21:23:57 +00005123 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005124}
5125
Chris Lattner7ef655a2010-01-12 21:23:57 +00005126QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00005127 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005128 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5129 QualType compType = CheckVectorOperands(Loc, lex, rex);
5130 if (CompLHSTy) *CompLHSTy = compType;
5131 return compType;
5132 }
Steve Naroff49b45262007-07-13 16:58:59 +00005133
Eli Friedmanab3a8522009-03-28 01:22:36 +00005134 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00005135
Reid Spencer5f016e22007-07-11 17:01:13 +00005136 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00005137 if (lex->getType()->isArithmeticType() &&
5138 rex->getType()->isArithmeticType()) {
5139 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005140 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005141 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005142
Eli Friedmand72d16e2008-05-18 18:08:51 +00005143 // Put any potential pointer into PExp
5144 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005145 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005146 std::swap(PExp, IExp);
5147
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005148 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005149
Eli Friedmand72d16e2008-05-18 18:08:51 +00005150 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00005151 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005152
Chris Lattnerb5f15622009-04-24 23:50:08 +00005153 // Check for arithmetic on pointers to incomplete types.
5154 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005155 if (getLangOptions().CPlusPlus) {
5156 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005157 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005158 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005159 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005160
5161 // GNU extension: arithmetic on pointer to void
5162 Diag(Loc, diag::ext_gnu_void_ptr)
5163 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00005164 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005165 if (getLangOptions().CPlusPlus) {
5166 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5167 << lex->getType() << lex->getSourceRange();
5168 return QualType();
5169 }
5170
5171 // GNU extension: arithmetic on pointer to function
5172 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5173 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00005174 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00005175 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00005176 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00005177 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00005178 PExp->getType()->isObjCObjectPointerType()) &&
5179 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00005180 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5181 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005182 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00005183 return QualType();
5184 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00005185 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005186 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005187 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5188 << PointeeTy << PExp->getSourceRange();
5189 return QualType();
5190 }
Mike Stump1eb44332009-09-09 15:08:12 +00005191
Eli Friedmanab3a8522009-03-28 01:22:36 +00005192 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00005193 QualType LHSTy = Context.isPromotableBitField(lex);
5194 if (LHSTy.isNull()) {
5195 LHSTy = lex->getType();
5196 if (LHSTy->isPromotableIntegerType())
5197 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005198 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005199 *CompLHSTy = LHSTy;
5200 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005201 return PExp->getType();
5202 }
5203 }
5204
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005205 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005206}
5207
Chris Lattnereca7be62008-04-07 05:30:13 +00005208// C99 6.5.6
5209QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005210 SourceLocation Loc, QualType* CompLHSTy) {
5211 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5212 QualType compType = CheckVectorOperands(Loc, lex, rex);
5213 if (CompLHSTy) *CompLHSTy = compType;
5214 return compType;
5215 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005216
Eli Friedmanab3a8522009-03-28 01:22:36 +00005217 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005218
Chris Lattner6e4ab612007-12-09 21:53:25 +00005219 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005220
Chris Lattner6e4ab612007-12-09 21:53:25 +00005221 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00005222 if (lex->getType()->isArithmeticType()
5223 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005224 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005225 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005226 }
Mike Stump1eb44332009-09-09 15:08:12 +00005227
Chris Lattner6e4ab612007-12-09 21:53:25 +00005228 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005229 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00005230 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005231
Douglas Gregore7450f52009-03-24 19:52:54 +00005232 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005233
Douglas Gregore7450f52009-03-24 19:52:54 +00005234 bool ComplainAboutVoid = false;
5235 Expr *ComplainAboutFunc = 0;
5236 if (lpointee->isVoidType()) {
5237 if (getLangOptions().CPlusPlus) {
5238 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5239 << lex->getSourceRange() << rex->getSourceRange();
5240 return QualType();
5241 }
5242
5243 // GNU C extension: arithmetic on pointer to void
5244 ComplainAboutVoid = true;
5245 } else if (lpointee->isFunctionType()) {
5246 if (getLangOptions().CPlusPlus) {
5247 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005248 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005249 return QualType();
5250 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005251
5252 // GNU C extension: arithmetic on pointer to function
5253 ComplainAboutFunc = lex;
5254 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005255 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005256 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005257 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005258 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005259 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005260
Chris Lattnerb5f15622009-04-24 23:50:08 +00005261 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005262 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005263 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5264 << lpointee << lex->getSourceRange();
5265 return QualType();
5266 }
Mike Stump1eb44332009-09-09 15:08:12 +00005267
Chris Lattner6e4ab612007-12-09 21:53:25 +00005268 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005269 if (rex->getType()->isIntegerType()) {
5270 if (ComplainAboutVoid)
5271 Diag(Loc, diag::ext_gnu_void_ptr)
5272 << lex->getSourceRange() << rex->getSourceRange();
5273 if (ComplainAboutFunc)
5274 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005275 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005276 << ComplainAboutFunc->getSourceRange();
5277
Eli Friedmanab3a8522009-03-28 01:22:36 +00005278 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005279 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005280 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005281
Chris Lattner6e4ab612007-12-09 21:53:25 +00005282 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005283 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005284 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005285
Douglas Gregore7450f52009-03-24 19:52:54 +00005286 // RHS must be a completely-type object type.
5287 // Handle the GNU void* extension.
5288 if (rpointee->isVoidType()) {
5289 if (getLangOptions().CPlusPlus) {
5290 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5291 << lex->getSourceRange() << rex->getSourceRange();
5292 return QualType();
5293 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005294
Douglas Gregore7450f52009-03-24 19:52:54 +00005295 ComplainAboutVoid = true;
5296 } else if (rpointee->isFunctionType()) {
5297 if (getLangOptions().CPlusPlus) {
5298 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005299 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005300 return QualType();
5301 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005302
5303 // GNU extension: arithmetic on pointer to function
5304 if (!ComplainAboutFunc)
5305 ComplainAboutFunc = rex;
5306 } else if (!rpointee->isDependentType() &&
5307 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005308 PDiag(diag::err_typecheck_sub_ptr_object)
5309 << rex->getSourceRange()
5310 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005311 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005312
Eli Friedman88d936b2009-05-16 13:54:38 +00005313 if (getLangOptions().CPlusPlus) {
5314 // Pointee types must be the same: C++ [expr.add]
5315 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5316 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5317 << lex->getType() << rex->getType()
5318 << lex->getSourceRange() << rex->getSourceRange();
5319 return QualType();
5320 }
5321 } else {
5322 // Pointee types must be compatible C99 6.5.6p3
5323 if (!Context.typesAreCompatible(
5324 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5325 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5326 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5327 << lex->getType() << rex->getType()
5328 << lex->getSourceRange() << rex->getSourceRange();
5329 return QualType();
5330 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005331 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005332
Douglas Gregore7450f52009-03-24 19:52:54 +00005333 if (ComplainAboutVoid)
5334 Diag(Loc, diag::ext_gnu_void_ptr)
5335 << lex->getSourceRange() << rex->getSourceRange();
5336 if (ComplainAboutFunc)
5337 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005338 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005339 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005340
5341 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005342 return Context.getPointerDiffType();
5343 }
5344 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005345
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005346 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005347}
5348
Chris Lattnereca7be62008-04-07 05:30:13 +00005349// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005350QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005351 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005352 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregorf6094622010-07-23 15:58:24 +00005353 if (!lex->getType()->hasIntegerRepresentation() ||
5354 !rex->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005355 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005356
Nate Begeman2207d792009-10-25 02:26:48 +00005357 // Vector shifts promote their scalar inputs to vector type.
5358 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5359 return CheckVectorOperands(Loc, lex, rex);
5360
Chris Lattnerca5eede2007-12-12 05:47:28 +00005361 // Shifts don't perform usual arithmetic conversions, they just do integer
5362 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005363 QualType LHSTy = Context.isPromotableBitField(lex);
5364 if (LHSTy.isNull()) {
5365 LHSTy = lex->getType();
5366 if (LHSTy->isPromotableIntegerType())
5367 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005368 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005369 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005370 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005371
Chris Lattnerca5eede2007-12-12 05:47:28 +00005372 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005373
Ryan Flynnd0439682009-08-07 16:20:20 +00005374 // Sanity-check shift operands
5375 llvm::APSInt Right;
5376 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005377 if (!rex->isValueDependent() &&
5378 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005379 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005380 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5381 else {
5382 llvm::APInt LeftBits(Right.getBitWidth(),
5383 Context.getTypeSize(lex->getType()));
5384 if (Right.uge(LeftBits))
5385 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5386 }
5387 }
5388
Chris Lattnerca5eede2007-12-12 05:47:28 +00005389 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005390 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005391}
5392
Chandler Carruth99919472010-07-10 12:30:03 +00005393static bool IsWithinTemplateSpecialization(Decl *D) {
5394 if (DeclContext *DC = D->getDeclContext()) {
5395 if (isa<ClassTemplateSpecializationDecl>(DC))
5396 return true;
5397 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5398 return FD->isFunctionTemplateSpecialization();
5399 }
5400 return false;
5401}
5402
Douglas Gregor0c6db942009-05-04 06:07:12 +00005403// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005404QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005405 unsigned OpaqueOpc, bool isRelational) {
5406 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5407
Chris Lattner02dd4b12009-12-05 05:40:13 +00005408 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005409 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005410 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005411
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005412 QualType lType = lex->getType();
5413 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005414
Douglas Gregor8eee1192010-06-22 22:12:46 +00005415 if (!lType->hasFloatingRepresentation() &&
5416 !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005417 // For non-floating point types, check for self-comparisons of the form
5418 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5419 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00005420 //
5421 // NOTE: Don't warn about comparison expressions resulting from macro
5422 // expansion. Also don't warn about comparisons which are only self
5423 // comparisons within a template specialization. The warnings should catch
5424 // obvious cases in the definition of the template anyways. The idea is to
5425 // warn when the typed comparison operator will always evaluate to the same
5426 // result.
Chris Lattner55660a72009-03-08 19:39:53 +00005427 Expr *LHSStripped = lex->IgnoreParens();
5428 Expr *RHSStripped = rex->IgnoreParens();
Chandler Carruth99919472010-07-10 12:30:03 +00005429 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00005430 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Chandler Carruth64d092c2010-07-12 06:23:38 +00005431 if (DRL->getDecl() == DRR->getDecl() && !Loc.isMacroID() &&
Chandler Carruth99919472010-07-10 12:30:03 +00005432 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00005433 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5434 << 0 // self-
5435 << (Opc == BinaryOperator::EQ
5436 || Opc == BinaryOperator::LE
5437 || Opc == BinaryOperator::GE));
5438 } else if (lType->isArrayType() && rType->isArrayType() &&
5439 !DRL->getDecl()->getType()->isReferenceType() &&
5440 !DRR->getDecl()->getType()->isReferenceType()) {
5441 // what is it always going to eval to?
5442 char always_evals_to;
5443 switch(Opc) {
5444 case BinaryOperator::EQ: // e.g. array1 == array2
5445 always_evals_to = 0; // false
5446 break;
5447 case BinaryOperator::NE: // e.g. array1 != array2
5448 always_evals_to = 1; // true
5449 break;
5450 default:
5451 // best we can say is 'a constant'
5452 always_evals_to = 2; // e.g. array1 <= array2
5453 break;
5454 }
5455 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5456 << 1 // array
5457 << always_evals_to);
5458 }
5459 }
Chandler Carruth99919472010-07-10 12:30:03 +00005460 }
Mike Stump1eb44332009-09-09 15:08:12 +00005461
Chris Lattner55660a72009-03-08 19:39:53 +00005462 if (isa<CastExpr>(LHSStripped))
5463 LHSStripped = LHSStripped->IgnoreParenCasts();
5464 if (isa<CastExpr>(RHSStripped))
5465 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005466
Chris Lattner55660a72009-03-08 19:39:53 +00005467 // Warn about comparisons against a string constant (unless the other
5468 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005469 Expr *literalString = 0;
5470 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005471 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005472 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005473 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005474 literalString = lex;
5475 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005476 } else if ((isa<StringLiteral>(RHSStripped) ||
5477 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005478 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005479 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005480 literalString = rex;
5481 literalStringStripped = RHSStripped;
5482 }
5483
5484 if (literalString) {
5485 std::string resultComparison;
5486 switch (Opc) {
5487 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5488 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5489 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5490 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5491 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5492 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5493 default: assert(false && "Invalid comparison operator");
5494 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005495
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005496 DiagRuntimeBehavior(Loc,
5497 PDiag(diag::warn_stringcompare)
5498 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00005499 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00005500 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005501 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005502
Douglas Gregord64fdd02010-06-08 19:50:34 +00005503 // C99 6.5.8p3 / C99 6.5.9p4
5504 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5505 UsualArithmeticConversions(lex, rex);
5506 else {
5507 UsualUnaryConversions(lex);
5508 UsualUnaryConversions(rex);
5509 }
5510
5511 lType = lex->getType();
5512 rType = rex->getType();
5513
Douglas Gregor447b69e2008-11-19 03:25:36 +00005514 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005515 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005516
Chris Lattnera5937dd2007-08-26 01:18:55 +00005517 if (isRelational) {
5518 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005519 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005520 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005521 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00005522 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005523 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005524
Chris Lattnera5937dd2007-08-26 01:18:55 +00005525 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005526 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005527 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005528
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005529 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005530 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005531 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005532 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005533
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005534 // All of the following pointer-related warnings are GCC extensions, except
5535 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00005536 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005537 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005538 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005539 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005540 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005541
Douglas Gregor0c6db942009-05-04 06:07:12 +00005542 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005543 if (LCanPointeeTy == RCanPointeeTy)
5544 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005545 if (!isRelational &&
5546 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5547 // Valid unless comparison between non-null pointer and function pointer
5548 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005549 // In a SFINAE context, we treat this as a hard error to maintain
5550 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005551 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5552 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005553 Diag(Loc,
5554 isSFINAEContext()?
5555 diag::err_typecheck_comparison_of_fptr_to_void
5556 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005557 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005558
5559 if (isSFINAEContext())
5560 return QualType();
5561
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005562 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5563 return ResultTy;
5564 }
5565 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005566 // C++ [expr.rel]p2:
5567 // [...] Pointer conversions (4.10) and qualification
5568 // conversions (4.4) are performed on pointer operands (or on
5569 // a pointer operand and a null pointer constant) to bring
5570 // them to their composite pointer type. [...]
5571 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005572 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005573 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005574 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005575 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005576 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005577 if (T.isNull()) {
5578 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5579 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5580 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005581 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005582 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005583 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005584 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005585 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00005586 }
5587
Eli Friedman73c39ab2009-10-20 08:27:19 +00005588 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5589 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005590 return ResultTy;
5591 }
Eli Friedman3075e762009-08-23 00:27:47 +00005592 // C99 6.5.9p2 and C99 6.5.8p2
5593 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5594 RCanPointeeTy.getUnqualifiedType())) {
5595 // Valid unless a relational comparison of function pointers
5596 if (isRelational && LCanPointeeTy->isFunctionType()) {
5597 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5598 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5599 }
5600 } else if (!isRelational &&
5601 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5602 // Valid unless comparison between non-null pointer and function pointer
5603 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5604 && !LHSIsNull && !RHSIsNull) {
5605 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5606 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5607 }
5608 } else {
5609 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005610 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005611 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005612 }
Eli Friedman3075e762009-08-23 00:27:47 +00005613 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005614 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005615 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005616 }
Mike Stump1eb44332009-09-09 15:08:12 +00005617
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005618 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005619 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005620 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005621 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005622 (lType->isPointerType() ||
5623 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00005624 ImpCastExprToType(rex, lType,
5625 lType->isMemberPointerType()
5626 ? CastExpr::CK_NullToMemberPointer
5627 : CastExpr::CK_IntegralToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005628 return ResultTy;
5629 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005630 if (LHSIsNull &&
5631 (rType->isPointerType() ||
5632 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00005633 ImpCastExprToType(lex, rType,
5634 rType->isMemberPointerType()
5635 ? CastExpr::CK_NullToMemberPointer
5636 : CastExpr::CK_IntegralToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005637 return ResultTy;
5638 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005639
5640 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005641 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005642 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5643 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005644 // In addition, pointers to members can be compared, or a pointer to
5645 // member and a null pointer constant. Pointer to member conversions
5646 // (4.11) and qualification conversions (4.4) are performed to bring
5647 // them to a common type. If one operand is a null pointer constant,
5648 // the common type is the type of the other operand. Otherwise, the
5649 // common type is a pointer to member type similar (4.4) to the type
5650 // of one of the operands, with a cv-qualification signature (4.4)
5651 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005652 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005653 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005654 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005655 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005656 if (T.isNull()) {
5657 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005658 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005659 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005660 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005661 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005662 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005663 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005664 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005665 }
Mike Stump1eb44332009-09-09 15:08:12 +00005666
Eli Friedman73c39ab2009-10-20 08:27:19 +00005667 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5668 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005669 return ResultTy;
5670 }
Mike Stump1eb44332009-09-09 15:08:12 +00005671
Douglas Gregor20b3e992009-08-24 17:42:35 +00005672 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005673 if (lType->isNullPtrType() && rType->isNullPtrType())
5674 return ResultTy;
5675 }
Mike Stump1eb44332009-09-09 15:08:12 +00005676
Steve Naroff1c7d0672008-09-04 15:10:53 +00005677 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005678 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005679 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5680 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005681
Steve Naroff1c7d0672008-09-04 15:10:53 +00005682 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005683 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005684 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005685 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005686 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005687 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005688 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005689 }
Steve Naroff59f53942008-09-28 01:11:11 +00005690 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005691 if (!isRelational
5692 && ((lType->isBlockPointerType() && rType->isPointerType())
5693 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005694 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005695 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005696 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005697 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005698 ->getPointeeType()->isVoidType())))
5699 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5700 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005701 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005702 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005703 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005704 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005705
Steve Naroff14108da2009-07-10 23:34:53 +00005706 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005707 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005708 const PointerType *LPT = lType->getAs<PointerType>();
5709 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005710 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005711 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005712 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005713 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005714
Steve Naroffa8069f12008-11-17 19:49:16 +00005715 if (!LPtrToVoid && !RPtrToVoid &&
5716 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005717 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005718 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005719 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005720 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005721 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005722 }
Steve Naroff14108da2009-07-10 23:34:53 +00005723 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005724 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005725 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5726 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005727 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005728 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005729 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005730 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005731 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
5732 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005733 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005734 bool isError = false;
5735 if ((LHSIsNull && lType->isIntegerType()) ||
5736 (RHSIsNull && rType->isIntegerType())) {
5737 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005738 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005739 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005740 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005741 else if (getLangOptions().CPlusPlus) {
5742 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
5743 isError = true;
5744 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005745 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005746
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005747 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005748 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005749 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005750 if (isError)
5751 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005752 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005753
5754 if (lType->isIntegerType())
5755 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005756 else
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005757 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005758 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005759 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005760
Steve Naroff39218df2008-09-04 16:56:14 +00005761 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005762 if (!isRelational && RHSIsNull
5763 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005764 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005765 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005766 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005767 if (!isRelational && LHSIsNull
5768 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005769 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005770 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005771 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005772 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005773}
5774
Nate Begemanbe2341d2008-07-14 18:02:46 +00005775/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005776/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005777/// like a scalar comparison, a vector comparison produces a vector of integer
5778/// types.
5779QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005780 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005781 bool isRelational) {
5782 // Check to make sure we're operating on vectors of the same type and width,
5783 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005784 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005785 if (vType.isNull())
5786 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005787
Nate Begemanbe2341d2008-07-14 18:02:46 +00005788 QualType lType = lex->getType();
5789 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005790
Nate Begemanbe2341d2008-07-14 18:02:46 +00005791 // For non-floating point types, check for self-comparisons of the form
5792 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5793 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00005794 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00005795 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5796 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5797 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord64fdd02010-06-08 19:50:34 +00005798 DiagRuntimeBehavior(Loc,
5799 PDiag(diag::warn_comparison_always)
5800 << 0 // self-
5801 << 2 // "a constant"
5802 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00005803 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005804
Nate Begemanbe2341d2008-07-14 18:02:46 +00005805 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00005806 if (!isRelational && lType->hasFloatingRepresentation()) {
5807 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005808 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005809 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005810
Nate Begemanbe2341d2008-07-14 18:02:46 +00005811 // Return the type for the comparison, which is the same as vector type for
5812 // integer vectors, or an integer type of identical size and number of
5813 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00005814 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00005815 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005816
John McCall183700f2009-09-21 23:43:11 +00005817 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005818 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005819 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005820 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005821 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005822 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5823
Mike Stumpeed9cac2009-02-19 03:04:26 +00005824 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005825 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005826 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5827}
5828
Reid Spencer5f016e22007-07-11 17:01:13 +00005829inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005830 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005831 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5832 if (lex->getType()->hasIntegerRepresentation() &&
5833 rex->getType()->hasIntegerRepresentation())
5834 return CheckVectorOperands(Loc, lex, rex);
5835
5836 return InvalidOperands(Loc, lex, rex);
5837 }
Steve Naroff90045e82007-07-13 23:32:42 +00005838
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005839 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005840
Steve Naroffa4332e22007-07-17 00:58:39 +00005841 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005842 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005843 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005844}
5845
5846inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00005847 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
5848
5849 // Diagnose cases where the user write a logical and/or but probably meant a
5850 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
5851 // is a constant.
5852 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman787b0942010-07-27 19:14:53 +00005853 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00005854 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00005855 !Loc.isMacroID()) {
5856 // If the RHS can be constant folded, and if it constant folds to something
5857 // that isn't 0 or 1 (which indicate a potential logical operation that
5858 // happened to fold to true/false) then warn.
5859 Expr::EvalResult Result;
5860 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
5861 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
5862 Diag(Loc, diag::warn_logical_instead_of_bitwise)
5863 << rex->getSourceRange()
5864 << (Opc == BinaryOperator::LAnd ? "&&" : "||")
5865 << (Opc == BinaryOperator::LAnd ? "&" : "|");
5866 }
5867 }
Chris Lattner90a8f272010-07-13 19:41:32 +00005868
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005869 if (!Context.getLangOptions().CPlusPlus) {
5870 UsualUnaryConversions(lex);
5871 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005872
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005873 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5874 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005875
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005876 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005877 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005878
John McCall75f7c0f2010-06-04 00:29:51 +00005879 // The following is safe because we only use this method for
5880 // non-overloadable operands.
5881
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005882 // C++ [expr.log.and]p1
5883 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00005884 // The operands are both contextually converted to type bool.
5885 if (PerformContextuallyConvertToBool(lex) ||
5886 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005887 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005888
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005889 // C++ [expr.log.and]p2
5890 // C++ [expr.log.or]p2
5891 // The result is a bool.
5892 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005893}
5894
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005895/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5896/// is a read-only property; return true if so. A readonly property expression
5897/// depends on various declarations and thus must be treated specially.
5898///
Mike Stump1eb44332009-09-09 15:08:12 +00005899static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005900 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5901 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5902 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5903 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005904 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005905 BaseType->getAsObjCInterfacePointerType())
5906 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5907 if (S.isPropertyReadonly(PDecl, IFace))
5908 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005909 }
5910 }
5911 return false;
5912}
5913
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005914/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5915/// emit an error and return true. If so, return false.
5916static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005917 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005918 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005919 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005920 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5921 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005922 if (IsLV == Expr::MLV_Valid)
5923 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005924
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005925 unsigned Diag = 0;
5926 bool NeedType = false;
5927 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005928 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005929 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005930 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5931 NeedType = true;
5932 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005933 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005934 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5935 NeedType = true;
5936 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005937 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005938 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5939 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00005940 case Expr::MLV_Valid:
5941 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00005942 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00005943 case Expr::MLV_MemberFunction:
5944 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005945 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5946 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005947 case Expr::MLV_IncompleteType:
5948 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005949 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005950 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00005951 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005952 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005953 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5954 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005955 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005956 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5957 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005958 case Expr::MLV_ReadonlyProperty:
5959 Diag = diag::error_readonly_property_assignment;
5960 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005961 case Expr::MLV_NoSetterProperty:
5962 Diag = diag::error_nosetter_property_assignment;
5963 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005964 case Expr::MLV_SubObjCPropertySetting:
5965 Diag = diag::error_no_subobject_property_setting;
5966 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005967 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005968
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005969 SourceRange Assign;
5970 if (Loc != OrigLoc)
5971 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005972 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005973 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005974 else
Mike Stump1eb44332009-09-09 15:08:12 +00005975 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005976 return true;
5977}
5978
5979
5980
5981// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005982QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5983 SourceLocation Loc,
5984 QualType CompoundType) {
5985 // Verify that LHS is a modifiable lvalue, and emit error if not.
5986 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005987 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005988
5989 QualType LHSType = LHS->getType();
5990 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005991 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005992 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00005993 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005994 // Simple assignment "x = y".
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00005995 if (const ObjCImplicitSetterGetterRefExpr *OISGE =
5996 dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) {
5997 // If using property-dot syntax notation for assignment, and there is a
5998 // setter, RHS expression is being passed to the setter argument. So,
5999 // type conversion (and comparison) is RHS to setter's argument type.
6000 if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) {
6001 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
6002 LHSTy = (*P)->getType();
6003 }
6004 }
6005
6006 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006007 // Special case of NSObject attributes on c-style pointer types.
6008 if (ConvTy == IncompatiblePointer &&
6009 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006010 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006011 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006012 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006013 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006014
Chris Lattner2c156472008-08-21 18:04:13 +00006015 // If the RHS is a unary plus or minus, check to see if they = and + are
6016 // right next to each other. If so, the user may have typo'd "x =+ 4"
6017 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006018 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00006019 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6020 RHSCheck = ICE->getSubExpr();
6021 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
6022 if ((UO->getOpcode() == UnaryOperator::Plus ||
6023 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006024 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00006025 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00006026 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6027 // And there is a space or other character before the subexpr of the
6028 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00006029 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6030 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006031 Diag(Loc, diag::warn_not_compound_assign)
6032 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
6033 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00006034 }
Chris Lattner2c156472008-08-21 18:04:13 +00006035 }
6036 } else {
6037 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00006038 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006039 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006040
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006041 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00006042 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00006043 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006044
Chris Lattner8b5dec32010-07-07 06:14:23 +00006045
6046 // Check to see if the destination operand is a dereferenced null pointer. If
6047 // so, and if not volatile-qualified, this is undefined behavior that the
6048 // optimizer will delete, so warn about it. People sometimes try to use this
6049 // to get a deterministic trap and are surprised by clang's behavior. This
6050 // only handles the pattern "*null = whatever", which is a very syntactic
6051 // check.
6052 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
6053 if (UO->getOpcode() == UnaryOperator::Deref &&
6054 UO->getSubExpr()->IgnoreParenCasts()->
6055 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6056 !UO->getType().isVolatileQualified()) {
6057 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6058 << UO->getSubExpr()->getSourceRange();
6059 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6060 }
6061
Reid Spencer5f016e22007-07-11 17:01:13 +00006062 // C99 6.5.16p3: The type of an assignment expression is the type of the
6063 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00006064 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00006065 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6066 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006067 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00006068 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006069 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006070}
6071
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006072// C99 6.5.17
6073QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00006074 DiagnoseUnusedExprResult(LHS);
6075
Chris Lattner53fcaa92008-07-25 20:54:07 +00006076 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00006077 // C++ does not perform this conversion (C++ [expr.comma]p1).
6078 if (!getLangOptions().CPlusPlus)
6079 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006080
6081 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
6082 // incomplete in C++).
6083
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006084 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006085}
6086
Steve Naroff49b45262007-07-13 16:58:59 +00006087/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6088/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006089QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006090 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00006091 if (Op->isTypeDependent())
6092 return Context.DependentTy;
6093
Chris Lattner3528d352008-11-21 07:05:48 +00006094 QualType ResType = Op->getType();
6095 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006096
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006097 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
6098 // Decrement of bool is not allowed.
6099 if (!isInc) {
6100 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
6101 return QualType();
6102 }
6103 // Increment of bool sets it to true, but is deprecated.
6104 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
6105 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00006106 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006107 } else if (ResType->isAnyPointerType()) {
6108 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006109
Chris Lattner3528d352008-11-21 07:05:48 +00006110 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00006111 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00006112 if (getLangOptions().CPlusPlus) {
6113 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
6114 << Op->getSourceRange();
6115 return QualType();
6116 }
6117
6118 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00006119 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00006120 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00006121 if (getLangOptions().CPlusPlus) {
6122 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
6123 << Op->getType() << Op->getSourceRange();
6124 return QualType();
6125 }
6126
6127 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00006128 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00006129 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00006130 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00006131 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006132 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006133 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00006134 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006135 else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00006136 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6137 << PointeeTy << Op->getSourceRange();
6138 return QualType();
6139 }
Eli Friedman5b088a12010-01-03 00:20:48 +00006140 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00006141 // C99 does not support ++/-- on complex types, we allow as an extension.
6142 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006143 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00006144 } else {
6145 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00006146 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00006147 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006148 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006149 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00006150 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00006151 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00006152 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006153 // In C++, a prefix increment is the same type as the operand. Otherwise
6154 // (in C or with postfix), the increment is the unqualified type of the
6155 // operand.
6156 return isPrefix && getLangOptions().CPlusPlus
6157 ? ResType : ResType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006158}
6159
Anders Carlsson369dee42008-02-01 07:15:58 +00006160/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00006161/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006162/// where the declaration is needed for type checking. We only need to
6163/// handle cases when the expression references a function designator
6164/// or is an lvalue. Here are some examples:
6165/// - &(x) => x
6166/// - &*****f => f for f a function designator.
6167/// - &s.xx => s
6168/// - &s.zz[1].yy -> s, if zz is an array
6169/// - *(x + 1) -> x, if x is an array
6170/// - &"123"[2] -> 0
6171/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006172static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00006173 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006174 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00006175 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00006176 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00006177 // If this is an arrow operator, the address is an offset from
6178 // the base's value, so the object the base refers to is
6179 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00006180 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00006181 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00006182 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00006183 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00006184 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00006185 // FIXME: This code shouldn't be necessary! We should catch the implicit
6186 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00006187 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6188 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6189 if (ICE->getSubExpr()->getType()->isArrayType())
6190 return getPrimaryDecl(ICE->getSubExpr());
6191 }
6192 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00006193 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006194 case Stmt::UnaryOperatorClass: {
6195 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006196
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006197 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006198 case UnaryOperator::Real:
6199 case UnaryOperator::Imag:
6200 case UnaryOperator::Extension:
6201 return getPrimaryDecl(UO->getSubExpr());
6202 default:
6203 return 0;
6204 }
6205 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006206 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00006207 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00006208 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00006209 // If the result of an implicit cast is an l-value, we care about
6210 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00006211 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00006212 default:
6213 return 0;
6214 }
6215}
6216
6217/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00006218/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00006219/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006220/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00006221/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006222/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00006223/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00006224QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006225 // Make sure to ignore parentheses in subsequent checks
6226 op = op->IgnoreParens();
6227
Douglas Gregor9103bb22008-12-17 22:52:20 +00006228 if (op->isTypeDependent())
6229 return Context.DependentTy;
6230
Steve Naroff08f19672008-01-13 17:10:08 +00006231 if (getLangOptions().C99) {
6232 // Implement C99-only parts of addressof rules.
6233 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
6234 if (uOp->getOpcode() == UnaryOperator::Deref)
6235 // Per C99 6.5.3.2, the address of a deref always returns a valid result
6236 // (assuming the deref expression is valid).
6237 return uOp->getSubExpr()->getType();
6238 }
6239 // Technically, there should be a check for array subscript
6240 // expressions here, but the result of one is always an lvalue anyway.
6241 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006242 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00006243 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00006244
Sebastian Redle27d87f2010-01-11 15:56:56 +00006245 MemberExpr *ME = dyn_cast<MemberExpr>(op);
6246 if (lval == Expr::LV_MemberFunction && ME &&
6247 isa<CXXMethodDecl>(ME->getMemberDecl())) {
6248 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
6249 // &f where f is a member of the current object, or &o.f, or &p->f
6250 // All these are not allowed, and we need to catch them before the dcl
6251 // branch of the if, below.
6252 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6253 << dcl;
6254 // FIXME: Improve this diagnostic and provide a fixit.
6255
6256 // Now recover by acting as if the function had been accessed qualified.
6257 return Context.getMemberPointerType(op->getType(),
6258 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
6259 .getTypePtr());
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006260 }
6261
6262 if (lval == Expr::LV_ClassTemporary) {
Douglas Gregore873fb72010-02-16 21:39:57 +00006263 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6264 : diag::ext_typecheck_addrof_class_temporary)
6265 << op->getType() << op->getSourceRange();
6266 if (isSFINAEContext())
6267 return QualType();
Chris Lattnerc721ae82010-07-05 19:36:34 +00006268 } else if (isa<ObjCSelectorExpr>(op))
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006269 return Context.getPointerType(op->getType());
Chris Lattnerc721ae82010-07-05 19:36:34 +00006270 else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00006271 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006272 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00006273 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00006274 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006275 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6276 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006277 return QualType();
6278 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00006279 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006280 // The operand cannot be a bit-field
6281 Diag(OpLoc, diag::err_typecheck_address_of)
6282 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00006283 return QualType();
Anders Carlsson09380262010-01-31 17:18:49 +00006284 } else if (op->refersToVectorElement()) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006285 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006286 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00006287 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00006288 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00006289 } else if (isa<ObjCPropertyRefExpr>(op)) {
6290 // cannot take address of a property expression.
6291 Diag(OpLoc, diag::err_typecheck_address_of)
6292 << "property expression" << op->getSourceRange();
6293 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00006294 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6295 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00006296 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6297 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00006298 } else if (isa<UnresolvedLookupExpr>(op)) {
6299 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00006300 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00006301 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00006302 // with the register storage-class specifier.
6303 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
6304 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006305 Diag(OpLoc, diag::err_typecheck_address_of)
6306 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006307 return QualType();
6308 }
John McCallba135432009-11-21 08:51:07 +00006309 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006310 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006311 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00006312 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00006313 // Could be a pointer to member, though, if there is an explicit
6314 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006315 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00006316 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006317 if (Ctx && Ctx->isRecord()) {
6318 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006319 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006320 diag::err_cannot_form_pointer_to_member_of_reference_type)
6321 << FD->getDeclName() << FD->getType();
6322 return QualType();
6323 }
Mike Stump1eb44332009-09-09 15:08:12 +00006324
Sebastian Redlebc07d52009-02-03 20:19:35 +00006325 return Context.getMemberPointerType(op->getType(),
6326 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006327 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00006328 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00006329 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00006330 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00006331 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006332 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6333 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00006334 return Context.getMemberPointerType(op->getType(),
6335 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6336 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00006337 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00006338 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00006339
Eli Friedman441cf102009-05-16 23:27:50 +00006340 if (lval == Expr::LV_IncompleteVoidType) {
6341 // Taking the address of a void variable is technically illegal, but we
6342 // allow it in cases which are otherwise valid.
6343 // Example: "extern void x; void* y = &x;".
6344 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6345 }
6346
Reid Spencer5f016e22007-07-11 17:01:13 +00006347 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00006348 if (op->getType()->isObjCObjectType())
6349 return Context.getObjCObjectPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00006350 return Context.getPointerType(op->getType());
6351}
6352
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006353/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
Chris Lattner22caddc2008-11-23 09:13:29 +00006354QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00006355 if (Op->isTypeDependent())
6356 return Context.DependentTy;
6357
Chris Lattner22caddc2008-11-23 09:13:29 +00006358 UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006359 QualType OpTy = Op->getType();
6360 QualType Result;
6361
6362 // Note that per both C89 and C99, indirection is always legal, even if OpTy
6363 // is an incomplete type or void. It would be possible to warn about
6364 // dereferencing a void pointer, but it's completely well-defined, and such a
6365 // warning is unlikely to catch any mistakes.
6366 if (const PointerType *PT = OpTy->getAs<PointerType>())
6367 Result = PT->getPointeeType();
6368 else if (const ObjCObjectPointerType *OPT =
6369 OpTy->getAs<ObjCObjectPointerType>())
6370 Result = OPT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006371
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006372 if (Result.isNull()) {
6373 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
6374 << OpTy << Op->getSourceRange();
6375 return QualType();
6376 }
6377
6378 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00006379}
6380
6381static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6382 tok::TokenKind Kind) {
6383 BinaryOperator::Opcode Opc;
6384 switch (Kind) {
6385 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00006386 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6387 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006388 case tok::star: Opc = BinaryOperator::Mul; break;
6389 case tok::slash: Opc = BinaryOperator::Div; break;
6390 case tok::percent: Opc = BinaryOperator::Rem; break;
6391 case tok::plus: Opc = BinaryOperator::Add; break;
6392 case tok::minus: Opc = BinaryOperator::Sub; break;
6393 case tok::lessless: Opc = BinaryOperator::Shl; break;
6394 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6395 case tok::lessequal: Opc = BinaryOperator::LE; break;
6396 case tok::less: Opc = BinaryOperator::LT; break;
6397 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6398 case tok::greater: Opc = BinaryOperator::GT; break;
6399 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6400 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6401 case tok::amp: Opc = BinaryOperator::And; break;
6402 case tok::caret: Opc = BinaryOperator::Xor; break;
6403 case tok::pipe: Opc = BinaryOperator::Or; break;
6404 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6405 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6406 case tok::equal: Opc = BinaryOperator::Assign; break;
6407 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6408 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6409 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6410 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6411 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6412 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6413 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6414 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6415 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6416 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6417 case tok::comma: Opc = BinaryOperator::Comma; break;
6418 }
6419 return Opc;
6420}
6421
6422static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6423 tok::TokenKind Kind) {
6424 UnaryOperator::Opcode Opc;
6425 switch (Kind) {
6426 default: assert(0 && "Unknown unary op!");
6427 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6428 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6429 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6430 case tok::star: Opc = UnaryOperator::Deref; break;
6431 case tok::plus: Opc = UnaryOperator::Plus; break;
6432 case tok::minus: Opc = UnaryOperator::Minus; break;
6433 case tok::tilde: Opc = UnaryOperator::Not; break;
6434 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006435 case tok::kw___real: Opc = UnaryOperator::Real; break;
6436 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6437 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6438 }
6439 return Opc;
6440}
6441
Douglas Gregoreaebc752008-11-06 23:29:22 +00006442/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6443/// operator @p Opc at location @c TokLoc. This routine only supports
6444/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006445Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6446 unsigned Op,
6447 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006448 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006449 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006450 // The following two variables are used for compound assignment operators
6451 QualType CompLHSTy; // Type of LHS after promotions for computation
6452 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006453
6454 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006455 case BinaryOperator::Assign:
6456 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6457 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006458 case BinaryOperator::PtrMemD:
6459 case BinaryOperator::PtrMemI:
6460 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6461 Opc == BinaryOperator::PtrMemI);
6462 break;
6463 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006464 case BinaryOperator::Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006465 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6466 Opc == BinaryOperator::Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006467 break;
6468 case BinaryOperator::Rem:
6469 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6470 break;
6471 case BinaryOperator::Add:
6472 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6473 break;
6474 case BinaryOperator::Sub:
6475 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6476 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006477 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006478 case BinaryOperator::Shr:
6479 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6480 break;
6481 case BinaryOperator::LE:
6482 case BinaryOperator::LT:
6483 case BinaryOperator::GE:
6484 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006485 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006486 break;
6487 case BinaryOperator::EQ:
6488 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006489 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006490 break;
6491 case BinaryOperator::And:
6492 case BinaryOperator::Xor:
6493 case BinaryOperator::Or:
6494 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6495 break;
6496 case BinaryOperator::LAnd:
6497 case BinaryOperator::LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00006498 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006499 break;
6500 case BinaryOperator::MulAssign:
6501 case BinaryOperator::DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006502 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6503 Opc == BinaryOperator::DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006504 CompLHSTy = CompResultTy;
6505 if (!CompResultTy.isNull())
6506 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006507 break;
6508 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006509 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6510 CompLHSTy = CompResultTy;
6511 if (!CompResultTy.isNull())
6512 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006513 break;
6514 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006515 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6516 if (!CompResultTy.isNull())
6517 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006518 break;
6519 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006520 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6521 if (!CompResultTy.isNull())
6522 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006523 break;
6524 case BinaryOperator::ShlAssign:
6525 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006526 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6527 CompLHSTy = CompResultTy;
6528 if (!CompResultTy.isNull())
6529 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006530 break;
6531 case BinaryOperator::AndAssign:
6532 case BinaryOperator::XorAssign:
6533 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006534 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6535 CompLHSTy = CompResultTy;
6536 if (!CompResultTy.isNull())
6537 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006538 break;
6539 case BinaryOperator::Comma:
6540 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6541 break;
6542 }
6543 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006544 return ExprError();
Fariborz Jahanian57dae1a2010-08-16 21:51:12 +00006545 if (ResultTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6546 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
6547 Diag(OpLoc, diag::err_assignment_requires_nonfragile_object)
6548 << ResultTy;
6549 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006550 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006551 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6552 else
6553 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006554 CompLHSTy, CompResultTy,
6555 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006556}
6557
Sebastian Redlaee3c932009-10-27 12:10:02 +00006558/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6559/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006560static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6561 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00006562 const PartialDiagnostic &FirstNote,
6563 SourceRange FirstParenRange,
6564 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006565 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00006566 Self.Diag(Loc, PD);
6567
6568 if (!FirstNote.getDiagID())
6569 return;
6570
6571 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6572 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6573 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006574 return;
6575 }
6576
Douglas Gregor55b38842010-04-14 16:09:52 +00006577 Self.Diag(Loc, FirstNote)
6578 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00006579 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006580
Douglas Gregor55b38842010-04-14 16:09:52 +00006581 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00006582 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006583
Douglas Gregor827feec2010-01-08 00:20:23 +00006584 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6585 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6586 // We can't display the parentheses, so just dig the
6587 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00006588 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00006589 return;
6590 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006591
Douglas Gregor55b38842010-04-14 16:09:52 +00006592 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00006593 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6594 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006595}
6596
Sebastian Redlaee3c932009-10-27 12:10:02 +00006597/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6598/// operators are mixed in a way that suggests that the programmer forgot that
6599/// comparison operators have higher precedence. The most typical example of
6600/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006601static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6602 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006603 typedef BinaryOperator BinOp;
6604 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6605 rhsopc = static_cast<BinOp::Opcode>(-1);
6606 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006607 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006608 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006609 rhsopc = BO->getOpcode();
6610
6611 // Subs are not binary operators.
6612 if (lhsopc == -1 && rhsopc == -1)
6613 return;
6614
6615 // Bitwise operations are sometimes used as eager logical ops.
6616 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006617 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6618 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006619 return;
6620
Sebastian Redlaee3c932009-10-27 12:10:02 +00006621 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006622 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006623 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006624 << SourceRange(lhs->getLocStart(), OpLoc)
6625 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006626 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006627 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006628 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6629 Self.PDiag(diag::note_precedence_bitwise_silence)
6630 << BinOp::getOpcodeStr(lhsopc),
6631 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00006632 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006633 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006634 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006635 << SourceRange(OpLoc, rhs->getLocEnd())
6636 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006637 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006638 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006639 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6640 Self.PDiag(diag::note_precedence_bitwise_silence)
6641 << BinOp::getOpcodeStr(rhsopc),
6642 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006643}
6644
6645/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6646/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6647/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6648static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6649 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006650 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006651 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6652}
6653
Reid Spencer5f016e22007-07-11 17:01:13 +00006654// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006655Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6656 tok::TokenKind Kind,
6657 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006658 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006659 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006660
Steve Narofff69936d2007-09-16 03:34:24 +00006661 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6662 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006663
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006664 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6665 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6666
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006667 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6668}
6669
6670Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6671 BinaryOperator::Opcode Opc,
6672 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006673 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006674 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006675 rhs->getType()->isOverloadableType())) {
6676 // Find all of the overloaded operators visible from this
6677 // point. We perform both an operator-name lookup from the local
6678 // scope and an argument-dependent lookup based on the types of
6679 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006680 UnresolvedSet<16> Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006681 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006682 if (S && OverOp != OO_None)
6683 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6684 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006685
Douglas Gregor063daf62009-03-13 18:40:31 +00006686 // Build the (potentially-overloaded, potentially-dependent)
6687 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006688 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006689 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006690
Douglas Gregoreaebc752008-11-06 23:29:22 +00006691 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006692 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006693}
6694
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006695Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006696 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006697 ExprArg InputArg) {
6698 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006699
Mike Stump390b4cc2009-05-16 07:39:55 +00006700 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006701 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006702 QualType resultType;
6703 switch (Opc) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006704 case UnaryOperator::PreInc:
6705 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006706 case UnaryOperator::PostInc:
6707 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006708 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006709 Opc == UnaryOperator::PreInc ||
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006710 Opc == UnaryOperator::PostInc,
6711 Opc == UnaryOperator::PreInc ||
6712 Opc == UnaryOperator::PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00006713 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006714 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006715 resultType = CheckAddressOfOperand(Input, OpLoc);
6716 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006717 case UnaryOperator::Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00006718 DefaultFunctionArrayLvalueConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006719 resultType = CheckIndirectionOperand(Input, OpLoc);
6720 break;
6721 case UnaryOperator::Plus:
6722 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006723 UsualUnaryConversions(Input);
6724 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006725 if (resultType->isDependentType())
6726 break;
Douglas Gregor00619622010-06-22 23:41:02 +00006727 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
6728 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00006729 break;
6730 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6731 resultType->isEnumeralType())
6732 break;
6733 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6734 Opc == UnaryOperator::Plus &&
6735 resultType->isPointerType())
6736 break;
6737
Sebastian Redl0eb23302009-01-19 00:08:26 +00006738 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6739 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006740 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006741 UsualUnaryConversions(Input);
6742 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006743 if (resultType->isDependentType())
6744 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006745 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6746 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6747 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006748 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006749 << resultType << Input->getSourceRange();
Douglas Gregorf6094622010-07-23 15:58:24 +00006750 else if (!resultType->hasIntegerRepresentation())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006751 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6752 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006753 break;
6754 case UnaryOperator::LNot: // logical negation
6755 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00006756 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006757 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006758 if (resultType->isDependentType())
6759 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006760 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006761 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6762 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006763 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006764 // In C++, it's bool. C++ 5.3.1p8
6765 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006766 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006767 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006768 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006769 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006770 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006771 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006772 resultType = Input->getType();
6773 break;
6774 }
6775 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006776 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006777
6778 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006779 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006780}
6781
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006782Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6783 UnaryOperator::Opcode Opc,
6784 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006785 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006786 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6787 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006788 // Find all of the overloaded operators visible from this
6789 // point. We perform both an operator-name lookup from the local
6790 // scope and an argument-dependent lookup based on the types of
6791 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006792 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006793 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006794 if (S && OverOp != OO_None)
6795 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6796 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006797
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006798 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6799 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006800
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006801 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6802}
6803
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006804// Unary Operators. 'Tok' is the token for the operator.
6805Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6806 tok::TokenKind Op, ExprArg input) {
6807 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6808}
6809
Steve Naroff1b273c42007-09-16 14:56:35 +00006810/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006811Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6812 SourceLocation LabLoc,
6813 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006814 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006815 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006816
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006817 // If we haven't seen this label yet, create a forward reference. It
6818 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006819 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006820 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006821
Reid Spencer5f016e22007-07-11 17:01:13 +00006822 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006823 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6824 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006825}
6826
Sebastian Redlf53597f2009-03-15 17:47:39 +00006827Sema::OwningExprResult
6828Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6829 SourceLocation RPLoc) { // "({..})"
6830 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006831 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6832 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6833
Douglas Gregordd8f5692010-03-10 04:54:39 +00006834 bool isFileScope
6835 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00006836 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006837 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006838
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006839 // FIXME: there are a variety of strange constraints to enforce here, for
6840 // example, it is not possible to goto into a stmt expression apparently.
6841 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006842
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006843 // If there are sub stmts in the compound stmt, take the type of the last one
6844 // as the type of the stmtexpr.
6845 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006846
Chris Lattner611b2ec2008-07-26 19:51:01 +00006847 if (!Compound->body_empty()) {
6848 Stmt *LastStmt = Compound->body_back();
6849 // If LastStmt is a label, skip down through into the body.
6850 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6851 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006852
Chris Lattner611b2ec2008-07-26 19:51:01 +00006853 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006854 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006855 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006856
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006857 // FIXME: Check that expression type is complete/non-abstract; statement
6858 // expressions are not lvalues.
6859
Sebastian Redlf53597f2009-03-15 17:47:39 +00006860 substmt.release();
6861 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006862}
Steve Naroffd34e9152007-08-01 22:05:33 +00006863
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006864Sema::OwningExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
6865 TypeSourceInfo *TInfo,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006866 OffsetOfComponent *CompPtr,
6867 unsigned NumComponents,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006868 SourceLocation RParenLoc) {
6869 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006870 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006871 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006872
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006873 // We must have at least one component that refers to the type, and the first
6874 // one is known to be a field designator. Verify that the ArgTy represents
6875 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006876 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006877 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
6878 << ArgTy << TypeRange);
6879
6880 // Type must be complete per C99 7.17p3 because a declaring a variable
6881 // with an incomplete type would be ill-formed.
6882 if (!Dependent
6883 && RequireCompleteType(BuiltinLoc, ArgTy,
6884 PDiag(diag::err_offsetof_incomplete_type)
6885 << TypeRange))
6886 return ExprError();
6887
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006888 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6889 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006890 // FIXME: This diagnostic isn't actually visible because the location is in
6891 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006892 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006893 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6894 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006895
6896 bool DidWarnAboutNonPOD = false;
6897 QualType CurrentType = ArgTy;
6898 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
6899 llvm::SmallVector<OffsetOfNode, 4> Comps;
6900 llvm::SmallVector<Expr*, 4> Exprs;
6901 for (unsigned i = 0; i != NumComponents; ++i) {
6902 const OffsetOfComponent &OC = CompPtr[i];
6903 if (OC.isBrackets) {
6904 // Offset of an array sub-field. TODO: Should we allow vector elements?
6905 if (!CurrentType->isDependentType()) {
6906 const ArrayType *AT = Context.getAsArrayType(CurrentType);
6907 if(!AT)
6908 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6909 << CurrentType);
6910 CurrentType = AT->getElementType();
6911 } else
6912 CurrentType = Context.DependentTy;
6913
6914 // The expression must be an integral expression.
6915 // FIXME: An integral constant expression?
6916 Expr *Idx = static_cast<Expr*>(OC.U.E);
6917 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
6918 !Idx->getType()->isIntegerType())
6919 return ExprError(Diag(Idx->getLocStart(),
6920 diag::err_typecheck_subscript_not_integer)
6921 << Idx->getSourceRange());
6922
6923 // Record this array index.
6924 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
6925 Exprs.push_back(Idx);
6926 continue;
6927 }
6928
6929 // Offset of a field.
6930 if (CurrentType->isDependentType()) {
6931 // We have the offset of a field, but we can't look into the dependent
6932 // type. Just record the identifier of the field.
6933 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
6934 CurrentType = Context.DependentTy;
6935 continue;
6936 }
6937
6938 // We need to have a complete type to look into.
6939 if (RequireCompleteType(OC.LocStart, CurrentType,
6940 diag::err_offsetof_incomplete_type))
6941 return ExprError();
6942
6943 // Look for the designated field.
6944 const RecordType *RC = CurrentType->getAs<RecordType>();
6945 if (!RC)
6946 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6947 << CurrentType);
6948 RecordDecl *RD = RC->getDecl();
6949
6950 // C++ [lib.support.types]p5:
6951 // The macro offsetof accepts a restricted set of type arguments in this
6952 // International Standard. type shall be a POD structure or a POD union
6953 // (clause 9).
6954 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6955 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6956 DiagRuntimeBehavior(BuiltinLoc,
6957 PDiag(diag::warn_offsetof_non_pod_type)
6958 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6959 << CurrentType))
6960 DidWarnAboutNonPOD = true;
6961 }
6962
6963 // Look for the field.
6964 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6965 LookupQualifiedName(R, RD);
6966 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
6967 if (!MemberDecl)
6968 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6969 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
6970 OC.LocEnd));
6971
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00006972 // C99 7.17p3:
6973 // (If the specified member is a bit-field, the behavior is undefined.)
6974 //
6975 // We diagnose this as an error.
6976 if (MemberDecl->getBitWidth()) {
6977 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
6978 << MemberDecl->getDeclName()
6979 << SourceRange(BuiltinLoc, RParenLoc);
6980 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
6981 return ExprError();
6982 }
Eli Friedman19410a72010-08-05 10:11:36 +00006983
6984 RecordDecl *Parent = MemberDecl->getParent();
6985 bool AnonStructUnion = Parent->isAnonymousStructOrUnion();
6986 if (AnonStructUnion) {
6987 do {
6988 Parent = cast<RecordDecl>(Parent->getParent());
6989 } while (Parent->isAnonymousStructOrUnion());
6990 }
6991
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006992 // If the member was found in a base class, introduce OffsetOfNodes for
6993 // the base class indirections.
6994 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
6995 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00006996 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006997 CXXBasePath &Path = Paths.front();
6998 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
6999 B != BEnd; ++B)
7000 Comps.push_back(OffsetOfNode(B->Base));
7001 }
Eli Friedman19410a72010-08-05 10:11:36 +00007002
7003 if (AnonStructUnion) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007004 llvm::SmallVector<FieldDecl*, 4> Path;
7005 BuildAnonymousStructUnionMemberPath(MemberDecl, Path);
7006 unsigned n = Path.size();
7007 for (int j = n - 1; j > -1; --j)
7008 Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd));
7009 } else {
7010 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
7011 }
7012 CurrentType = MemberDecl->getType().getNonReferenceType();
7013 }
7014
7015 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
7016 TInfo, Comps.data(), Comps.size(),
7017 Exprs.data(), Exprs.size(), RParenLoc));
7018}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007019
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007020Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
7021 SourceLocation BuiltinLoc,
7022 SourceLocation TypeLoc,
7023 TypeTy *argty,
7024 OffsetOfComponent *CompPtr,
7025 unsigned NumComponents,
7026 SourceLocation RPLoc) {
7027
7028 TypeSourceInfo *ArgTInfo;
7029 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
7030 if (ArgTy.isNull())
7031 return ExprError();
7032
Eli Friedman5a15dc12010-08-05 10:15:45 +00007033 if (!ArgTInfo)
7034 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
7035
7036 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
7037 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007038}
7039
7040
Sebastian Redlf53597f2009-03-15 17:47:39 +00007041Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
7042 TypeTy *arg1,TypeTy *arg2,
7043 SourceLocation RPLoc) {
Abramo Bagnara3fcb73d2010-08-10 08:50:03 +00007044 TypeSourceInfo *argTInfo1;
7045 QualType argT1 = GetTypeFromParser(arg1, &argTInfo1);
7046 TypeSourceInfo *argTInfo2;
7047 QualType argT2 = GetTypeFromParser(arg2, &argTInfo2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007048
Steve Naroffd34e9152007-08-01 22:05:33 +00007049 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00007050
Abramo Bagnara3fcb73d2010-08-10 08:50:03 +00007051 return BuildTypesCompatibleExpr(BuiltinLoc, argTInfo1, argTInfo2, RPLoc);
7052}
7053
7054Sema::OwningExprResult
7055Sema::BuildTypesCompatibleExpr(SourceLocation BuiltinLoc,
7056 TypeSourceInfo *argTInfo1,
7057 TypeSourceInfo *argTInfo2,
7058 SourceLocation RPLoc) {
Douglas Gregorc12a9c52009-05-19 22:28:02 +00007059 if (getLangOptions().CPlusPlus) {
7060 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
7061 << SourceRange(BuiltinLoc, RPLoc);
7062 return ExprError();
7063 }
7064
Sebastian Redlf53597f2009-03-15 17:47:39 +00007065 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
Abramo Bagnara3fcb73d2010-08-10 08:50:03 +00007066 argTInfo1, argTInfo2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00007067}
7068
Abramo Bagnara3fcb73d2010-08-10 08:50:03 +00007069
Sebastian Redlf53597f2009-03-15 17:47:39 +00007070Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
7071 ExprArg cond,
7072 ExprArg expr1, ExprArg expr2,
7073 SourceLocation RPLoc) {
7074 Expr *CondExpr = static_cast<Expr*>(cond.get());
7075 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
7076 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007077
Steve Naroffd04fdd52007-08-03 21:21:27 +00007078 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
7079
Sebastian Redl28507842009-02-26 14:39:58 +00007080 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00007081 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00007082 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00007083 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00007084 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00007085 } else {
7086 // The conditional expression is required to be a constant expression.
7087 llvm::APSInt condEval(32);
7088 SourceLocation ExpLoc;
7089 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00007090 return ExprError(Diag(ExpLoc,
7091 diag::err_typecheck_choose_expr_requires_constant)
7092 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00007093
Sebastian Redl28507842009-02-26 14:39:58 +00007094 // If the condition is > zero, then the AST type is the same as the LSHExpr.
7095 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00007096 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
7097 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00007098 }
7099
Sebastian Redlf53597f2009-03-15 17:47:39 +00007100 cond.release(); expr1.release(); expr2.release();
7101 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00007102 resType, RPLoc,
7103 resType->isDependentType(),
7104 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00007105}
7106
Steve Naroff4eb206b2008-09-03 18:15:37 +00007107//===----------------------------------------------------------------------===//
7108// Clang Extensions.
7109//===----------------------------------------------------------------------===//
7110
7111/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00007112void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007113 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
7114 PushBlockScope(BlockScope, Block);
7115 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00007116 if (BlockScope)
7117 PushDeclContext(BlockScope, Block);
7118 else
7119 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00007120}
7121
Mike Stump98eb8a72009-02-04 22:31:32 +00007122void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00007123 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007124 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007125
John McCallbf1a0282010-06-04 23:28:52 +00007126 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall82dc0092010-06-04 11:21:44 +00007127 CurBlock->TheDecl->setSignatureAsWritten(Sig);
John McCallbf1a0282010-06-04 23:28:52 +00007128 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00007129
John McCallc71a4912010-06-04 19:02:56 +00007130 bool isVariadic;
John McCall82dc0092010-06-04 11:21:44 +00007131 QualType RetTy;
7132 if (const FunctionType *Fn = T->getAs<FunctionType>()) {
John McCallc71a4912010-06-04 19:02:56 +00007133 CurBlock->FunctionType = T;
John McCall82dc0092010-06-04 11:21:44 +00007134 RetTy = Fn->getResultType();
John McCallc71a4912010-06-04 19:02:56 +00007135 isVariadic =
John McCall82dc0092010-06-04 11:21:44 +00007136 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
7137 } else {
7138 RetTy = T;
John McCallc71a4912010-06-04 19:02:56 +00007139 isVariadic = false;
John McCall82dc0092010-06-04 11:21:44 +00007140 }
Mike Stump1eb44332009-09-09 15:08:12 +00007141
John McCallc71a4912010-06-04 19:02:56 +00007142 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00007143
John McCall82dc0092010-06-04 11:21:44 +00007144 // Don't allow returning an array by value.
7145 if (RetTy->isArrayType()) {
7146 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
Mike Stump98eb8a72009-02-04 22:31:32 +00007147 return;
7148 }
7149
John McCall82dc0092010-06-04 11:21:44 +00007150 // Don't allow returning a objc interface by value.
7151 if (RetTy->isObjCObjectType()) {
7152 Diag(ParamInfo.getSourceRange().getBegin(),
7153 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
7154 return;
7155 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007156
John McCall82dc0092010-06-04 11:21:44 +00007157 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00007158 // return type. TODO: what should we do with declarators like:
7159 // ^ * { ... }
7160 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00007161 if (RetTy != Context.DependentTy)
7162 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007163
John McCall82dc0092010-06-04 11:21:44 +00007164 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00007165 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall82dc0092010-06-04 11:21:44 +00007166 if (isa<FunctionProtoType>(T)) {
7167 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
7168 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
7169 ParmVarDecl *Param = TL.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00007170 if (Param->getIdentifier() == 0 &&
7171 !Param->isImplicit() &&
7172 !Param->isInvalidDecl() &&
7173 !getLangOptions().CPlusPlus)
7174 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00007175 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00007176 }
John McCall82dc0092010-06-04 11:21:44 +00007177
7178 // Fake up parameter variables if we have a typedef, like
7179 // ^ fntype { ... }
7180 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
7181 for (FunctionProtoType::arg_type_iterator
7182 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
7183 ParmVarDecl *Param =
7184 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
7185 ParamInfo.getSourceRange().getBegin(),
7186 *I);
John McCallc71a4912010-06-04 19:02:56 +00007187 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00007188 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00007189 }
John McCall82dc0092010-06-04 11:21:44 +00007190
John McCallc71a4912010-06-04 19:02:56 +00007191 // Set the parameters on the block decl.
7192 if (!Params.empty())
7193 CurBlock->TheDecl->setParams(Params.data(), Params.size());
John McCall82dc0092010-06-04 11:21:44 +00007194
7195 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007196 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00007197
John McCallc71a4912010-06-04 19:02:56 +00007198 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00007199 Diag(ParamInfo.getAttributes()->getLoc(),
7200 diag::warn_attribute_sentinel_not_variadic) << 1;
7201 // FIXME: remove the attribute.
7202 }
7203
7204 // Put the parameter variables in scope. We can bail out immediately
7205 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00007206 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00007207 return;
7208
John McCall053f4bd2010-03-22 09:20:08 +00007209 bool ShouldCheckShadow =
7210 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
7211
Steve Naroff090276f2008-10-10 01:28:17 +00007212 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00007213 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
7214 (*AI)->setOwningFunction(CurBlock->TheDecl);
7215
Steve Naroff090276f2008-10-10 01:28:17 +00007216 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00007217 if ((*AI)->getIdentifier()) {
7218 if (ShouldCheckShadow)
7219 CheckShadow(CurBlock->TheScope, *AI);
7220
Steve Naroff090276f2008-10-10 01:28:17 +00007221 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00007222 }
John McCall7a9813c2010-01-22 00:28:27 +00007223 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00007224}
7225
7226/// ActOnBlockError - If there is an error parsing a block, this callback
7227/// is invoked to pop the information about the block from the action impl.
7228void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00007229 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00007230 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007231 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00007232 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00007233}
7234
7235/// ActOnBlockStmtExpr - This is called when the body of a block statement
7236/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00007237Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
7238 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00007239 // If blocks are disabled, emit an error.
7240 if (!LangOpts.Blocks)
7241 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00007242
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007243 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00007244
Steve Naroff090276f2008-10-10 01:28:17 +00007245 PopDeclContext();
7246
Steve Naroff4eb206b2008-09-03 18:15:37 +00007247 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00007248 if (!BSI->ReturnType.isNull())
7249 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007250
Mike Stump56925862009-07-28 22:04:01 +00007251 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00007252 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00007253
7254 // If the user wrote a function type in some form, try to use that.
7255 if (!BSI->FunctionType.isNull()) {
7256 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
7257
7258 FunctionType::ExtInfo Ext = FTy->getExtInfo();
7259 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
7260
7261 // Turn protoless block types into nullary block types.
7262 if (isa<FunctionNoProtoType>(FTy)) {
7263 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7264 false, false, 0, 0, Ext);
7265
7266 // Otherwise, if we don't need to change anything about the function type,
7267 // preserve its sugar structure.
7268 } else if (FTy->getResultType() == RetTy &&
7269 (!NoReturn || FTy->getNoReturnAttr())) {
7270 BlockTy = BSI->FunctionType;
7271
7272 // Otherwise, make the minimal modifications to the function type.
7273 } else {
7274 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
7275 BlockTy = Context.getFunctionType(RetTy,
7276 FPT->arg_type_begin(),
7277 FPT->getNumArgs(),
7278 FPT->isVariadic(),
7279 /*quals*/ 0,
7280 FPT->hasExceptionSpec(),
7281 FPT->hasAnyExceptionSpec(),
7282 FPT->getNumExceptions(),
7283 FPT->exception_begin(),
7284 Ext);
7285 }
7286
7287 // If we don't have a function type, just build one from nothing.
7288 } else {
7289 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7290 false, false, 0, 0,
7291 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
7292 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007293
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007294 // FIXME: Check that return/parameter types are complete/non-abstract
John McCallc71a4912010-06-04 19:02:56 +00007295 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
7296 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00007297 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007298
Chris Lattner17a78302009-04-19 05:28:12 +00007299 // If needed, diagnose invalid gotos and switches in the block.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007300 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
Chris Lattner17a78302009-04-19 05:28:12 +00007301 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00007302
Anders Carlssone9146f22009-05-01 19:49:17 +00007303 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stumpa3899eb2010-01-19 23:08:01 +00007304
7305 bool Good = true;
7306 // Check goto/label use.
7307 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
7308 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
7309 LabelStmt *L = I->second;
7310
7311 // Verify that we have no forward references left. If so, there was a goto
7312 // or address of a label taken, but no definition of it.
7313 if (L->getSubStmt() != 0)
7314 continue;
7315
7316 // Emit error.
7317 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
7318 Good = false;
7319 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007320 if (!Good) {
7321 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00007322 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007323 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007324
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007325 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00007326 const sema::AnalysisBasedWarnings::Policy &WP =
7327 AnalysisWarnings.getDefaultPolicy();
7328 AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007329
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007330 Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
7331 BSI->hasBlockDeclRefExprs);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007332 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007333 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00007334}
7335
Sebastian Redlf53597f2009-03-15 17:47:39 +00007336Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
7337 ExprArg expr, TypeTy *type,
7338 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00007339 TypeSourceInfo *TInfo;
7340 QualType T = GetTypeFromParser(type, &TInfo);
7341 return BuildVAArgExpr(BuiltinLoc, move(expr), TInfo, RPLoc);
7342}
7343
7344Sema::OwningExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
7345 ExprArg expr, TypeSourceInfo *TInfo,
7346 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00007347 Expr *E = static_cast<Expr*>(expr.get());
7348 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00007349
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007350 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007351
7352 // Get the va_list type
7353 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00007354 if (VaListType->isArrayType()) {
7355 // Deal with implicit array decay; for example, on x86-64,
7356 // va_list is an array, but it's supposed to decay to
7357 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007358 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00007359 // Make sure the input expression also decays appropriately.
7360 UsualUnaryConversions(E);
7361 } else {
7362 // Otherwise, the va_list argument must be an l-value because
7363 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00007364 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00007365 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00007366 return ExprError();
7367 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007368
Douglas Gregordd027302009-05-19 23:10:31 +00007369 if (!E->isTypeDependent() &&
7370 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00007371 return ExprError(Diag(E->getLocStart(),
7372 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00007373 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00007374 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007375
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007376 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007377 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007378
Sebastian Redlf53597f2009-03-15 17:47:39 +00007379 expr.release();
Abramo Bagnara2cad9002010-08-10 10:06:15 +00007380 QualType T = TInfo->getType().getNonLValueExprType(Context);
7381 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007382}
7383
Sebastian Redlf53597f2009-03-15 17:47:39 +00007384Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007385 // The type of __null will be int or long, depending on the size of
7386 // pointers on the target.
7387 QualType Ty;
7388 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7389 Ty = Context.IntTy;
7390 else
7391 Ty = Context.LongTy;
7392
Sebastian Redlf53597f2009-03-15 17:47:39 +00007393 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007394}
7395
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007396static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00007397 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007398 if (!SemaRef.getLangOptions().ObjC1)
7399 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007400
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007401 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7402 if (!PT)
7403 return;
7404
7405 // Check if the destination is of type 'id'.
7406 if (!PT->isObjCIdType()) {
7407 // Check if the destination is the 'NSString' interface.
7408 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7409 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7410 return;
7411 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007412
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007413 // Strip off any parens and casts.
7414 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7415 if (!SL || SL->isWide())
7416 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007417
Douglas Gregor849b2432010-03-31 17:46:05 +00007418 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007419}
7420
Chris Lattner5cf216b2008-01-04 18:04:52 +00007421bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7422 SourceLocation Loc,
7423 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00007424 Expr *SrcExpr, AssignmentAction Action,
7425 bool *Complained) {
7426 if (Complained)
7427 *Complained = false;
7428
Chris Lattner5cf216b2008-01-04 18:04:52 +00007429 // Decode the result (notice that AST's are still created for extensions).
7430 bool isInvalid = false;
7431 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00007432 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007433
Chris Lattner5cf216b2008-01-04 18:04:52 +00007434 switch (ConvTy) {
7435 default: assert(0 && "Unknown conversion type");
7436 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007437 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00007438 DiagKind = diag::ext_typecheck_convert_pointer_int;
7439 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007440 case IntToPointer:
7441 DiagKind = diag::ext_typecheck_convert_int_pointer;
7442 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007443 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00007444 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007445 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7446 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00007447 case IncompatiblePointerSign:
7448 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7449 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007450 case FunctionVoidPointer:
7451 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7452 break;
7453 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00007454 // If the qualifiers lost were because we were applying the
7455 // (deprecated) C++ conversion from a string literal to a char*
7456 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7457 // Ideally, this check would be performed in
7458 // CheckPointerTypesForAssignment. However, that would require a
7459 // bit of refactoring (so that the second argument is an
7460 // expression, rather than a type), which should be done as part
7461 // of a larger effort to fix CheckPointerTypesForAssignment for
7462 // C++ semantics.
7463 if (getLangOptions().CPlusPlus &&
7464 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7465 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007466 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7467 break;
Sean Huntc9132b62009-11-08 07:46:34 +00007468 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00007469 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00007470 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007471 case IntToBlockPointer:
7472 DiagKind = diag::err_int_to_block_pointer;
7473 break;
7474 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00007475 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007476 break;
Steve Naroff39579072008-10-14 22:18:38 +00007477 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00007478 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00007479 // it can give a more specific diagnostic.
7480 DiagKind = diag::warn_incompatible_qualified_id;
7481 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007482 case IncompatibleVectors:
7483 DiagKind = diag::warn_incompatible_vectors;
7484 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007485 case Incompatible:
7486 DiagKind = diag::err_typecheck_convert_incompatible;
7487 isInvalid = true;
7488 break;
7489 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007490
Douglas Gregord4eea832010-04-09 00:35:39 +00007491 QualType FirstType, SecondType;
7492 switch (Action) {
7493 case AA_Assigning:
7494 case AA_Initializing:
7495 // The destination type comes first.
7496 FirstType = DstType;
7497 SecondType = SrcType;
7498 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007499
Douglas Gregord4eea832010-04-09 00:35:39 +00007500 case AA_Returning:
7501 case AA_Passing:
7502 case AA_Converting:
7503 case AA_Sending:
7504 case AA_Casting:
7505 // The source type comes first.
7506 FirstType = SrcType;
7507 SecondType = DstType;
7508 break;
7509 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007510
Douglas Gregord4eea832010-04-09 00:35:39 +00007511 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007512 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00007513 if (Complained)
7514 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007515 return isInvalid;
7516}
Anders Carlssone21555e2008-11-30 19:50:32 +00007517
Chris Lattner3bf68932009-04-25 21:59:05 +00007518bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007519 llvm::APSInt ICEResult;
7520 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7521 if (Result)
7522 *Result = ICEResult;
7523 return false;
7524 }
7525
Anders Carlssone21555e2008-11-30 19:50:32 +00007526 Expr::EvalResult EvalResult;
7527
Mike Stumpeed9cac2009-02-19 03:04:26 +00007528 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00007529 EvalResult.HasSideEffects) {
7530 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7531
7532 if (EvalResult.Diag) {
7533 // We only show the note if it's not the usual "invalid subexpression"
7534 // or if it's actually in a subexpression.
7535 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7536 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7537 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7538 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007539
Anders Carlssone21555e2008-11-30 19:50:32 +00007540 return true;
7541 }
7542
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007543 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7544 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00007545
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007546 if (EvalResult.Diag &&
7547 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7548 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007549
Anders Carlssone21555e2008-11-30 19:50:32 +00007550 if (Result)
7551 *Result = EvalResult.Val.getInt();
7552 return false;
7553}
Douglas Gregore0762c92009-06-19 23:52:42 +00007554
Douglas Gregor2afce722009-11-26 00:44:06 +00007555void
Mike Stump1eb44332009-09-09 15:08:12 +00007556Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007557 ExprEvalContexts.push_back(
7558 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007559}
7560
Mike Stump1eb44332009-09-09 15:08:12 +00007561void
Douglas Gregor2afce722009-11-26 00:44:06 +00007562Sema::PopExpressionEvaluationContext() {
7563 // Pop the current expression evaluation context off the stack.
7564 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7565 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007566
Douglas Gregor06d33692009-12-12 07:57:52 +00007567 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7568 if (Rec.PotentiallyReferenced) {
7569 // Mark any remaining declarations in the current position of the stack
7570 // as "referenced". If they were not meant to be referenced, semantic
7571 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007572 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00007573 I = Rec.PotentiallyReferenced->begin(),
7574 IEnd = Rec.PotentiallyReferenced->end();
7575 I != IEnd; ++I)
7576 MarkDeclarationReferenced(I->first, I->second);
7577 }
7578
7579 if (Rec.PotentiallyDiagnosed) {
7580 // Emit any pending diagnostics.
7581 for (PotentiallyEmittedDiagnostics::iterator
7582 I = Rec.PotentiallyDiagnosed->begin(),
7583 IEnd = Rec.PotentiallyDiagnosed->end();
7584 I != IEnd; ++I)
7585 Diag(I->first, I->second);
7586 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007587 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007588
7589 // When are coming out of an unevaluated context, clear out any
7590 // temporaries that we may have created as part of the evaluation of
7591 // the expression in that context: they aren't relevant because they
7592 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007593 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00007594 ExprTemporaries.size() > Rec.NumTemporaries)
7595 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7596 ExprTemporaries.end());
7597
7598 // Destroy the popped expression evaluation record.
7599 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007600}
Douglas Gregore0762c92009-06-19 23:52:42 +00007601
7602/// \brief Note that the given declaration was referenced in the source code.
7603///
7604/// This routine should be invoke whenever a given declaration is referenced
7605/// in the source code, and where that reference occurred. If this declaration
7606/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7607/// C99 6.9p3), then the declaration will be marked as used.
7608///
7609/// \param Loc the location where the declaration was referenced.
7610///
7611/// \param D the declaration that has been referenced by the source code.
7612void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7613 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007614
Douglas Gregorc070cc62010-06-17 23:14:26 +00007615 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007616 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007617
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007618 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7619 // template or not. The reason for this is that unevaluated expressions
7620 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7621 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007622 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007623 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Douglas Gregore0762c92009-06-19 23:52:42 +00007624 D->setUsed(true);
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007625 return;
7626 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007627
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007628 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7629 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007630
Douglas Gregore0762c92009-06-19 23:52:42 +00007631 // Do not mark anything as "used" within a dependent context; wait for
7632 // an instantiation.
7633 if (CurContext->isDependentContext())
7634 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007635
Douglas Gregor2afce722009-11-26 00:44:06 +00007636 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007637 case Unevaluated:
7638 // We are in an expression that is not potentially evaluated; do nothing.
7639 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007640
Douglas Gregorac7610d2009-06-22 20:57:11 +00007641 case PotentiallyEvaluated:
7642 // We are in a potentially-evaluated expression, so this declaration is
7643 // "used"; handle this below.
7644 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007645
Douglas Gregorac7610d2009-06-22 20:57:11 +00007646 case PotentiallyPotentiallyEvaluated:
7647 // We are in an expression that may be potentially evaluated; queue this
7648 // declaration reference until we know whether the expression is
7649 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007650 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007651 return;
7652 }
Mike Stump1eb44332009-09-09 15:08:12 +00007653
Douglas Gregore0762c92009-06-19 23:52:42 +00007654 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007655 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007656 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007657 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007658 if (!Constructor->isUsed(false))
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007659 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007660 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007661 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007662 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007663 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7664 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007665
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007666 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007667 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007668 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007669 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007670 if (Destructor->isVirtual())
7671 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007672 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7673 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7674 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007675 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00007676 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007677 } else if (MethodDecl->isVirtual())
7678 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007679 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007680 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007681 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007682 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00007683 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007684 bool AlreadyInstantiated = false;
7685 if (FunctionTemplateSpecializationInfo *SpecInfo
7686 = Function->getTemplateSpecializationInfo()) {
7687 if (SpecInfo->getPointOfInstantiation().isInvalid())
7688 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007689 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007690 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007691 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007692 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007693 = Function->getMemberSpecializationInfo()) {
7694 if (MSInfo->getPointOfInstantiation().isInvalid())
7695 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007696 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007697 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007698 AlreadyInstantiated = true;
7699 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007700
Douglas Gregor60406be2010-01-16 22:29:39 +00007701 if (!AlreadyInstantiated) {
7702 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7703 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7704 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7705 Loc));
7706 else
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007707 PendingImplicitInstantiations.push_back(std::make_pair(Function,
Douglas Gregor60406be2010-01-16 22:29:39 +00007708 Loc));
7709 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007710 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007711
Douglas Gregore0762c92009-06-19 23:52:42 +00007712 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007713 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007714
Douglas Gregore0762c92009-06-19 23:52:42 +00007715 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007716 }
Mike Stump1eb44332009-09-09 15:08:12 +00007717
Douglas Gregore0762c92009-06-19 23:52:42 +00007718 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007719 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007720 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007721 Var->getInstantiatedFromStaticDataMember()) {
7722 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7723 assert(MSInfo && "Missing member specialization information?");
7724 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7725 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7726 MSInfo->setPointOfInstantiation(Loc);
7727 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7728 }
7729 }
Mike Stump1eb44332009-09-09 15:08:12 +00007730
Douglas Gregore0762c92009-06-19 23:52:42 +00007731 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007732
Douglas Gregore0762c92009-06-19 23:52:42 +00007733 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007734 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007735 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007736}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007737
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007738namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007739 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007740 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007741 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007742 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
7743 Sema &S;
7744 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007745
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007746 public:
7747 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007748
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007749 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007750
7751 bool TraverseTemplateArgument(const TemplateArgument &Arg);
7752 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007753 };
7754}
7755
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007756bool MarkReferencedDecls::TraverseTemplateArgument(
7757 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007758 if (Arg.getKind() == TemplateArgument::Declaration) {
7759 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
7760 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007761
7762 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007763}
7764
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007765bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007766 if (ClassTemplateSpecializationDecl *Spec
7767 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
7768 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007769 return TraverseTemplateArguments(Args.getFlatArgumentList(),
7770 Args.flat_size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007771 }
7772
Chandler Carruthe3e210c2010-06-10 10:31:57 +00007773 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007774}
7775
7776void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
7777 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007778 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007779}
7780
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007781/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7782/// of the program being compiled.
7783///
7784/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007785/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007786/// possibility that the code will actually be executable. Code in sizeof()
7787/// expressions, code used only during overload resolution, etc., are not
7788/// potentially evaluated. This routine will suppress such diagnostics or,
7789/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007790/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007791/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007792///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007793/// This routine should be used for all diagnostics that describe the run-time
7794/// behavior of a program, such as passing a non-POD value through an ellipsis.
7795/// Failure to do so will likely result in spurious diagnostics or failures
7796/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007797bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007798 const PartialDiagnostic &PD) {
7799 switch (ExprEvalContexts.back().Context ) {
7800 case Unevaluated:
7801 // The argument will never be evaluated, so don't complain.
7802 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007803
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007804 case PotentiallyEvaluated:
7805 Diag(Loc, PD);
7806 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007807
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007808 case PotentiallyPotentiallyEvaluated:
7809 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7810 break;
7811 }
7812
7813 return false;
7814}
7815
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007816bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7817 CallExpr *CE, FunctionDecl *FD) {
7818 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7819 return false;
7820
7821 PartialDiagnostic Note =
7822 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7823 << FD->getDeclName() : PDiag();
7824 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007825
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007826 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007827 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007828 PDiag(diag::err_call_function_incomplete_return)
7829 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007830 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007831 << CE->getSourceRange(),
7832 std::make_pair(NoteLoc, Note)))
7833 return true;
7834
7835 return false;
7836}
7837
John McCall5a881bb2009-10-12 21:59:07 +00007838// Diagnose the common s/=/==/ typo. Note that adding parentheses
7839// will prevent this condition from triggering, which is what we want.
7840void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7841 SourceLocation Loc;
7842
John McCalla52ef082009-11-11 02:41:58 +00007843 unsigned diagnostic = diag::warn_condition_is_assignment;
7844
John McCall5a881bb2009-10-12 21:59:07 +00007845 if (isa<BinaryOperator>(E)) {
7846 BinaryOperator *Op = cast<BinaryOperator>(E);
7847 if (Op->getOpcode() != BinaryOperator::Assign)
7848 return;
7849
John McCallc8d8ac52009-11-12 00:06:05 +00007850 // Greylist some idioms by putting them into a warning subcategory.
7851 if (ObjCMessageExpr *ME
7852 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7853 Selector Sel = ME->getSelector();
7854
John McCallc8d8ac52009-11-12 00:06:05 +00007855 // self = [<foo> init...]
7856 if (isSelfExpr(Op->getLHS())
7857 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7858 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7859
7860 // <foo> = [<bar> nextObject]
7861 else if (Sel.isUnarySelector() &&
7862 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7863 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7864 }
John McCalla52ef082009-11-11 02:41:58 +00007865
John McCall5a881bb2009-10-12 21:59:07 +00007866 Loc = Op->getOperatorLoc();
7867 } else if (isa<CXXOperatorCallExpr>(E)) {
7868 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7869 if (Op->getOperator() != OO_Equal)
7870 return;
7871
7872 Loc = Op->getOperatorLoc();
7873 } else {
7874 // Not an assignment.
7875 return;
7876 }
7877
John McCall5a881bb2009-10-12 21:59:07 +00007878 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007879 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007880
Douglas Gregor55b38842010-04-14 16:09:52 +00007881 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor827feec2010-01-08 00:20:23 +00007882 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregor849b2432010-03-31 17:46:05 +00007883 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor55b38842010-04-14 16:09:52 +00007884 Diag(Loc, diag::note_condition_assign_silence)
7885 << FixItHint::CreateInsertion(Open, "(")
7886 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00007887}
7888
7889bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7890 DiagnoseAssignmentAsCondition(E);
7891
7892 if (!E->isTypeDependent()) {
Douglas Gregora873dfc2010-02-03 00:27:59 +00007893 DefaultFunctionArrayLvalueConversion(E);
John McCall5a881bb2009-10-12 21:59:07 +00007894
7895 QualType T = E->getType();
7896
7897 if (getLangOptions().CPlusPlus) {
7898 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7899 return true;
7900 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7901 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7902 << T << E->getSourceRange();
7903 return true;
7904 }
7905 }
7906
7907 return false;
7908}
Douglas Gregor586596f2010-05-06 17:25:47 +00007909
7910Sema::OwningExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7911 ExprArg SubExpr) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00007912 Expr *Sub = SubExpr.takeAs<Expr>();
7913 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00007914 return ExprError();
7915
Douglas Gregorff331c12010-07-25 18:17:45 +00007916 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregor586596f2010-05-06 17:25:47 +00007917 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00007918
7919 return Owned(Sub);
7920}