blob: 5be017a754114ca22f296328c8ef8a7e883faae3 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor85dabae2009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Ted Kremenekd6b87082010-01-25 04:41:41 +000017#include "clang/Analysis/AnalysisContext.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000021#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000025#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000026#include "clang/Lex/LiteralSupport.h"
27#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000028#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000029#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000030#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000031#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000032using namespace clang;
33
David Chisnall9f57c292009-08-17 16:35:33 +000034
Douglas Gregor171c45a2009-02-18 21:56:37 +000035/// \brief Determine whether the use of this declaration is valid, and
36/// emit any corresponding diagnostics.
37///
38/// This routine diagnoses various problems with referencing
39/// declarations that can occur when using a declaration. For example,
40/// it might warn if a deprecated or unavailable declaration is being
41/// used, or produce an error (and return true) if a C++0x deleted
42/// function is being used.
43///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000044/// If IgnoreDeprecated is set to true, this should not want about deprecated
45/// decls.
46///
Douglas Gregor171c45a2009-02-18 21:56:37 +000047/// \returns true if there was an error (this declaration cannot be
48/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000049///
John McCall28a6aea2009-11-04 02:18:39 +000050bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000051 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000052 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000053 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000054 }
55
Chris Lattnera27dd592009-10-25 17:21:40 +000056 // See if the decl is unavailable
57 if (D->getAttr<UnavailableAttr>()) {
58 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
59 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
60 }
61
Douglas Gregor171c45a2009-02-18 21:56:37 +000062 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000064 if (FD->isDeleted()) {
65 Diag(Loc, diag::err_deleted_function_use);
66 Diag(D->getLocation(), diag::note_unavailable_here) << true;
67 return true;
68 }
Douglas Gregorde681d42009-02-24 04:26:15 +000069 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000070
Douglas Gregor171c45a2009-02-18 21:56:37 +000071 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000072}
73
Fariborz Jahanian027b8862009-05-13 18:09:35 +000074/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000075/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000076/// attribute. It warns if call does not have the sentinel argument.
77///
78void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000079 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000080 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000081 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000082 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000083 int sentinelPos = attr->getSentinel();
84 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000085
Mike Stump87c57ac2009-05-16 07:39:55 +000086 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
87 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000088 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000089 bool warnNotEnoughArgs = false;
90 int isMethod = 0;
91 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
92 // skip over named parameters.
93 ObjCMethodDecl::param_iterator P, E = MD->param_end();
94 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
95 if (nullPos)
96 --nullPos;
97 else
98 ++i;
99 }
100 warnNotEnoughArgs = (P != E || i >= NumArgs);
101 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000102 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000103 // skip over named parameters.
104 ObjCMethodDecl::param_iterator P, E = FD->param_end();
105 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
106 if (nullPos)
107 --nullPos;
108 else
109 ++i;
110 }
111 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000112 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000113 // block or function pointer call.
114 QualType Ty = V->getType();
115 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000116 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000117 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
118 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000119 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
120 unsigned NumArgsInProto = Proto->getNumArgs();
121 unsigned k;
122 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
123 if (nullPos)
124 --nullPos;
125 else
126 ++i;
127 }
128 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
129 }
130 if (Ty->isBlockPointerType())
131 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000133 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000134 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000135 return;
136
137 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000138 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000139 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000140 return;
141 }
142 int sentinel = i;
143 while (sentinelPos > 0 && i < NumArgs-1) {
144 --sentinelPos;
145 ++i;
146 }
147 if (sentinelPos > 0) {
148 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000149 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000150 return;
151 }
152 while (i < NumArgs-1) {
153 ++i;
154 ++sentinel;
155 }
156 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000157 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
158 (!sentinelExpr->getType()->isPointerType() ||
159 !sentinelExpr->isNullPointerConstant(Context,
160 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000161 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000162 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000163 }
164 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000165}
166
Douglas Gregor87f95b02009-02-26 21:00:50 +0000167SourceRange Sema::getExprRange(ExprTy *E) const {
168 Expr *Ex = (Expr *)E;
169 return Ex? Ex->getSourceRange() : SourceRange();
170}
171
Chris Lattner513165e2008-07-25 21:10:04 +0000172//===----------------------------------------------------------------------===//
173// Standard Promotions and Conversions
174//===----------------------------------------------------------------------===//
175
Chris Lattner513165e2008-07-25 21:10:04 +0000176/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
177void Sema::DefaultFunctionArrayConversion(Expr *&E) {
178 QualType Ty = E->getType();
179 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
180
Chris Lattner513165e2008-07-25 21:10:04 +0000181 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000182 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000183 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000184 else if (Ty->isArrayType()) {
185 // In C90 mode, arrays only promote to pointers if the array expression is
186 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
187 // type 'array of type' is converted to an expression that has type 'pointer
188 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
189 // that has type 'array of type' ...". The relevant change is "an lvalue"
190 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000191 //
192 // C++ 4.2p1:
193 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
194 // T" can be converted to an rvalue of type "pointer to T".
195 //
196 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
197 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000198 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
199 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000200 }
Chris Lattner513165e2008-07-25 21:10:04 +0000201}
202
203/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000204/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000205/// sometimes surpressed. For example, the array->pointer conversion doesn't
206/// apply if the array is an argument to the sizeof or address (&) operators.
207/// In these instances, this routine should *not* be called.
208Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
209 QualType Ty = Expr->getType();
210 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000211
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000212 // C99 6.3.1.1p2:
213 //
214 // The following may be used in an expression wherever an int or
215 // unsigned int may be used:
216 // - an object or expression with an integer type whose integer
217 // conversion rank is less than or equal to the rank of int
218 // and unsigned int.
219 // - A bit-field of type _Bool, int, signed int, or unsigned int.
220 //
221 // If an int can represent all values of the original type, the
222 // value is converted to an int; otherwise, it is converted to an
223 // unsigned int. These are called the integer promotions. All
224 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000225 QualType PTy = Context.isPromotableBitField(Expr);
226 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000227 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000228 return Expr;
229 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000230 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000231 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000232 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000233 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000234 }
235
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000236 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000237 return Expr;
238}
239
Chris Lattner2ce500f2008-07-25 22:25:12 +0000240/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000241/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000242/// double. All other argument types are converted by UsualUnaryConversions().
243void Sema::DefaultArgumentPromotion(Expr *&Expr) {
244 QualType Ty = Expr->getType();
245 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner2ce500f2008-07-25 22:25:12 +0000247 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000248 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000249 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000250 return ImpCastExprToType(Expr, Context.DoubleTy,
251 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000252
Chris Lattner2ce500f2008-07-25 22:25:12 +0000253 UsualUnaryConversions(Expr);
254}
255
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000256/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
257/// will warn if the resulting type is not a POD type, and rejects ObjC
258/// interfaces passed by value. This returns true if the argument type is
259/// completely illegal.
260bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000261 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000262
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000263 if (Expr->getType()->isObjCInterfaceType() &&
264 DiagRuntimeBehavior(Expr->getLocStart(),
265 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
266 << Expr->getType() << CT))
267 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000268
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000269 if (!Expr->getType()->isPODType() &&
270 DiagRuntimeBehavior(Expr->getLocStart(),
271 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
272 << Expr->getType() << CT))
273 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000274
275 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000276}
277
278
Chris Lattner513165e2008-07-25 21:10:04 +0000279/// UsualArithmeticConversions - Performs various conversions that are common to
280/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000281/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000282/// responsible for emitting appropriate error diagnostics.
283/// FIXME: verify the conversion rules for "complex int" are consistent with
284/// GCC.
285QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
286 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000287 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000288 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000289
290 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000291
Mike Stump11289f42009-09-09 15:08:12 +0000292 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000293 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000294 QualType lhs =
295 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000296 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000297 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000298
299 // If both types are identical, no conversion is needed.
300 if (lhs == rhs)
301 return lhs;
302
303 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
304 // The caller can deal with this (e.g. pointer + int).
305 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
306 return lhs;
307
Douglas Gregord2c2d172009-05-02 00:36:19 +0000308 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000309 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000310 if (!LHSBitfieldPromoteTy.isNull())
311 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000312 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000313 if (!RHSBitfieldPromoteTy.isNull())
314 rhs = RHSBitfieldPromoteTy;
315
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000316 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000317 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000318 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
319 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000320 return destType;
321}
322
Chris Lattner513165e2008-07-25 21:10:04 +0000323//===----------------------------------------------------------------------===//
324// Semantic Analysis for various Expression Types
325//===----------------------------------------------------------------------===//
326
327
Steve Naroff83895f72007-09-16 03:34:24 +0000328/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000329/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
330/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
331/// multiple tokens. However, the common case is that StringToks points to one
332/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000333///
334Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000335Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000336 assert(NumStringToks && "Must have at least one string!");
337
Chris Lattner8a24e582009-01-16 18:51:42 +0000338 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000339 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000340 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000341
Chris Lattner23b7eb62007-06-15 23:05:46 +0000342 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000343 for (unsigned i = 0; i != NumStringToks; ++i)
344 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000345
Chris Lattner36fc8792008-02-11 00:02:17 +0000346 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000347 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000348 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000349
350 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
351 if (getLangOptions().CPlusPlus)
352 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000353
Chris Lattner36fc8792008-02-11 00:02:17 +0000354 // Get an array type for the string, according to C99 6.4.5. This includes
355 // the nul terminator character as well as the string length for pascal
356 // strings.
357 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000358 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000359 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000360
Chris Lattner5b183d82006-11-10 05:03:26 +0000361 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000362 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000363 Literal.GetStringLength(),
364 Literal.AnyWide, StrTy,
365 &StringTokLocs[0],
366 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000367}
368
Chris Lattner2a9d9892008-10-20 05:16:36 +0000369/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
370/// CurBlock to VD should cause it to be snapshotted (as we do for auto
371/// variables defined outside the block) or false if this is not needed (e.g.
372/// for values inside the block or for globals).
373///
Chris Lattner497d7b02009-04-21 22:26:47 +0000374/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
375/// up-to-date.
376///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000377static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
378 ValueDecl *VD) {
379 // If the value is defined inside the block, we couldn't snapshot it even if
380 // we wanted to.
381 if (CurBlock->TheDecl == VD->getDeclContext())
382 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000383
Chris Lattner2a9d9892008-10-20 05:16:36 +0000384 // If this is an enum constant or function, it is constant, don't snapshot.
385 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
386 return false;
387
388 // If this is a reference to an extern, static, or global variable, no need to
389 // snapshot it.
390 // FIXME: What about 'const' variables in C++?
391 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000392 if (!Var->hasLocalStorage())
393 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattner497d7b02009-04-21 22:26:47 +0000395 // Blocks that have these can't be constant.
396 CurBlock->hasBlockDeclRefExprs = true;
397
398 // If we have nested blocks, the decl may be declared in an outer block (in
399 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
400 // be defined outside all of the current blocks (in which case the blocks do
401 // all get the bit). Walk the nesting chain.
402 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
403 NextBlock = NextBlock->PrevBlockInfo) {
404 // If we found the defining block for the variable, don't mark the block as
405 // having a reference outside it.
406 if (NextBlock->TheDecl == VD->getDeclContext())
407 break;
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattner497d7b02009-04-21 22:26:47 +0000409 // Otherwise, the DeclRef from the inner block causes the outer one to need
410 // a snapshot as well.
411 NextBlock->hasBlockDeclRefExprs = true;
412 }
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattner2a9d9892008-10-20 05:16:36 +0000414 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000415}
416
Chris Lattner2a9d9892008-10-20 05:16:36 +0000417
418
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000419/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000420Sema::OwningExprResult
John McCallce546572009-12-08 09:08:17 +0000421Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000422 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000423 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
424 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000425 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000426 << D->getDeclName();
427 return ExprError();
428 }
Mike Stump11289f42009-09-09 15:08:12 +0000429
Anders Carlsson946b86d2009-06-24 00:10:43 +0000430 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
431 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
432 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
433 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000434 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000435 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000436 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000437 << D->getIdentifier();
438 return ExprError();
439 }
440 }
441 }
442 }
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000444 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000445
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000446 return Owned(DeclRefExpr::Create(Context,
447 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
448 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000449 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000450}
451
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000452/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
453/// variable corresponding to the anonymous union or struct whose type
454/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000455static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
456 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000457 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000458 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000459
Mike Stump87c57ac2009-05-16 07:39:55 +0000460 // FIXME: Once Decls are directly linked together, this will be an O(1)
461 // operation rather than a slow walk through DeclContext's vector (which
462 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000463 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000464 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000465 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000466 D != DEnd; ++D) {
467 if (*D == Record) {
468 // The object for the anonymous struct/union directly
469 // follows its type in the list of declarations.
470 ++D;
471 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000472 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000473 return *D;
474 }
475 }
476
477 assert(false && "Missing object for anonymous record");
478 return 0;
479}
480
Douglas Gregord5846a12009-04-15 06:41:24 +0000481/// \brief Given a field that represents a member of an anonymous
482/// struct/union, build the path from that field's context to the
483/// actual member.
484///
485/// Construct the sequence of field member references we'll have to
486/// perform to get to the field in the anonymous union/struct. The
487/// list of members is built from the field outward, so traverse it
488/// backwards to go from an object in the current context to the field
489/// we found.
490///
491/// \returns The variable from which the field access should begin,
492/// for an anonymous struct/union that is not a member of another
493/// class. Otherwise, returns NULL.
494VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
495 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000496 assert(Field->getDeclContext()->isRecord() &&
497 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
498 && "Field must be stored inside an anonymous struct or union");
499
Douglas Gregord5846a12009-04-15 06:41:24 +0000500 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000501 VarDecl *BaseObject = 0;
502 DeclContext *Ctx = Field->getDeclContext();
503 do {
504 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000505 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000506 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000507 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000508 else {
509 BaseObject = cast<VarDecl>(AnonObject);
510 break;
511 }
512 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000513 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000514 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000515
516 return BaseObject;
517}
518
519Sema::OwningExprResult
520Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
521 FieldDecl *Field,
522 Expr *BaseObjectExpr,
523 SourceLocation OpLoc) {
524 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000525 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000526 AnonFields);
527
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000528 // Build the expression that refers to the base object, from
529 // which we will build a sequence of member references to each
530 // of the anonymous union objects and, eventually, the field we
531 // found via name lookup.
532 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000533 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000534 if (BaseObject) {
535 // BaseObject is an anonymous struct/union variable (and is,
536 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000537 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000538 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000539 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000540 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000541 BaseQuals
542 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000543 } else if (BaseObjectExpr) {
544 // The caller provided the base object expression. Determine
545 // whether its a pointer and whether it adds any qualifiers to the
546 // anonymous struct/union fields we're looking into.
547 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000548 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000549 BaseObjectIsPointer = true;
550 ObjectType = ObjectPtr->getPointeeType();
551 }
John McCall8ccfcb52009-09-24 19:53:00 +0000552 BaseQuals
553 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000554 } else {
555 // We've found a member of an anonymous struct/union that is
556 // inside a non-anonymous struct/union, so in a well-formed
557 // program our base object expression is "this".
558 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
559 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000560 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000561 = Context.getTagDeclType(
562 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
563 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000564 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000565 == Context.getCanonicalType(ThisType)) ||
566 IsDerivedFrom(ThisType, AnonFieldType)) {
567 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000568 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000569 MD->getThisType(Context),
570 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000571 BaseObjectIsPointer = true;
572 }
573 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000574 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
575 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000576 }
John McCall8ccfcb52009-09-24 19:53:00 +0000577 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000578 }
579
Mike Stump11289f42009-09-09 15:08:12 +0000580 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000581 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
582 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000583 }
584
585 // Build the implicit member references to the field of the
586 // anonymous struct/union.
587 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000588 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000589 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
590 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
591 FI != FIEnd; ++FI) {
592 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000593 Qualifiers MemberTypeQuals =
594 Context.getCanonicalType(MemberType).getQualifiers();
595
596 // CVR attributes from the base are picked up by members,
597 // except that 'mutable' members don't pick up 'const'.
598 if ((*FI)->isMutable())
599 ResultQuals.removeConst();
600
601 // GC attributes are never picked up by members.
602 ResultQuals.removeObjCGCAttr();
603
604 // TR 18037 does not allow fields to be declared with address spaces.
605 assert(!MemberTypeQuals.hasAddressSpace());
606
607 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
608 if (NewQuals != MemberTypeQuals)
609 MemberType = Context.getQualifiedType(MemberType, NewQuals);
610
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000611 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000612 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000613 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000614 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
615 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000616 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000617 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000618 }
619
Sebastian Redlffbcf962009-01-18 18:53:16 +0000620 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000621}
622
John McCall10eae182009-11-30 22:42:35 +0000623/// Decomposes the given name into a DeclarationName, its location, and
624/// possibly a list of template arguments.
625///
626/// If this produces template arguments, it is permitted to call
627/// DecomposeTemplateName.
628///
629/// This actually loses a lot of source location information for
630/// non-standard name kinds; we should consider preserving that in
631/// some way.
632static void DecomposeUnqualifiedId(Sema &SemaRef,
633 const UnqualifiedId &Id,
634 TemplateArgumentListInfo &Buffer,
635 DeclarationName &Name,
636 SourceLocation &NameLoc,
637 const TemplateArgumentListInfo *&TemplateArgs) {
638 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
639 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
640 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
641
642 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
643 Id.TemplateId->getTemplateArgs(),
644 Id.TemplateId->NumArgs);
645 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
646 TemplateArgsPtr.release();
647
648 TemplateName TName =
649 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
650
651 Name = SemaRef.Context.getNameForTemplate(TName);
652 NameLoc = Id.TemplateId->TemplateNameLoc;
653 TemplateArgs = &Buffer;
654 } else {
655 Name = SemaRef.GetNameFromUnqualifiedId(Id);
656 NameLoc = Id.StartLocation;
657 TemplateArgs = 0;
658 }
659}
660
661/// Decompose the given template name into a list of lookup results.
662///
663/// The unqualified ID must name a non-dependent template, which can
664/// be more easily tested by checking whether DecomposeUnqualifiedId
665/// found template arguments.
666static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
667 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
668 TemplateName TName =
669 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
670
John McCalle66edc12009-11-24 19:00:30 +0000671 if (TemplateDecl *TD = TName.getAsTemplateDecl())
672 R.addDecl(TD);
John McCalld28ae272009-12-02 08:04:21 +0000673 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
674 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
675 I != E; ++I)
John McCalle66edc12009-11-24 19:00:30 +0000676 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000677
John McCalle66edc12009-11-24 19:00:30 +0000678 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000679}
680
John McCall10eae182009-11-30 22:42:35 +0000681static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
682 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
683 E = Record->bases_end(); I != E; ++I) {
684 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
685 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
686 if (!BaseRT) return false;
687
688 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
689 if (!BaseRecord->isDefinition() ||
690 !IsFullyFormedScope(SemaRef, BaseRecord))
691 return false;
692 }
693
694 return true;
695}
696
John McCallf786fb12009-11-30 23:50:49 +0000697/// Determines whether we can lookup this id-expression now or whether
698/// we have to wait until template instantiation is complete.
699static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000700 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000701
John McCallf786fb12009-11-30 23:50:49 +0000702 // If the qualifier scope isn't computable, it's definitely dependent.
703 if (!DC) return true;
704
705 // If the qualifier scope doesn't name a record, we can always look into it.
706 if (!isa<CXXRecordDecl>(DC)) return false;
707
708 // We can't look into record types unless they're fully-formed.
709 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
710
John McCall2d74de92009-12-01 22:10:20 +0000711 return false;
712}
John McCallf786fb12009-11-30 23:50:49 +0000713
John McCall2d74de92009-12-01 22:10:20 +0000714/// Determines if the given class is provably not derived from all of
715/// the prospective base classes.
716static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
717 CXXRecordDecl *Record,
718 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000719 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000720 return false;
721
John McCalla6d407c2009-12-01 22:28:41 +0000722 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
723 if (!RD) return false;
724 Record = cast<CXXRecordDecl>(RD);
725
John McCall2d74de92009-12-01 22:10:20 +0000726 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
727 E = Record->bases_end(); I != E; ++I) {
728 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
729 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
730 if (!BaseRT) return false;
731
732 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000733 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
734 return false;
735 }
736
737 return true;
738}
739
John McCall5af04502009-12-02 20:26:00 +0000740/// Determines if this is an instance member of a class.
741static bool IsInstanceMember(NamedDecl *D) {
John McCall57500772009-12-16 12:17:52 +0000742 assert(D->isCXXClassMember() &&
John McCall2d74de92009-12-01 22:10:20 +0000743 "checking whether non-member is instance member");
744
745 if (isa<FieldDecl>(D)) return true;
746
747 if (isa<CXXMethodDecl>(D))
748 return !cast<CXXMethodDecl>(D)->isStatic();
749
750 if (isa<FunctionTemplateDecl>(D)) {
751 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
752 return !cast<CXXMethodDecl>(D)->isStatic();
753 }
754
755 return false;
756}
757
758enum IMAKind {
759 /// The reference is definitely not an instance member access.
760 IMA_Static,
761
762 /// The reference may be an implicit instance member access.
763 IMA_Mixed,
764
765 /// The reference may be to an instance member, but it is invalid if
766 /// so, because the context is not an instance method.
767 IMA_Mixed_StaticContext,
768
769 /// The reference may be to an instance member, but it is invalid if
770 /// so, because the context is from an unrelated class.
771 IMA_Mixed_Unrelated,
772
773 /// The reference is definitely an implicit instance member access.
774 IMA_Instance,
775
776 /// The reference may be to an unresolved using declaration.
777 IMA_Unresolved,
778
779 /// The reference may be to an unresolved using declaration and the
780 /// context is not an instance method.
781 IMA_Unresolved_StaticContext,
782
783 /// The reference is to a member of an anonymous structure in a
784 /// non-class context.
785 IMA_AnonymousMember,
786
787 /// All possible referrents are instance members and the current
788 /// context is not an instance method.
789 IMA_Error_StaticContext,
790
791 /// All possible referrents are instance members of an unrelated
792 /// class.
793 IMA_Error_Unrelated
794};
795
796/// The given lookup names class member(s) and is not being used for
797/// an address-of-member expression. Classify the type of access
798/// according to whether it's possible that this reference names an
799/// instance member. This is best-effort; it is okay to
800/// conservatively answer "yes", in which case some errors will simply
801/// not be caught until template-instantiation.
802static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
803 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +0000804 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +0000805
806 bool isStaticContext =
807 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
808 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
809
810 if (R.isUnresolvableResult())
811 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
812
813 // Collect all the declaring classes of instance members we find.
814 bool hasNonInstance = false;
815 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
816 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
817 NamedDecl *D = (*I)->getUnderlyingDecl();
818 if (IsInstanceMember(D)) {
819 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
820
821 // If this is a member of an anonymous record, move out to the
822 // innermost non-anonymous struct or union. If there isn't one,
823 // that's a special case.
824 while (R->isAnonymousStructOrUnion()) {
825 R = dyn_cast<CXXRecordDecl>(R->getParent());
826 if (!R) return IMA_AnonymousMember;
827 }
828 Classes.insert(R->getCanonicalDecl());
829 }
830 else
831 hasNonInstance = true;
832 }
833
834 // If we didn't find any instance members, it can't be an implicit
835 // member reference.
836 if (Classes.empty())
837 return IMA_Static;
838
839 // If the current context is not an instance method, it can't be
840 // an implicit member reference.
841 if (isStaticContext)
842 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
843
844 // If we can prove that the current context is unrelated to all the
845 // declaring classes, it can't be an implicit member reference (in
846 // which case it's an error if any of those members are selected).
847 if (IsProvablyNotDerivedFrom(SemaRef,
848 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
849 Classes))
850 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
851
852 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
853}
854
855/// Diagnose a reference to a field with no object available.
856static void DiagnoseInstanceReference(Sema &SemaRef,
857 const CXXScopeSpec &SS,
858 const LookupResult &R) {
859 SourceLocation Loc = R.getNameLoc();
860 SourceRange Range(Loc);
861 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
862
863 if (R.getAsSingle<FieldDecl>()) {
864 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
865 if (MD->isStatic()) {
866 // "invalid use of member 'x' in static member function"
867 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
868 << Range << R.getLookupName();
869 return;
870 }
871 }
872
873 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
874 << R.getLookupName() << Range;
875 return;
876 }
877
878 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000879}
880
John McCalld681c392009-12-16 08:11:27 +0000881/// Diagnose an empty lookup.
882///
883/// \return false if new lookup candidates were found
Douglas Gregor598b08f2009-12-31 05:20:13 +0000884bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCalld681c392009-12-16 08:11:27 +0000885 LookupResult &R) {
886 DeclarationName Name = R.getLookupName();
887
John McCalld681c392009-12-16 08:11:27 +0000888 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000889 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +0000890 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
891 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +0000892 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +0000893 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000894 diagnostic_suggest = diag::err_undeclared_use_suggest;
895 }
John McCalld681c392009-12-16 08:11:27 +0000896
Douglas Gregor598b08f2009-12-31 05:20:13 +0000897 // If the original lookup was an unqualified lookup, fake an
898 // unqualified lookup. This is useful when (for example) the
899 // original lookup would not have found something because it was a
900 // dependent name.
901 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
902 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +0000903 if (isa<CXXRecordDecl>(DC)) {
904 LookupQualifiedName(R, DC);
905
906 if (!R.empty()) {
907 // Don't give errors about ambiguities in this lookup.
908 R.suppressDiagnostics();
909
910 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
911 bool isInstance = CurMethod &&
912 CurMethod->isInstance() &&
913 DC == CurMethod->getParent();
914
915 // Give a code modification hint to insert 'this->'.
916 // TODO: fixit for inserting 'Base<T>::' in the other cases.
917 // Actually quite difficult!
918 if (isInstance)
919 Diag(R.getNameLoc(), diagnostic) << Name
920 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
921 "this->");
922 else
923 Diag(R.getNameLoc(), diagnostic) << Name;
924
925 // Do we really want to note all of these?
926 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
927 Diag((*I)->getLocation(), diag::note_dependent_var_use);
928
929 // Tell the callee to try to recover.
930 return false;
931 }
932 }
933 }
934
Douglas Gregor598b08f2009-12-31 05:20:13 +0000935 // We didn't find anything, so try to correct for a typo.
Douglas Gregor25363982010-01-01 00:15:04 +0000936 if (S && CorrectTypo(R, S, &SS)) {
937 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
938 if (SS.isEmpty())
939 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
940 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregor598b08f2009-12-31 05:20:13 +0000941 R.getLookupName().getAsString());
Douglas Gregor25363982010-01-01 00:15:04 +0000942 else
943 Diag(R.getNameLoc(), diag::err_no_member_suggest)
944 << Name << computeDeclContext(SS, false) << R.getLookupName()
945 << SS.getRange()
946 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregor598b08f2009-12-31 05:20:13 +0000947 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000948 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
949 Diag(ND->getLocation(), diag::note_previous_decl)
950 << ND->getDeclName();
951
Douglas Gregor25363982010-01-01 00:15:04 +0000952 // Tell the callee to try to recover.
953 return false;
954 }
955
956 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
957 // FIXME: If we ended up with a typo for a type name or
958 // Objective-C class name, we're in trouble because the parser
959 // is in the wrong place to recover. Suggest the typo
960 // correction, but don't make it a fix-it since we're not going
961 // to recover well anyway.
962 if (SS.isEmpty())
963 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
964 else
965 Diag(R.getNameLoc(), diag::err_no_member_suggest)
966 << Name << computeDeclContext(SS, false) << R.getLookupName()
967 << SS.getRange();
968
969 // Don't try to recover; it won't work.
970 return true;
971 }
972
973 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +0000974 }
975
976 // Emit a special diagnostic for failed member lookups.
977 // FIXME: computing the declaration context might fail here (?)
978 if (!SS.isEmpty()) {
979 Diag(R.getNameLoc(), diag::err_no_member)
980 << Name << computeDeclContext(SS, false)
981 << SS.getRange();
982 return true;
983 }
984
John McCalld681c392009-12-16 08:11:27 +0000985 // Give up, we can't recover.
986 Diag(R.getNameLoc(), diagnostic) << Name;
987 return true;
988}
989
John McCalle66edc12009-11-24 19:00:30 +0000990Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
991 const CXXScopeSpec &SS,
992 UnqualifiedId &Id,
993 bool HasTrailingLParen,
994 bool isAddressOfOperand) {
995 assert(!(isAddressOfOperand && HasTrailingLParen) &&
996 "cannot be direct & operand and have a trailing lparen");
997
998 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +0000999 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001000
John McCall10eae182009-11-30 22:42:35 +00001001 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001002
1003 // Decompose the UnqualifiedId into the following data.
1004 DeclarationName Name;
1005 SourceLocation NameLoc;
1006 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +00001007 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1008 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001009
Douglas Gregor4ea80432008-11-18 15:03:34 +00001010 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +00001011
John McCalle66edc12009-11-24 19:00:30 +00001012 // C++ [temp.dep.expr]p3:
1013 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001014 // -- an identifier that was declared with a dependent type,
1015 // (note: handled after lookup)
1016 // -- a template-id that is dependent,
1017 // (note: handled in BuildTemplateIdExpr)
1018 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001019 // -- a nested-name-specifier that contains a class-name that
1020 // names a dependent type.
1021 // Determine whether this is a member of an unknown specialization;
1022 // we need to handle these differently.
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001023 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1024 Name.getCXXNameType()->isDependentType()) ||
1025 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCalle66edc12009-11-24 19:00:30 +00001026 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +00001027 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001028 TemplateArgs);
1029 }
John McCalld14a8642009-11-21 08:51:07 +00001030
John McCalle66edc12009-11-24 19:00:30 +00001031 // Perform the required lookup.
1032 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1033 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +00001034 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +00001035 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +00001036 } else {
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001037 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1038 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001039
John McCalle66edc12009-11-24 19:00:30 +00001040 // If this reference is in an Objective-C method, then we need to do
1041 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001042 if (IvarLookupFollowUp) {
1043 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001044 if (E.isInvalid())
1045 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001046
John McCalle66edc12009-11-24 19:00:30 +00001047 Expr *Ex = E.takeAs<Expr>();
1048 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001049 }
Chris Lattner59a25942008-03-31 00:36:02 +00001050 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001051
John McCalle66edc12009-11-24 19:00:30 +00001052 if (R.isAmbiguous())
1053 return ExprError();
1054
Douglas Gregor171c45a2009-02-18 21:56:37 +00001055 // Determine whether this name might be a candidate for
1056 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001057 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001058
John McCalle66edc12009-11-24 19:00:30 +00001059 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001060 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001061 // in C90, extension in C99, forbidden in C++).
1062 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1063 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1064 if (D) R.addDecl(D);
1065 }
1066
1067 // If this name wasn't predeclared and if this is not a function
1068 // call, diagnose the problem.
1069 if (R.empty()) {
Douglas Gregor598b08f2009-12-31 05:20:13 +00001070 if (DiagnoseEmptyLookup(S, SS, R))
John McCalld681c392009-12-16 08:11:27 +00001071 return ExprError();
1072
1073 assert(!R.empty() &&
1074 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001075
1076 // If we found an Objective-C instance variable, let
1077 // LookupInObjCMethod build the appropriate expression to
1078 // reference the ivar.
1079 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1080 R.clear();
1081 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1082 assert(E.isInvalid() || E.get());
1083 return move(E);
1084 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001085 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001086 }
Mike Stump11289f42009-09-09 15:08:12 +00001087
John McCalle66edc12009-11-24 19:00:30 +00001088 // This is guaranteed from this point on.
1089 assert(!R.empty() || ADL);
1090
1091 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001092 // Warn about constructs like:
1093 // if (void *X = foo()) { ... } else { X }.
1094 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +00001095
Douglas Gregor3256d042009-06-30 15:47:41 +00001096 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1097 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001098 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00001099 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001100 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001101 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001102 << Var->getDeclName()
1103 << (Var->getType()->isPointerType()? 2 :
1104 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001105 break;
1106 }
Mike Stump11289f42009-09-09 15:08:12 +00001107
Douglas Gregor13a2c032009-11-05 17:49:26 +00001108 // Move to the parent of this scope.
1109 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001110 }
1111 }
John McCalle66edc12009-11-24 19:00:30 +00001112 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001113 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1114 // C99 DR 316 says that, if a function type comes from a
1115 // function definition (without a prototype), that type is only
1116 // used for checking compatibility. Therefore, when referencing
1117 // the function, we pretend that we don't have the full function
1118 // type.
John McCalle66edc12009-11-24 19:00:30 +00001119 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001120 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001121
Douglas Gregor3256d042009-06-30 15:47:41 +00001122 QualType T = Func->getType();
1123 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001124 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001125 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001126 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001127 }
1128 }
Mike Stump11289f42009-09-09 15:08:12 +00001129
John McCall2d74de92009-12-01 22:10:20 +00001130 // Check whether this might be a C++ implicit instance member access.
1131 // C++ [expr.prim.general]p6:
1132 // Within the definition of a non-static member function, an
1133 // identifier that names a non-static member is transformed to a
1134 // class member access expression.
1135 // But note that &SomeClass::foo is grammatically distinct, even
1136 // though we don't parse it that way.
John McCall57500772009-12-16 12:17:52 +00001137 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCalle66edc12009-11-24 19:00:30 +00001138 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall57500772009-12-16 12:17:52 +00001139 if (!isAbstractMemberPointer)
1140 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001141 }
1142
John McCalle66edc12009-11-24 19:00:30 +00001143 if (TemplateArgs)
1144 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001145
John McCalle66edc12009-11-24 19:00:30 +00001146 return BuildDeclarationNameExpr(SS, R, ADL);
1147}
1148
John McCall57500772009-12-16 12:17:52 +00001149/// Builds an expression which might be an implicit member expression.
1150Sema::OwningExprResult
1151Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1152 LookupResult &R,
1153 const TemplateArgumentListInfo *TemplateArgs) {
1154 switch (ClassifyImplicitMemberAccess(*this, R)) {
1155 case IMA_Instance:
1156 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1157
1158 case IMA_AnonymousMember:
1159 assert(R.isSingleResult());
1160 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1161 R.getAsSingle<FieldDecl>());
1162
1163 case IMA_Mixed:
1164 case IMA_Mixed_Unrelated:
1165 case IMA_Unresolved:
1166 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1167
1168 case IMA_Static:
1169 case IMA_Mixed_StaticContext:
1170 case IMA_Unresolved_StaticContext:
1171 if (TemplateArgs)
1172 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1173 return BuildDeclarationNameExpr(SS, R, false);
1174
1175 case IMA_Error_StaticContext:
1176 case IMA_Error_Unrelated:
1177 DiagnoseInstanceReference(*this, SS, R);
1178 return ExprError();
1179 }
1180
1181 llvm_unreachable("unexpected instance member access kind");
1182 return ExprError();
1183}
1184
John McCall10eae182009-11-30 22:42:35 +00001185/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1186/// declaration name, generally during template instantiation.
1187/// There's a large number of things which don't need to be done along
1188/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001189Sema::OwningExprResult
1190Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1191 DeclarationName Name,
1192 SourceLocation NameLoc) {
1193 DeclContext *DC;
1194 if (!(DC = computeDeclContext(SS, false)) ||
1195 DC->isDependentContext() ||
1196 RequireCompleteDeclContext(SS))
1197 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1198
1199 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1200 LookupQualifiedName(R, DC);
1201
1202 if (R.isAmbiguous())
1203 return ExprError();
1204
1205 if (R.empty()) {
1206 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1207 return ExprError();
1208 }
1209
1210 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1211}
1212
1213/// LookupInObjCMethod - The parser has read a name in, and Sema has
1214/// detected that we're currently inside an ObjC method. Perform some
1215/// additional lookup.
1216///
1217/// Ideally, most of this would be done by lookup, but there's
1218/// actually quite a lot of extra work involved.
1219///
1220/// Returns a null sentinel to indicate trivial success.
1221Sema::OwningExprResult
1222Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001223 IdentifierInfo *II,
1224 bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001225 SourceLocation Loc = Lookup.getNameLoc();
1226
1227 // There are two cases to handle here. 1) scoped lookup could have failed,
1228 // in which case we should look for an ivar. 2) scoped lookup could have
1229 // found a decl, but that decl is outside the current instance method (i.e.
1230 // a global variable). In these two cases, we do a lookup for an ivar with
1231 // this name, if the lookup sucedes, we replace it our current decl.
1232
1233 // If we're in a class method, we don't normally want to look for
1234 // ivars. But if we don't find anything else, and there's an
1235 // ivar, that's an error.
1236 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1237
1238 bool LookForIvars;
1239 if (Lookup.empty())
1240 LookForIvars = true;
1241 else if (IsClassMethod)
1242 LookForIvars = false;
1243 else
1244 LookForIvars = (Lookup.isSingleResult() &&
1245 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1246
1247 if (LookForIvars) {
1248 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1249 ObjCInterfaceDecl *ClassDeclared;
1250 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1251 // Diagnose using an ivar in a class method.
1252 if (IsClassMethod)
1253 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1254 << IV->getDeclName());
1255
1256 // If we're referencing an invalid decl, just return this as a silent
1257 // error node. The error diagnostic was already emitted on the decl.
1258 if (IV->isInvalidDecl())
1259 return ExprError();
1260
1261 // Check if referencing a field with __attribute__((deprecated)).
1262 if (DiagnoseUseOfDecl(IV, Loc))
1263 return ExprError();
1264
1265 // Diagnose the use of an ivar outside of the declaring class.
1266 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1267 ClassDeclared != IFace)
1268 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1269
1270 // FIXME: This should use a new expr for a direct reference, don't
1271 // turn this into Self->ivar, just return a BareIVarExpr or something.
1272 IdentifierInfo &II = Context.Idents.get("self");
1273 UnqualifiedId SelfName;
1274 SelfName.setIdentifier(&II, SourceLocation());
1275 CXXScopeSpec SelfScopeSpec;
1276 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1277 SelfName, false, false);
1278 MarkDeclarationReferenced(Loc, IV);
1279 return Owned(new (Context)
1280 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1281 SelfExpr.takeAs<Expr>(), true, true));
1282 }
1283 } else if (getCurMethodDecl()->isInstanceMethod()) {
1284 // We should warn if a local variable hides an ivar.
1285 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1286 ObjCInterfaceDecl *ClassDeclared;
1287 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1288 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1289 IFace == ClassDeclared)
1290 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1291 }
1292 }
1293
1294 // Needed to implement property "super.method" notation.
1295 if (Lookup.empty() && II->isStr("super")) {
1296 QualType T;
1297
1298 if (getCurMethodDecl()->isInstanceMethod())
1299 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1300 getCurMethodDecl()->getClassInterface()));
1301 else
1302 T = Context.getObjCClassType();
1303 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1304 }
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001305 if (Lookup.empty() && II && AllowBuiltinCreation) {
1306 // FIXME. Consolidate this with similar code in LookupName.
1307 if (unsigned BuiltinID = II->getBuiltinID()) {
1308 if (!(getLangOptions().CPlusPlus &&
1309 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1310 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1311 S, Lookup.isForRedeclaration(),
1312 Lookup.getNameLoc());
1313 if (D) Lookup.addDecl(D);
1314 }
1315 }
1316 }
John McCalle66edc12009-11-24 19:00:30 +00001317 // Sentinel value saying that we didn't do anything special.
1318 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001319}
John McCalld14a8642009-11-21 08:51:07 +00001320
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001321/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001322bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001323Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1324 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001325 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001326 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001327 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001328 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001329 if (DestType->isDependentType() || From->getType()->isDependentType())
1330 return false;
1331 QualType FromRecordType = From->getType();
1332 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001333 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001334 DestType = Context.getPointerType(DestType);
1335 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001336 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001337 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1338 CheckDerivedToBaseConversion(FromRecordType,
1339 DestRecordType,
1340 From->getSourceRange().getBegin(),
1341 From->getSourceRange()))
1342 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001343 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1344 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001345 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001346 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001347}
Douglas Gregor3256d042009-06-30 15:47:41 +00001348
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001349/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001350static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001351 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001352 SourceLocation Loc, QualType Ty,
1353 const TemplateArgumentListInfo *TemplateArgs = 0) {
1354 NestedNameSpecifier *Qualifier = 0;
1355 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001356 if (SS.isSet()) {
1357 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1358 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001359 }
Mike Stump11289f42009-09-09 15:08:12 +00001360
John McCalle66edc12009-11-24 19:00:30 +00001361 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1362 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001363}
1364
John McCall2d74de92009-12-01 22:10:20 +00001365/// Builds an implicit member access expression. The current context
1366/// is known to be an instance method, and the given unqualified lookup
1367/// set is known to contain only instance members, at least one of which
1368/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001369Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001370Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1371 LookupResult &R,
1372 const TemplateArgumentListInfo *TemplateArgs,
1373 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001374 assert(!R.empty() && !R.isAmbiguous());
1375
John McCalld14a8642009-11-21 08:51:07 +00001376 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001377
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001378 // We may have found a field within an anonymous union or struct
1379 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001380 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001381 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001382 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001383 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001384 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001385
John McCall2d74de92009-12-01 22:10:20 +00001386 // If this is known to be an instance access, go ahead and build a
1387 // 'this' expression now.
1388 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1389 Expr *This = 0; // null signifies implicit access
1390 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00001391 SourceLocation Loc = R.getNameLoc();
1392 if (SS.getRange().isValid())
1393 Loc = SS.getRange().getBegin();
1394 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001395 }
1396
John McCall2d74de92009-12-01 22:10:20 +00001397 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1398 /*OpLoc*/ SourceLocation(),
1399 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00001400 SS,
1401 /*FirstQualifierInScope*/ 0,
1402 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001403}
1404
John McCalle66edc12009-11-24 19:00:30 +00001405bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001406 const LookupResult &R,
1407 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001408 // Only when used directly as the postfix-expression of a call.
1409 if (!HasTrailingLParen)
1410 return false;
1411
1412 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001413 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001414 return false;
1415
1416 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001417 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001418 return false;
1419
1420 // Turn off ADL when we find certain kinds of declarations during
1421 // normal lookup:
1422 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1423 NamedDecl *D = *I;
1424
1425 // C++0x [basic.lookup.argdep]p3:
1426 // -- a declaration of a class member
1427 // Since using decls preserve this property, we check this on the
1428 // original decl.
John McCall57500772009-12-16 12:17:52 +00001429 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001430 return false;
1431
1432 // C++0x [basic.lookup.argdep]p3:
1433 // -- a block-scope function declaration that is not a
1434 // using-declaration
1435 // NOTE: we also trigger this for function templates (in fact, we
1436 // don't check the decl type at all, since all other decl types
1437 // turn off ADL anyway).
1438 if (isa<UsingShadowDecl>(D))
1439 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1440 else if (D->getDeclContext()->isFunctionOrMethod())
1441 return false;
1442
1443 // C++0x [basic.lookup.argdep]p3:
1444 // -- a declaration that is neither a function or a function
1445 // template
1446 // And also for builtin functions.
1447 if (isa<FunctionDecl>(D)) {
1448 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1449
1450 // But also builtin functions.
1451 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1452 return false;
1453 } else if (!isa<FunctionTemplateDecl>(D))
1454 return false;
1455 }
1456
1457 return true;
1458}
1459
1460
John McCalld14a8642009-11-21 08:51:07 +00001461/// Diagnoses obvious problems with the use of the given declaration
1462/// as an expression. This is only actually called for lookups that
1463/// were not overloaded, and it doesn't promise that the declaration
1464/// will in fact be used.
1465static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1466 if (isa<TypedefDecl>(D)) {
1467 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1468 return true;
1469 }
1470
1471 if (isa<ObjCInterfaceDecl>(D)) {
1472 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1473 return true;
1474 }
1475
1476 if (isa<NamespaceDecl>(D)) {
1477 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1478 return true;
1479 }
1480
1481 return false;
1482}
1483
1484Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001485Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001486 LookupResult &R,
1487 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001488 // If this is a single, fully-resolved result and we don't need ADL,
1489 // just build an ordinary singleton decl ref.
1490 if (!NeedsADL && R.isSingleResult())
John McCallb53bbd42009-11-22 01:44:31 +00001491 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001492
1493 // We only need to check the declaration if there's exactly one
1494 // result, because in the overloaded case the results can only be
1495 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001496 if (R.isSingleResult() &&
1497 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001498 return ExprError();
1499
John McCall58cc69d2010-01-27 01:50:18 +00001500 // Otherwise, just build an unresolved lookup expression. Suppress
1501 // any lookup-related diagnostics; we'll hash these out later, when
1502 // we've picked a target.
1503 R.suppressDiagnostics();
1504
John McCalle66edc12009-11-24 19:00:30 +00001505 bool Dependent
1506 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001507 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001508 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001509 (NestedNameSpecifier*) SS.getScopeRep(),
1510 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001511 R.getLookupName(), R.getNameLoc(),
1512 NeedsADL, R.isOverloadedResult());
John McCall58cc69d2010-01-27 01:50:18 +00001513 ULE->addDecls(R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00001514
1515 return Owned(ULE);
1516}
1517
1518
1519/// \brief Complete semantic analysis for a reference to the given declaration.
1520Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001521Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001522 SourceLocation Loc, NamedDecl *D) {
1523 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001524 assert(!isa<FunctionTemplateDecl>(D) &&
1525 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001526
1527 if (CheckDeclInExpr(*this, Loc, D))
1528 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001529
Douglas Gregore7488b92009-12-01 16:58:18 +00001530 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1531 // Specifically diagnose references to class templates that are missing
1532 // a template argument list.
1533 Diag(Loc, diag::err_template_decl_ref)
1534 << Template << SS.getRange();
1535 Diag(Template->getLocation(), diag::note_template_decl_here);
1536 return ExprError();
1537 }
1538
1539 // Make sure that we're referring to a value.
1540 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1541 if (!VD) {
1542 Diag(Loc, diag::err_ref_non_value)
1543 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00001544 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001545 return ExprError();
1546 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001547
Douglas Gregor171c45a2009-02-18 21:56:37 +00001548 // Check whether this declaration can be used. Note that we suppress
1549 // this check when we're going to perform argument-dependent lookup
1550 // on this function name, because this might not be the function
1551 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001552 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001553 return ExprError();
1554
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001555 // Only create DeclRefExpr's for valid Decl's.
1556 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001557 return ExprError();
1558
Chris Lattner2a9d9892008-10-20 05:16:36 +00001559 // If the identifier reference is inside a block, and it refers to a value
1560 // that is outside the block, create a BlockDeclRefExpr instead of a
1561 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1562 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001563 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001564 // We do not do this for things like enum constants, global variables, etc,
1565 // as they do not get snapshotted.
1566 //
1567 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00001568 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1569 Diag(Loc, diag::err_ref_vm_type);
1570 Diag(D->getLocation(), diag::note_declared_at);
1571 return ExprError();
1572 }
1573
Mike Stump8971a862010-01-05 03:10:36 +00001574 if (VD->getType()->isArrayType()) {
1575 Diag(Loc, diag::err_ref_array_type);
1576 Diag(D->getLocation(), diag::note_declared_at);
1577 return ExprError();
1578 }
1579
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001580 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001581 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001582 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001583 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001584 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001585 // This is to record that a 'const' was actually synthesize and added.
1586 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001587 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001588
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001589 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001590 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001591 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001592 }
1593 // If this reference is not in a block or if the referenced variable is
1594 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001595
John McCalle66edc12009-11-24 19:00:30 +00001596 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001597}
Chris Lattnere168f762006-11-10 05:29:30 +00001598
Sebastian Redlffbcf962009-01-18 18:53:16 +00001599Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1600 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001601 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001602
Chris Lattnere168f762006-11-10 05:29:30 +00001603 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001604 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001605 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1606 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1607 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001608 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001609
Chris Lattnera81a0272008-01-12 08:14:25 +00001610 // Pre-defined identifiers are of type char[x], where x is the length of the
1611 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001612
Anders Carlsson2fb08242009-09-08 18:24:21 +00001613 Decl *currentDecl = getCurFunctionOrMethodDecl();
1614 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001615 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001616 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001617 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001618
Anders Carlsson0b209a82009-09-11 01:22:35 +00001619 QualType ResTy;
1620 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1621 ResTy = Context.DependentTy;
1622 } else {
1623 unsigned Length =
1624 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001625
Anders Carlsson0b209a82009-09-11 01:22:35 +00001626 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001627 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001628 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1629 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001630 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001631}
1632
Sebastian Redlffbcf962009-01-18 18:53:16 +00001633Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001634 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001635 CharBuffer.resize(Tok.getLength());
1636 const char *ThisTokBegin = &CharBuffer[0];
1637 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001638
Steve Naroffae4143e2007-04-26 20:39:23 +00001639 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1640 Tok.getLocation(), PP);
1641 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001642 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001643
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001644 QualType Ty;
1645 if (!getLangOptions().CPlusPlus)
1646 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1647 else if (Literal.isWide())
1648 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1649 else
1650 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00001651
Sebastian Redl20614a72009-01-20 22:23:13 +00001652 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1653 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001654 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001655}
1656
Sebastian Redlffbcf962009-01-18 18:53:16 +00001657Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1658 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001659 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1660 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001661 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001662 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001663 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001664 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001665 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001666
Chris Lattner23b7eb62007-06-15 23:05:46 +00001667 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001668 // Add padding so that NumericLiteralParser can overread by one character.
1669 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001670 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001671
Chris Lattner67ca9252007-05-21 01:08:44 +00001672 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001673 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001674
Mike Stump11289f42009-09-09 15:08:12 +00001675 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001676 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001677 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001678 return ExprError();
1679
Chris Lattner1c20a172007-08-26 03:42:43 +00001680 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001681
Chris Lattner1c20a172007-08-26 03:42:43 +00001682 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001683 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001684 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001685 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001686 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001687 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001688 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001689 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001690
1691 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1692
John McCall53b93a02009-12-24 09:08:04 +00001693 using llvm::APFloat;
1694 APFloat Val(Format);
1695
1696 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00001697
1698 // Overflow is always an error, but underflow is only an error if
1699 // we underflowed to zero (APFloat reports denormals as underflow).
1700 if ((result & APFloat::opOverflow) ||
1701 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00001702 unsigned diagnostic;
1703 llvm::SmallVector<char, 20> buffer;
1704 if (result & APFloat::opOverflow) {
1705 diagnostic = diag::err_float_overflow;
1706 APFloat::getLargest(Format).toString(buffer);
1707 } else {
1708 diagnostic = diag::err_float_underflow;
1709 APFloat::getSmallest(Format).toString(buffer);
1710 }
1711
1712 Diag(Tok.getLocation(), diagnostic)
1713 << Ty
1714 << llvm::StringRef(buffer.data(), buffer.size());
1715 }
1716
1717 bool isExact = (result == APFloat::opOK);
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001718 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001719
Chris Lattner1c20a172007-08-26 03:42:43 +00001720 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001721 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001722 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001723 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001724
Neil Boothac582c52007-08-29 22:00:19 +00001725 // long long is a C99 feature.
1726 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001727 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001728 Diag(Tok.getLocation(), diag::ext_longlong);
1729
Chris Lattner67ca9252007-05-21 01:08:44 +00001730 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001731 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001732
Chris Lattner67ca9252007-05-21 01:08:44 +00001733 if (Literal.GetIntegerValue(ResultVal)) {
1734 // If this value didn't fit into uintmax_t, warn and force to ull.
1735 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001736 Ty = Context.UnsignedLongLongTy;
1737 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001738 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001739 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001740 // If this value fits into a ULL, try to figure out what else it fits into
1741 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001742
Chris Lattner67ca9252007-05-21 01:08:44 +00001743 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1744 // be an unsigned int.
1745 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1746
1747 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001748 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001749 if (!Literal.isLong && !Literal.isLongLong) {
1750 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001751 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001752
Chris Lattner67ca9252007-05-21 01:08:44 +00001753 // Does it fit in a unsigned int?
1754 if (ResultVal.isIntN(IntSize)) {
1755 // Does it fit in a signed int?
1756 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001757 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001758 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001759 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001760 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001761 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001762 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001763
Chris Lattner67ca9252007-05-21 01:08:44 +00001764 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001765 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001766 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001767
Chris Lattner67ca9252007-05-21 01:08:44 +00001768 // Does it fit in a unsigned long?
1769 if (ResultVal.isIntN(LongSize)) {
1770 // Does it fit in a signed long?
1771 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001772 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001773 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001774 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001775 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001776 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001777 }
1778
Chris Lattner67ca9252007-05-21 01:08:44 +00001779 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001780 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001781 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001782
Chris Lattner67ca9252007-05-21 01:08:44 +00001783 // Does it fit in a unsigned long long?
1784 if (ResultVal.isIntN(LongLongSize)) {
1785 // Does it fit in a signed long long?
1786 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001787 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001788 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001789 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001790 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001791 }
1792 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001793
Chris Lattner67ca9252007-05-21 01:08:44 +00001794 // If we still couldn't decide a type, we probably have something that
1795 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001796 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001797 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001798 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001799 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001800 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001801
Chris Lattner55258cf2008-05-09 05:59:00 +00001802 if (ResultVal.getBitWidth() != Width)
1803 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001804 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001805 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001806 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001807
Chris Lattner1c20a172007-08-26 03:42:43 +00001808 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1809 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001810 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001811 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001812
1813 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001814}
1815
Sebastian Redlffbcf962009-01-18 18:53:16 +00001816Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1817 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001818 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001819 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001820 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001821}
1822
Steve Naroff71b59a92007-06-04 22:22:31 +00001823/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001824/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001825bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001826 SourceLocation OpLoc,
1827 const SourceRange &ExprRange,
1828 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001829 if (exprType->isDependentType())
1830 return false;
1831
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001832 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1833 // the result is the size of the referenced type."
1834 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1835 // result shall be the alignment of the referenced type."
1836 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1837 exprType = Ref->getPointeeType();
1838
Steve Naroff043d45d2007-05-15 02:32:35 +00001839 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001840 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001841 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001842 if (isSizeof)
1843 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1844 return false;
1845 }
Mike Stump11289f42009-09-09 15:08:12 +00001846
Chris Lattner62975a72009-04-24 00:30:45 +00001847 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001848 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001849 Diag(OpLoc, diag::ext_sizeof_void_type)
1850 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001851 return false;
1852 }
Mike Stump11289f42009-09-09 15:08:12 +00001853
Chris Lattner62975a72009-04-24 00:30:45 +00001854 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00001855 PDiag(diag::err_sizeof_alignof_incomplete_type)
1856 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001857 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001858
Chris Lattner62975a72009-04-24 00:30:45 +00001859 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001860 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001861 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001862 << exprType << isSizeof << ExprRange;
1863 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001864 }
Mike Stump11289f42009-09-09 15:08:12 +00001865
Chris Lattner62975a72009-04-24 00:30:45 +00001866 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001867}
1868
Chris Lattner8dff0172009-01-24 20:17:12 +00001869bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1870 const SourceRange &ExprRange) {
1871 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001872
Mike Stump11289f42009-09-09 15:08:12 +00001873 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001874 if (isa<DeclRefExpr>(E))
1875 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001876
1877 // Cannot know anything else if the expression is dependent.
1878 if (E->isTypeDependent())
1879 return false;
1880
Douglas Gregor71235ec2009-05-02 02:18:30 +00001881 if (E->getBitField()) {
1882 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1883 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001884 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001885
1886 // Alignment of a field access is always okay, so long as it isn't a
1887 // bit-field.
1888 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001889 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001890 return false;
1891
Chris Lattner8dff0172009-01-24 20:17:12 +00001892 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1893}
1894
Douglas Gregor0950e412009-03-13 21:01:28 +00001895/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001896Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001897Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001898 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001899 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001900 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001901 return ExprError();
1902
John McCallbcd03502009-12-07 02:54:59 +00001903 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001904
Douglas Gregor0950e412009-03-13 21:01:28 +00001905 if (!T->isDependentType() &&
1906 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1907 return ExprError();
1908
1909 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001910 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001911 Context.getSizeType(), OpLoc,
1912 R.getEnd()));
1913}
1914
1915/// \brief Build a sizeof or alignof expression given an expression
1916/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001917Action::OwningExprResult
1918Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001919 bool isSizeOf, SourceRange R) {
1920 // Verify that the operand is valid.
1921 bool isInvalid = false;
1922 if (E->isTypeDependent()) {
1923 // Delay type-checking for type-dependent expressions.
1924 } else if (!isSizeOf) {
1925 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001926 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001927 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1928 isInvalid = true;
1929 } else {
1930 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1931 }
1932
1933 if (isInvalid)
1934 return ExprError();
1935
1936 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1937 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1938 Context.getSizeType(), OpLoc,
1939 R.getEnd()));
1940}
1941
Sebastian Redl6f282892008-11-11 17:56:53 +00001942/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1943/// the same for @c alignof and @c __alignof
1944/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001945Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001946Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1947 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001948 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001949 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001950
Sebastian Redl6f282892008-11-11 17:56:53 +00001951 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001952 TypeSourceInfo *TInfo;
1953 (void) GetTypeFromParser(TyOrEx, &TInfo);
1954 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001955 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001956
Douglas Gregor0950e412009-03-13 21:01:28 +00001957 Expr *ArgEx = (Expr *)TyOrEx;
1958 Action::OwningExprResult Result
1959 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1960
1961 if (Result.isInvalid())
1962 DeleteExpr(ArgEx);
1963
1964 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001965}
1966
Chris Lattner709322b2009-02-17 08:12:06 +00001967QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001968 if (V->isTypeDependent())
1969 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001970
Chris Lattnere267f5d2007-08-26 05:39:26 +00001971 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001972 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001973 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001974
Chris Lattnere267f5d2007-08-26 05:39:26 +00001975 // Otherwise they pass through real integer and floating point types here.
1976 if (V->getType()->isArithmeticType())
1977 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001978
Chris Lattnere267f5d2007-08-26 05:39:26 +00001979 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001980 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1981 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001982 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001983}
1984
1985
Chris Lattnere168f762006-11-10 05:29:30 +00001986
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001987Action::OwningExprResult
1988Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1989 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00001990 UnaryOperator::Opcode Opc;
1991 switch (Kind) {
1992 default: assert(0 && "Unknown unary op!");
1993 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1994 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1995 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001996
Eli Friedmancfdd40c2009-11-18 03:38:04 +00001997 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001998}
1999
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002000Action::OwningExprResult
2001Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2002 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002003 // Since this might be a postfix expression, get rid of ParenListExprs.
2004 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2005
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002006 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2007 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00002008
Douglas Gregor40412ac2008-11-19 17:17:41 +00002009 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002010 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2011 Base.release();
2012 Idx.release();
2013 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2014 Context.DependentTy, RLoc));
2015 }
2016
Mike Stump11289f42009-09-09 15:08:12 +00002017 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002018 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002019 LHSExp->getType()->isEnumeralType() ||
2020 RHSExp->getType()->isRecordType() ||
2021 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00002022 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00002023 }
2024
Sebastian Redladba46e2009-10-29 20:17:01 +00002025 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2026}
2027
2028
2029Action::OwningExprResult
2030Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2031 ExprArg Idx, SourceLocation RLoc) {
2032 Expr *LHSExp = static_cast<Expr*>(Base.get());
2033 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2034
Chris Lattner36d572b2007-07-16 00:14:47 +00002035 // Perform default conversions.
2036 DefaultFunctionArrayConversion(LHSExp);
2037 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002038
Chris Lattner36d572b2007-07-16 00:14:47 +00002039 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00002040
Steve Naroffc1aadb12007-03-28 21:49:40 +00002041 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002042 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002043 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002044 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002045 Expr *BaseExpr, *IndexExpr;
2046 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002047 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2048 BaseExpr = LHSExp;
2049 IndexExpr = RHSExp;
2050 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002051 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002052 BaseExpr = LHSExp;
2053 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002054 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002055 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002056 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002057 BaseExpr = RHSExp;
2058 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002059 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002060 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002061 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002062 BaseExpr = LHSExp;
2063 IndexExpr = RHSExp;
2064 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002065 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002066 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002067 // Handle the uncommon case of "123[Ptr]".
2068 BaseExpr = RHSExp;
2069 IndexExpr = LHSExp;
2070 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002071 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002072 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002073 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002074
Chris Lattner36d572b2007-07-16 00:14:47 +00002075 // FIXME: need to deal with const...
2076 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002077 } else if (LHSTy->isArrayType()) {
2078 // If we see an array that wasn't promoted by
2079 // DefaultFunctionArrayConversion, it must be an array that
2080 // wasn't promoted because of the C90 rule that doesn't
2081 // allow promoting non-lvalue arrays. Warn, then
2082 // force the promotion here.
2083 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2084 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002085 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2086 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002087 LHSTy = LHSExp->getType();
2088
2089 BaseExpr = LHSExp;
2090 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002091 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002092 } else if (RHSTy->isArrayType()) {
2093 // Same as previous, except for 123[f().a] case
2094 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2095 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002096 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2097 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002098 RHSTy = RHSExp->getType();
2099
2100 BaseExpr = RHSExp;
2101 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002102 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002103 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002104 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2105 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002106 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002107 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00002108 if (!(IndexExpr->getType()->isIntegerType() &&
2109 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002110 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2111 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002112
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002113 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002114 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2115 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002116 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2117
Douglas Gregorac1fb652009-03-24 19:52:54 +00002118 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002119 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2120 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002121 // incomplete types are not object types.
2122 if (ResultType->isFunctionType()) {
2123 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2124 << ResultType << BaseExpr->getSourceRange();
2125 return ExprError();
2126 }
Mike Stump11289f42009-09-09 15:08:12 +00002127
Douglas Gregorac1fb652009-03-24 19:52:54 +00002128 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002129 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002130 PDiag(diag::err_subscript_incomplete_type)
2131 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002132 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002133
Chris Lattner62975a72009-04-24 00:30:45 +00002134 // Diagnose bad cases where we step over interface counts.
2135 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2136 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2137 << ResultType << BaseExpr->getSourceRange();
2138 return ExprError();
2139 }
Mike Stump11289f42009-09-09 15:08:12 +00002140
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002141 Base.release();
2142 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002143 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002144 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002145}
2146
Steve Narofff8fd09e2007-07-27 22:15:19 +00002147QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002148CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002149 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002150 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002151 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2152 // see FIXME there.
2153 //
2154 // FIXME: This logic can be greatly simplified by splitting it along
2155 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002156 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002157
Steve Narofff8fd09e2007-07-27 22:15:19 +00002158 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002159 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002160
Mike Stump4e1f26a2009-02-19 03:04:26 +00002161 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002162 // special names that indicate a subset of exactly half the elements are
2163 // to be selected.
2164 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002165
Nate Begemanbb70bf62009-01-18 01:47:54 +00002166 // This flag determines whether or not CompName has an 's' char prefix,
2167 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002168 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002169
2170 // Check that we've found one of the special components, or that the component
2171 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002172 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002173 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2174 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002175 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002176 do
2177 compStr++;
2178 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002179 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002180 do
2181 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002182 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002183 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002184
Mike Stump4e1f26a2009-02-19 03:04:26 +00002185 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002186 // We didn't get to the end of the string. This means the component names
2187 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002188 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2189 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002190 return QualType();
2191 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002192
Nate Begemanbb70bf62009-01-18 01:47:54 +00002193 // Ensure no component accessor exceeds the width of the vector type it
2194 // operates on.
2195 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002196 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002197
2198 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002199 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002200
2201 while (*compStr) {
2202 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2203 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2204 << baseType << SourceRange(CompLoc);
2205 return QualType();
2206 }
2207 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002208 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002209
Steve Narofff8fd09e2007-07-27 22:15:19 +00002210 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002211 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002212 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002213 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002214 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002215 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002216 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002217 if (HexSwizzle)
2218 CompSize--;
2219
Steve Narofff8fd09e2007-07-27 22:15:19 +00002220 if (CompSize == 1)
2221 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002222
Nate Begemance4d7fc2008-04-18 23:10:10 +00002223 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002224 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002225 // diagostics look bad. We want extended vector types to appear built-in.
2226 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2227 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2228 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002229 }
2230 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002231}
2232
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002233static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002234 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002235 const Selector &Sel,
2236 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002237
Anders Carlssonf571c112009-08-26 18:25:21 +00002238 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002239 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002240 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002241 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002242
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002243 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2244 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002245 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002246 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002247 return D;
2248 }
2249 return 0;
2250}
2251
Steve Narofffb4330f2009-06-17 22:40:22 +00002252static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002253 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002254 const Selector &Sel,
2255 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002256 // Check protocols on qualified interfaces.
2257 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002258 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002259 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002260 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002261 GDecl = PD;
2262 break;
2263 }
2264 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002265 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002266 GDecl = OMD;
2267 break;
2268 }
2269 }
2270 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002271 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002272 E = QIdTy->qual_end(); I != E; ++I) {
2273 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002274 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002275 if (GDecl)
2276 return GDecl;
2277 }
2278 }
2279 return GDecl;
2280}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002281
John McCall10eae182009-11-30 22:42:35 +00002282Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002283Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2284 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002285 const CXXScopeSpec &SS,
2286 NamedDecl *FirstQualifierInScope,
2287 DeclarationName Name, SourceLocation NameLoc,
2288 const TemplateArgumentListInfo *TemplateArgs) {
2289 Expr *BaseExpr = Base.takeAs<Expr>();
2290
2291 // Even in dependent contexts, try to diagnose base expressions with
2292 // obviously wrong types, e.g.:
2293 //
2294 // T* t;
2295 // t.f;
2296 //
2297 // In Obj-C++, however, the above expression is valid, since it could be
2298 // accessing the 'f' property if T is an Obj-C interface. The extra check
2299 // allows this, while still reporting an error if T is a struct pointer.
2300 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002301 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002302 if (PT && (!getLangOptions().ObjC1 ||
2303 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002304 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002305 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002306 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002307 return ExprError();
2308 }
2309 }
2310
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002311 assert(BaseType->isDependentType() || Name.isDependentName());
John McCall10eae182009-11-30 22:42:35 +00002312
2313 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2314 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002315 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002316 IsArrow, OpLoc,
2317 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2318 SS.getRange(),
2319 FirstQualifierInScope,
2320 Name, NameLoc,
2321 TemplateArgs));
2322}
2323
2324/// We know that the given qualified member reference points only to
2325/// declarations which do not belong to the static type of the base
2326/// expression. Diagnose the problem.
2327static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2328 Expr *BaseExpr,
2329 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002330 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002331 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002332 // If this is an implicit member access, use a different set of
2333 // diagnostics.
2334 if (!BaseExpr)
2335 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002336
2337 // FIXME: this is an exceedingly lame diagnostic for some of the more
2338 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002339 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002340 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002341 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002342}
2343
2344// Check whether the declarations we found through a nested-name
2345// specifier in a member expression are actually members of the base
2346// type. The restriction here is:
2347//
2348// C++ [expr.ref]p2:
2349// ... In these cases, the id-expression shall name a
2350// member of the class or of one of its base classes.
2351//
2352// So it's perfectly legitimate for the nested-name specifier to name
2353// an unrelated class, and for us to find an overload set including
2354// decls from classes which are not superclasses, as long as the decl
2355// we actually pick through overload resolution is from a superclass.
2356bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2357 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002358 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002359 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002360 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2361 if (!BaseRT) {
2362 // We can't check this yet because the base type is still
2363 // dependent.
2364 assert(BaseType->isDependentType());
2365 return false;
2366 }
2367 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002368
2369 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002370 // If this is an implicit member reference and we find a
2371 // non-instance member, it's not an error.
2372 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2373 return false;
John McCall10eae182009-11-30 22:42:35 +00002374
John McCall2d74de92009-12-01 22:10:20 +00002375 // Note that we use the DC of the decl, not the underlying decl.
2376 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2377 while (RecordD->isAnonymousStructOrUnion())
2378 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2379
2380 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2381 MemberRecord.insert(RecordD->getCanonicalDecl());
2382
2383 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2384 return false;
2385 }
2386
John McCallcd4b4772009-12-02 03:53:29 +00002387 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002388 return true;
2389}
2390
2391static bool
2392LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2393 SourceRange BaseRange, const RecordType *RTy,
2394 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2395 RecordDecl *RDecl = RTy->getDecl();
2396 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2397 PDiag(diag::err_typecheck_incomplete_tag)
2398 << BaseRange))
2399 return true;
2400
2401 DeclContext *DC = RDecl;
2402 if (SS.isSet()) {
2403 // If the member name was a qualified-id, look into the
2404 // nested-name-specifier.
2405 DC = SemaRef.computeDeclContext(SS, false);
2406
John McCallcd4b4772009-12-02 03:53:29 +00002407 if (SemaRef.RequireCompleteDeclContext(SS)) {
2408 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2409 << SS.getRange() << DC;
2410 return true;
2411 }
2412
John McCall2d74de92009-12-01 22:10:20 +00002413 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2414
2415 if (!isa<TypeDecl>(DC)) {
2416 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2417 << DC << SS.getRange();
2418 return true;
John McCall10eae182009-11-30 22:42:35 +00002419 }
2420 }
2421
John McCall2d74de92009-12-01 22:10:20 +00002422 // The record definition is complete, now look up the member.
2423 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002424
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002425 if (!R.empty())
2426 return false;
2427
2428 // We didn't find anything with the given name, so try to correct
2429 // for typos.
2430 DeclarationName Name = R.getLookupName();
2431 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
2432 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2433 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2434 << Name << DC << R.getLookupName() << SS.getRange()
2435 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2436 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002437 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2438 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2439 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002440 return false;
2441 } else {
2442 R.clear();
2443 }
2444
John McCall10eae182009-11-30 22:42:35 +00002445 return false;
2446}
2447
2448Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002449Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002450 SourceLocation OpLoc, bool IsArrow,
2451 const CXXScopeSpec &SS,
2452 NamedDecl *FirstQualifierInScope,
2453 DeclarationName Name, SourceLocation NameLoc,
2454 const TemplateArgumentListInfo *TemplateArgs) {
2455 Expr *Base = BaseArg.takeAs<Expr>();
2456
John McCallcd4b4772009-12-02 03:53:29 +00002457 if (BaseType->isDependentType() ||
2458 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002459 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002460 IsArrow, OpLoc,
2461 SS, FirstQualifierInScope,
2462 Name, NameLoc,
2463 TemplateArgs);
2464
2465 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002466
John McCall2d74de92009-12-01 22:10:20 +00002467 // Implicit member accesses.
2468 if (!Base) {
2469 QualType RecordTy = BaseType;
2470 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2471 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2472 RecordTy->getAs<RecordType>(),
2473 OpLoc, SS))
2474 return ExprError();
2475
2476 // Explicit member accesses.
2477 } else {
2478 OwningExprResult Result =
2479 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall38836f02010-01-15 08:34:02 +00002480 SS, /*ObjCImpDecl*/ DeclPtrTy());
John McCall2d74de92009-12-01 22:10:20 +00002481
2482 if (Result.isInvalid()) {
2483 Owned(Base);
2484 return ExprError();
2485 }
2486
2487 if (Result.get())
2488 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002489 }
2490
John McCall2d74de92009-12-01 22:10:20 +00002491 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCall38836f02010-01-15 08:34:02 +00002492 OpLoc, IsArrow, SS, FirstQualifierInScope,
2493 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002494}
2495
2496Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002497Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2498 SourceLocation OpLoc, bool IsArrow,
2499 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00002500 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00002501 LookupResult &R,
2502 const TemplateArgumentListInfo *TemplateArgs) {
2503 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002504 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002505 if (IsArrow) {
2506 assert(BaseType->isPointerType());
2507 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2508 }
2509
2510 NestedNameSpecifier *Qualifier =
2511 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2512 DeclarationName MemberName = R.getLookupName();
2513 SourceLocation MemberLoc = R.getNameLoc();
2514
2515 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002516 return ExprError();
2517
John McCall10eae182009-11-30 22:42:35 +00002518 if (R.empty()) {
2519 // Rederive where we looked up.
2520 DeclContext *DC = (SS.isSet()
2521 ? computeDeclContext(SS, false)
2522 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002523
John McCall10eae182009-11-30 22:42:35 +00002524 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002525 << MemberName << DC
2526 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002527 return ExprError();
2528 }
2529
John McCall38836f02010-01-15 08:34:02 +00002530 // Diagnose lookups that find only declarations from a non-base
2531 // type. This is possible for either qualified lookups (which may
2532 // have been qualified with an unrelated type) or implicit member
2533 // expressions (which were found with unqualified lookup and thus
2534 // may have come from an enclosing scope). Note that it's okay for
2535 // lookup to find declarations from a non-base type as long as those
2536 // aren't the ones picked by overload resolution.
2537 if ((SS.isSet() || !BaseExpr ||
2538 (isa<CXXThisExpr>(BaseExpr) &&
2539 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
2540 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002541 return ExprError();
2542
2543 // Construct an unresolved result if we in fact got an unresolved
2544 // result.
2545 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002546 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002547 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002548 R.isUnresolvableResult() ||
2549 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002550
John McCall58cc69d2010-01-27 01:50:18 +00002551 // Suppress any lookup-related diagnostics; we'll do these when we
2552 // pick a member.
2553 R.suppressDiagnostics();
2554
John McCall10eae182009-11-30 22:42:35 +00002555 UnresolvedMemberExpr *MemExpr
2556 = UnresolvedMemberExpr::Create(Context, Dependent,
2557 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002558 BaseExpr, BaseExprType,
2559 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002560 Qualifier, SS.getRange(),
2561 MemberName, MemberLoc,
2562 TemplateArgs);
John McCall58cc69d2010-01-27 01:50:18 +00002563 MemExpr->addDecls(R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00002564
2565 return Owned(MemExpr);
2566 }
2567
2568 assert(R.isSingleResult());
2569 NamedDecl *MemberDecl = R.getFoundDecl();
2570
2571 // FIXME: diagnose the presence of template arguments now.
2572
2573 // If the decl being referenced had an error, return an error for this
2574 // sub-expr without emitting another error, in order to avoid cascading
2575 // error cases.
2576 if (MemberDecl->isInvalidDecl())
2577 return ExprError();
2578
John McCall2d74de92009-12-01 22:10:20 +00002579 // Handle the implicit-member-access case.
2580 if (!BaseExpr) {
2581 // If this is not an instance member, convert to a non-member access.
2582 if (!IsInstanceMember(MemberDecl))
2583 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2584
Douglas Gregorb15af892010-01-07 23:12:05 +00002585 SourceLocation Loc = R.getNameLoc();
2586 if (SS.getRange().isValid())
2587 Loc = SS.getRange().getBegin();
2588 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00002589 }
2590
John McCall10eae182009-11-30 22:42:35 +00002591 bool ShouldCheckUse = true;
2592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2593 // Don't diagnose the use of a virtual member function unless it's
2594 // explicitly qualified.
2595 if (MD->isVirtual() && !SS.isSet())
2596 ShouldCheckUse = false;
2597 }
2598
2599 // Check the use of this member.
2600 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2601 Owned(BaseExpr);
2602 return ExprError();
2603 }
2604
2605 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2606 // We may have found a field within an anonymous union or struct
2607 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002608 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2609 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002610 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2611 BaseExpr, OpLoc);
2612
2613 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2614 QualType MemberType = FD->getType();
2615 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2616 MemberType = Ref->getPointeeType();
2617 else {
2618 Qualifiers BaseQuals = BaseType.getQualifiers();
2619 BaseQuals.removeObjCGCAttr();
2620 if (FD->isMutable()) BaseQuals.removeConst();
2621
2622 Qualifiers MemberQuals
2623 = Context.getCanonicalType(MemberType).getQualifiers();
2624
2625 Qualifiers Combined = BaseQuals + MemberQuals;
2626 if (Combined != MemberQuals)
2627 MemberType = Context.getQualifiedType(MemberType, Combined);
2628 }
2629
2630 MarkDeclarationReferenced(MemberLoc, FD);
2631 if (PerformObjectMemberConversion(BaseExpr, FD))
2632 return ExprError();
2633 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2634 FD, MemberLoc, MemberType));
2635 }
2636
2637 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2638 MarkDeclarationReferenced(MemberLoc, Var);
2639 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2640 Var, MemberLoc,
2641 Var->getType().getNonReferenceType()));
2642 }
2643
2644 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2645 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2646 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2647 MemberFn, MemberLoc,
2648 MemberFn->getType()));
2649 }
2650
2651 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2652 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2653 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2654 Enum, MemberLoc, Enum->getType()));
2655 }
2656
2657 Owned(BaseExpr);
2658
2659 if (isa<TypeDecl>(MemberDecl))
2660 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2661 << MemberName << int(IsArrow));
2662
2663 // We found a declaration kind that we didn't expect. This is a
2664 // generic error message that tells the user that she can't refer
2665 // to this member with '.' or '->'.
2666 return ExprError(Diag(MemberLoc,
2667 diag::err_typecheck_member_reference_unknown)
2668 << MemberName << int(IsArrow));
2669}
2670
2671/// Look up the given member of the given non-type-dependent
2672/// expression. This can return in one of two ways:
2673/// * If it returns a sentinel null-but-valid result, the caller will
2674/// assume that lookup was performed and the results written into
2675/// the provided structure. It will take over from there.
2676/// * Otherwise, the returned expression will be produced in place of
2677/// an ordinary member expression.
2678///
2679/// The ObjCImpDecl bit is a gross hack that will need to be properly
2680/// fixed for ObjC++.
2681Sema::OwningExprResult
2682Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002683 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002684 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002685 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002686 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002687
Steve Naroffeaaae462007-12-16 21:42:28 +00002688 // Perform default conversions.
2689 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002690
Steve Naroff185616f2007-07-26 03:11:44 +00002691 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002692 assert(!BaseType->isDependentType());
2693
2694 DeclarationName MemberName = R.getLookupName();
2695 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002696
2697 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002698 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002699 // function. Suggest the addition of those parentheses, build the
2700 // call, and continue on.
2701 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2702 if (const FunctionProtoType *Fun
2703 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2704 QualType ResultTy = Fun->getResultType();
2705 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002706 ((!IsArrow && ResultTy->isRecordType()) ||
2707 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002708 ResultTy->getAs<PointerType>()->getPointeeType()
2709 ->isRecordType()))) {
2710 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2711 Diag(Loc, diag::err_member_reference_needs_call)
2712 << QualType(Fun, 0)
2713 << CodeModificationHint::CreateInsertion(Loc, "()");
2714
2715 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002716 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002717 MultiExprArg(*this, 0, 0), 0, Loc);
2718 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002719 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002720
2721 BaseExpr = NewBase.takeAs<Expr>();
2722 DefaultFunctionArrayConversion(BaseExpr);
2723 BaseType = BaseExpr->getType();
2724 }
2725 }
2726 }
2727
David Chisnall9f57c292009-08-17 16:35:33 +00002728 // If this is an Objective-C pseudo-builtin and a definition is provided then
2729 // use that.
2730 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002731 if (IsArrow) {
2732 // Handle the following exceptional case PObj->isa.
2733 if (const ObjCObjectPointerType *OPT =
2734 BaseType->getAs<ObjCObjectPointerType>()) {
2735 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2736 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002737 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2738 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002739 }
2740 }
David Chisnall9f57c292009-08-17 16:35:33 +00002741 // We have an 'id' type. Rather than fall through, we check if this
2742 // is a reference to 'isa'.
2743 if (BaseType != Context.ObjCIdRedefinitionType) {
2744 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002745 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002746 }
David Chisnall9f57c292009-08-17 16:35:33 +00002747 }
John McCall10eae182009-11-30 22:42:35 +00002748
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002749 // If this is an Objective-C pseudo-builtin and a definition is provided then
2750 // use that.
2751 if (Context.isObjCSelType(BaseType)) {
2752 // We have an 'SEL' type. Rather than fall through, we check if this
2753 // is a reference to 'sel_id'.
2754 if (BaseType != Context.ObjCSelRedefinitionType) {
2755 BaseType = Context.ObjCSelRedefinitionType;
2756 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2757 }
2758 }
John McCall10eae182009-11-30 22:42:35 +00002759
Steve Naroff185616f2007-07-26 03:11:44 +00002760 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002761
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002762 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002763 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002764 // Also must look for a getter name which uses property syntax.
2765 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2766 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2767 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2768 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2769 ObjCMethodDecl *Getter;
2770 // FIXME: need to also look locally in the implementation.
2771 if ((Getter = IFace->lookupClassMethod(Sel))) {
2772 // Check the use of this method.
2773 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2774 return ExprError();
2775 }
2776 // If we found a getter then this may be a valid dot-reference, we
2777 // will look for the matching setter, in case it is needed.
2778 Selector SetterSel =
2779 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2780 PP.getSelectorTable(), Member);
2781 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2782 if (!Setter) {
2783 // If this reference is in an @implementation, also check for 'private'
2784 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002785 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002786 }
2787 // Look through local category implementations associated with the class.
2788 if (!Setter)
2789 Setter = IFace->getCategoryClassMethod(SetterSel);
2790
2791 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2792 return ExprError();
2793
2794 if (Getter || Setter) {
2795 QualType PType;
2796
2797 if (Getter)
2798 PType = Getter->getResultType();
2799 else
2800 // Get the expression type from Setter's incoming parameter.
2801 PType = (*(Setter->param_end() -1))->getType();
2802 // FIXME: we must check that the setter has property type.
2803 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2804 PType,
2805 Setter, MemberLoc, BaseExpr));
2806 }
2807 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2808 << MemberName << BaseType);
2809 }
2810 }
2811
2812 if (BaseType->isObjCClassType() &&
2813 BaseType != Context.ObjCClassRedefinitionType) {
2814 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002815 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002816 }
Mike Stump11289f42009-09-09 15:08:12 +00002817
John McCall10eae182009-11-30 22:42:35 +00002818 if (IsArrow) {
2819 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002820 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002821 else if (BaseType->isObjCObjectPointerType())
2822 ;
John McCalla928c652009-12-07 22:46:59 +00002823 else if (BaseType->isRecordType()) {
2824 // Recover from arrow accesses to records, e.g.:
2825 // struct MyRecord foo;
2826 // foo->bar
2827 // This is actually well-formed in C++ if MyRecord has an
2828 // overloaded operator->, but that should have been dealt with
2829 // by now.
2830 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2831 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2832 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2833 IsArrow = false;
2834 } else {
John McCall10eae182009-11-30 22:42:35 +00002835 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2836 << BaseType << BaseExpr->getSourceRange();
2837 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002838 }
John McCalla928c652009-12-07 22:46:59 +00002839 } else {
2840 // Recover from dot accesses to pointers, e.g.:
2841 // type *foo;
2842 // foo.bar
2843 // This is actually well-formed in two cases:
2844 // - 'type' is an Objective C type
2845 // - 'bar' is a pseudo-destructor name which happens to refer to
2846 // the appropriate pointer type
2847 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2848 const PointerType *PT = BaseType->getAs<PointerType>();
2849 if (PT && PT->getPointeeType()->isRecordType()) {
2850 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2851 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2852 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2853 BaseType = PT->getPointeeType();
2854 IsArrow = true;
2855 }
2856 }
John McCall10eae182009-11-30 22:42:35 +00002857 }
John McCalla928c652009-12-07 22:46:59 +00002858
John McCall10eae182009-11-30 22:42:35 +00002859 // Handle field access to simple records. This also handles access
2860 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002861 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002862 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2863 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002864 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002865 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002866 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002867
Douglas Gregorad8a3362009-09-04 17:36:40 +00002868 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2869 // into a record type was handled above, any destructor we see here is a
2870 // pseudo-destructor.
2871 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2872 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002873 // The left hand side of the dot operator shall be of scalar type. The
2874 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002875 // type.
2876 if (!BaseType->isScalarType())
2877 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2878 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002879
Douglas Gregorad8a3362009-09-04 17:36:40 +00002880 // [...] The type designated by the pseudo-destructor-name shall be the
2881 // same as the object type.
2882 if (!MemberName.getCXXNameType()->isDependentType() &&
2883 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2884 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2885 << BaseType << MemberName.getCXXNameType()
2886 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002887
2888 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002889 // the form
2890 //
Mike Stump11289f42009-09-09 15:08:12 +00002891 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2892 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002893 // shall designate the same scalar type.
2894 //
2895 // FIXME: DPG can't see any way to trigger this particular clause, so it
2896 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002897
Douglas Gregorad8a3362009-09-04 17:36:40 +00002898 // FIXME: We've lost the precise spelling of the type by going through
2899 // DeclarationName. Can we do better?
2900 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002901 IsArrow, OpLoc,
2902 (NestedNameSpecifier *) SS.getScopeRep(),
2903 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002904 MemberName.getCXXNameType(),
2905 MemberLoc));
2906 }
Mike Stump11289f42009-09-09 15:08:12 +00002907
Chris Lattnerdc420f42008-07-21 04:59:05 +00002908 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2909 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002910 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2911 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002912 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002913 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002914 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002915 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002916 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2917
Steve Naroffa057ba92009-07-16 00:25:06 +00002918 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2919 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002920 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002921
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002922 if (!IV) {
2923 // Attempt to correct for typos in ivar names.
2924 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
2925 LookupMemberName);
2926 if (CorrectTypo(Res, 0, 0, IDecl) &&
2927 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
2928 Diag(R.getNameLoc(),
2929 diag::err_typecheck_member_reference_ivar_suggest)
2930 << IDecl->getDeclName() << MemberName << IV->getDeclName()
2931 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2932 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002933 Diag(IV->getLocation(), diag::note_previous_decl)
2934 << IV->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002935 }
2936 }
2937
Steve Naroffa057ba92009-07-16 00:25:06 +00002938 if (IV) {
2939 // If the decl being referenced had an error, return an error for this
2940 // sub-expr without emitting another error, in order to avoid cascading
2941 // error cases.
2942 if (IV->isInvalidDecl())
2943 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002944
Steve Naroffa057ba92009-07-16 00:25:06 +00002945 // Check whether we can reference this field.
2946 if (DiagnoseUseOfDecl(IV, MemberLoc))
2947 return ExprError();
2948 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2949 IV->getAccessControl() != ObjCIvarDecl::Package) {
2950 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2951 if (ObjCMethodDecl *MD = getCurMethodDecl())
2952 ClassOfMethodDecl = MD->getClassInterface();
2953 else if (ObjCImpDecl && getCurFunctionDecl()) {
2954 // Case of a c-function declared inside an objc implementation.
2955 // FIXME: For a c-style function nested inside an objc implementation
2956 // class, there is no implementation context available, so we pass
2957 // down the context as argument to this routine. Ideally, this context
2958 // need be passed down in the AST node and somehow calculated from the
2959 // AST for a function decl.
2960 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002961 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002962 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2963 ClassOfMethodDecl = IMPD->getClassInterface();
2964 else if (ObjCCategoryImplDecl* CatImplClass =
2965 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2966 ClassOfMethodDecl = CatImplClass->getClassInterface();
2967 }
Mike Stump11289f42009-09-09 15:08:12 +00002968
2969 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2970 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002971 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002972 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002973 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002974 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2975 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002976 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002977 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002978 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002979
2980 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2981 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002982 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002983 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002984 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002985 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002986 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002987 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002988 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002989 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002990 if (!IsArrow && (BaseType->isObjCIdType() ||
2991 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002992 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002993 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002994
Steve Naroff7cae42b2009-07-10 23:34:53 +00002995 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002996 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002997 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2998 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2999 // Check the use of this declaration
3000 if (DiagnoseUseOfDecl(PD, MemberLoc))
3001 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003002
Steve Naroff7cae42b2009-07-10 23:34:53 +00003003 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3004 MemberLoc, BaseExpr));
3005 }
3006 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3007 // Check the use of this method.
3008 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3009 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003010
Steve Naroff7cae42b2009-07-10 23:34:53 +00003011 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00003012 OMD->getResultType(),
3013 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003014 NULL, 0));
3015 }
3016 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003017
Steve Naroff7cae42b2009-07-10 23:34:53 +00003018 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003019 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003020 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00003021 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3022 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003023 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00003024 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003025 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
3026 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00003027 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003028
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003029 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00003030 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003031 // Check whether we can reference this property.
3032 if (DiagnoseUseOfDecl(PD, MemberLoc))
3033 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003034 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00003035 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003036 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00003037 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3038 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003039 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00003040 MemberLoc, BaseExpr));
3041 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003042 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00003043 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3044 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00003045 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003046 // Check whether we can reference this property.
3047 if (DiagnoseUseOfDecl(PD, MemberLoc))
3048 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00003049
Steve Narofff6009ed2009-01-21 00:14:39 +00003050 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00003051 MemberLoc, BaseExpr));
3052 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003053 // If that failed, look for an "implicit" property by seeing if the nullary
3054 // selector is implemented.
3055
3056 // FIXME: The logic for looking up nullary and unary selectors should be
3057 // shared with the code in ActOnInstanceMessage.
3058
Anders Carlssonf571c112009-08-26 18:25:21 +00003059 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003060 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003061
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003062 // If this reference is in an @implementation, check for 'private' methods.
3063 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00003064 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003065
Steve Naroff1df62692008-10-22 19:16:27 +00003066 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003067 if (!Getter)
3068 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003069 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003070 // Check if we can reference this property.
3071 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3072 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00003073 }
3074 // If we found a getter then this may be a valid dot-reference, we
3075 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00003076 Selector SetterSel =
3077 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00003078 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003079 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003080 if (!Setter) {
3081 // If this reference is in an @implementation, also check for 'private'
3082 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003083 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003084 }
3085 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003086 if (!Setter)
3087 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003088
Steve Naroff1d984fe2009-03-11 13:48:17 +00003089 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3090 return ExprError();
3091
Fariborz Jahanianc1d2fa52010-01-19 17:48:02 +00003092 if (Getter) {
Steve Naroff1d984fe2009-03-11 13:48:17 +00003093 QualType PType;
Fariborz Jahanianc1d2fa52010-01-19 17:48:02 +00003094 PType = Getter->getResultType();
Fariborz Jahanian9a846652009-08-20 17:02:02 +00003095 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00003096 Setter, MemberLoc, BaseExpr));
3097 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003098
3099 // Attempt to correct for typos in property names.
3100 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3101 LookupOrdinaryName);
3102 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
3103 Res.getAsSingle<ObjCPropertyDecl>()) {
3104 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3105 << MemberName << BaseType << Res.getLookupName()
3106 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
3107 Res.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003108 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3109 Diag(Property->getLocation(), diag::note_previous_decl)
3110 << Property->getDeclName();
3111
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003112 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
John McCall38836f02010-01-15 08:34:02 +00003113 ObjCImpDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003114 }
3115
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003116 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003117 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00003118 }
Mike Stump11289f42009-09-09 15:08:12 +00003119
Steve Naroffe87026a2009-07-24 17:54:45 +00003120 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003121 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00003122 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003123 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003124 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003125 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003126
Chris Lattnerb63a7452008-07-21 04:28:12 +00003127 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003128 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003129 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00003130 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3131 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003132 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00003133 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00003134 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003135 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003136
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003137 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3138 << BaseType << BaseExpr->getSourceRange();
3139
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003140 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003141}
3142
John McCall10eae182009-11-30 22:42:35 +00003143static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3144 SourceLocation NameLoc,
3145 Sema::ExprArg MemExpr) {
3146 Expr *E = (Expr *) MemExpr.get();
3147 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3148 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00003149 << isa<CXXPseudoDestructorExpr>(E)
3150 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3151
John McCall10eae182009-11-30 22:42:35 +00003152 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3153 move(MemExpr),
3154 /*LPLoc*/ ExpectedLParenLoc,
3155 Sema::MultiExprArg(SemaRef, 0, 0),
3156 /*CommaLocs*/ 0,
3157 /*RPLoc*/ ExpectedLParenLoc);
3158}
3159
3160/// The main callback when the parser finds something like
3161/// expression . [nested-name-specifier] identifier
3162/// expression -> [nested-name-specifier] identifier
3163/// where 'identifier' encompasses a fairly broad spectrum of
3164/// possibilities, including destructor and operator references.
3165///
3166/// \param OpKind either tok::arrow or tok::period
3167/// \param HasTrailingLParen whether the next token is '(', which
3168/// is used to diagnose mis-uses of special members that can
3169/// only be called
3170/// \param ObjCImpDecl the current ObjC @implementation decl;
3171/// this is an ugly hack around the fact that ObjC @implementations
3172/// aren't properly put in the context chain
3173Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3174 SourceLocation OpLoc,
3175 tok::TokenKind OpKind,
3176 const CXXScopeSpec &SS,
3177 UnqualifiedId &Id,
3178 DeclPtrTy ObjCImpDecl,
3179 bool HasTrailingLParen) {
3180 if (SS.isSet() && SS.isInvalid())
3181 return ExprError();
3182
3183 TemplateArgumentListInfo TemplateArgsBuffer;
3184
3185 // Decompose the name into its component parts.
3186 DeclarationName Name;
3187 SourceLocation NameLoc;
3188 const TemplateArgumentListInfo *TemplateArgs;
3189 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3190 Name, NameLoc, TemplateArgs);
3191
3192 bool IsArrow = (OpKind == tok::arrow);
3193
3194 NamedDecl *FirstQualifierInScope
3195 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3196 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3197
3198 // This is a postfix expression, so get rid of ParenListExprs.
3199 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3200
3201 Expr *Base = BaseArg.takeAs<Expr>();
3202 OwningExprResult Result(*this);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003203 if (Base->getType()->isDependentType() || Name.isDependentName()) {
John McCall2d74de92009-12-01 22:10:20 +00003204 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003205 IsArrow, OpLoc,
3206 SS, FirstQualifierInScope,
3207 Name, NameLoc,
3208 TemplateArgs);
3209 } else {
3210 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3211 if (TemplateArgs) {
3212 // Re-use the lookup done for the template name.
3213 DecomposeTemplateName(R, Id);
3214 } else {
3215 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall38836f02010-01-15 08:34:02 +00003216 SS, ObjCImpDecl);
John McCall10eae182009-11-30 22:42:35 +00003217
3218 if (Result.isInvalid()) {
3219 Owned(Base);
3220 return ExprError();
3221 }
3222
3223 if (Result.get()) {
3224 // The only way a reference to a destructor can be used is to
3225 // immediately call it, which falls into this case. If the
3226 // next token is not a '(', produce a diagnostic and build the
3227 // call now.
3228 if (!HasTrailingLParen &&
3229 Id.getKind() == UnqualifiedId::IK_DestructorName)
3230 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3231
3232 return move(Result);
3233 }
3234 }
3235
John McCall2d74de92009-12-01 22:10:20 +00003236 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003237 OpLoc, IsArrow, SS, FirstQualifierInScope,
3238 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003239 }
3240
3241 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003242}
3243
Anders Carlsson355933d2009-08-25 03:49:14 +00003244Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3245 FunctionDecl *FD,
3246 ParmVarDecl *Param) {
3247 if (Param->hasUnparsedDefaultArg()) {
3248 Diag (CallLoc,
3249 diag::err_use_of_default_argument_to_function_declared_later) <<
3250 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003251 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003252 diag::note_default_argument_declared_here);
3253 } else {
3254 if (Param->hasUninstantiatedDefaultArg()) {
3255 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3256
3257 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00003258 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00003259
Mike Stump11289f42009-09-09 15:08:12 +00003260 InstantiatingTemplate Inst(*this, CallLoc, Param,
3261 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003262 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003263
John McCall76d824f2009-08-25 22:02:44 +00003264 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003265 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003266 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003267
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003268 // Check the expression as an initializer for the parameter.
3269 InitializedEntity Entity
3270 = InitializedEntity::InitializeParameter(Param);
3271 InitializationKind Kind
3272 = InitializationKind::CreateCopy(Param->getLocation(),
3273 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3274 Expr *ResultE = Result.takeAs<Expr>();
3275
3276 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3277 Result = InitSeq.Perform(*this, Entity, Kind,
3278 MultiExprArg(*this, (void**)&ResultE, 1));
3279 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003280 return ExprError();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003281
3282 // Build the default argument expression.
Douglas Gregor033f6752009-12-23 23:03:06 +00003283 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003284 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003285 }
Mike Stump11289f42009-09-09 15:08:12 +00003286
Anders Carlsson355933d2009-08-25 03:49:14 +00003287 // If the default expression creates temporaries, we need to
3288 // push them to the current stack of expression temporaries so they'll
3289 // be properly destroyed.
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003290 // FIXME: We should really be rebuilding the default argument with new
3291 // bound temporaries; see the comment in PR5810.
Anders Carlsson714d0962009-12-15 19:16:31 +00003292 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3293 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson355933d2009-08-25 03:49:14 +00003294 }
3295
3296 // We already type-checked the argument, so we know it works.
Douglas Gregor033f6752009-12-23 23:03:06 +00003297 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003298}
3299
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003300/// ConvertArgumentsForCall - Converts the arguments specified in
3301/// Args/NumArgs to the parameter types of the function FDecl with
3302/// function prototype Proto. Call is the call expression itself, and
3303/// Fn is the function expression. For a C++ member function, this
3304/// routine does not attempt to convert the object argument. Returns
3305/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003306bool
3307Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003308 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003309 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003310 Expr **Args, unsigned NumArgs,
3311 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003312 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003313 // assignment, to the types of the corresponding parameter, ...
3314 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003315 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003316
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003317 // If too few arguments are available (and we don't have default
3318 // arguments for the remaining parameters), don't make the call.
3319 if (NumArgs < NumArgsInProto) {
3320 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3321 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3322 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003323 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003324 }
3325
3326 // If too many are passed and not variadic, error on the extras and drop
3327 // them.
3328 if (NumArgs > NumArgsInProto) {
3329 if (!Proto->isVariadic()) {
3330 Diag(Args[NumArgsInProto]->getLocStart(),
3331 diag::err_typecheck_call_too_many_args)
3332 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3333 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3334 Args[NumArgs-1]->getLocEnd());
3335 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003336 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003337 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003338 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003339 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003340 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003341 VariadicCallType CallType =
3342 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3343 if (Fn->getType()->isBlockPointerType())
3344 CallType = VariadicBlock; // Block
3345 else if (isa<MemberExpr>(Fn))
3346 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003347 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003348 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003349 if (Invalid)
3350 return true;
3351 unsigned TotalNumArgs = AllArgs.size();
3352 for (unsigned i = 0; i < TotalNumArgs; ++i)
3353 Call->setArg(i, AllArgs[i]);
3354
3355 return false;
3356}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003357
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003358bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3359 FunctionDecl *FDecl,
3360 const FunctionProtoType *Proto,
3361 unsigned FirstProtoArg,
3362 Expr **Args, unsigned NumArgs,
3363 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003364 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003365 unsigned NumArgsInProto = Proto->getNumArgs();
3366 unsigned NumArgsToCheck = NumArgs;
3367 bool Invalid = false;
3368 if (NumArgs != NumArgsInProto)
3369 // Use default arguments for missing arguments
3370 NumArgsToCheck = NumArgsInProto;
3371 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003372 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003373 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003374 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003375
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003376 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003377 if (ArgIx < NumArgs) {
3378 Arg = Args[ArgIx++];
3379
Eli Friedman3164fb12009-03-22 22:00:50 +00003380 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3381 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003382 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003383 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003384 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003385
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003386 // Pass the argument
3387 ParmVarDecl *Param = 0;
3388 if (FDecl && i < FDecl->getNumParams())
3389 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003390
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003391
3392 InitializedEntity Entity =
3393 Param? InitializedEntity::InitializeParameter(Param)
3394 : InitializedEntity::InitializeParameter(ProtoArgType);
3395 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3396 SourceLocation(),
3397 Owned(Arg));
3398 if (ArgE.isInvalid())
3399 return true;
3400
3401 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003402 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003403 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003404
Mike Stump11289f42009-09-09 15:08:12 +00003405 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003406 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003407 if (ArgExpr.isInvalid())
3408 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003409
Anders Carlsson355933d2009-08-25 03:49:14 +00003410 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003411 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003412 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003413 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003414
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003415 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003416 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003417 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003418 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003419 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003420 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003421 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003422 }
3423 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003424 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003425}
3426
Steve Naroff83895f72007-09-16 03:34:24 +00003427/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003428/// This provides the location of the left/right parens and a list of comma
3429/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003430Action::OwningExprResult
3431Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3432 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003433 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003434 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003435
3436 // Since this might be a postfix expression, get rid of ParenListExprs.
3437 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003438
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003439 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003440 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003441 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003442
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003443 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003444 // If this is a pseudo-destructor expression, build the call immediately.
3445 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3446 if (NumArgs > 0) {
3447 // Pseudo-destructor calls should not have any arguments.
3448 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3449 << CodeModificationHint::CreateRemoval(
3450 SourceRange(Args[0]->getLocStart(),
3451 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregorad8a3362009-09-04 17:36:40 +00003453 for (unsigned I = 0; I != NumArgs; ++I)
3454 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003455
Douglas Gregorad8a3362009-09-04 17:36:40 +00003456 NumArgs = 0;
3457 }
Mike Stump11289f42009-09-09 15:08:12 +00003458
Douglas Gregorad8a3362009-09-04 17:36:40 +00003459 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3460 RParenLoc));
3461 }
Mike Stump11289f42009-09-09 15:08:12 +00003462
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003463 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003464 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003465 // FIXME: Will need to cache the results of name lookup (including ADL) in
3466 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003467 bool Dependent = false;
3468 if (Fn->isTypeDependent())
3469 Dependent = true;
3470 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3471 Dependent = true;
3472
3473 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003474 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003475 Context.DependentTy, RParenLoc));
3476
3477 // Determine whether this is a call to an object (C++ [over.call.object]).
3478 if (Fn->getType()->isRecordType())
3479 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3480 CommaLocs, RParenLoc));
3481
John McCall10eae182009-11-30 22:42:35 +00003482 Expr *NakedFn = Fn->IgnoreParens();
3483
3484 // Determine whether this is a call to an unresolved member function.
3485 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3486 // If lookup was unresolved but not dependent (i.e. didn't find
3487 // an unresolved using declaration), it has to be an overloaded
3488 // function set, which means it must contain either multiple
3489 // declarations (all methods or method templates) or a single
3490 // method template.
3491 assert((MemE->getNumDecls() > 1) ||
3492 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003493 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003494
John McCall2d74de92009-12-01 22:10:20 +00003495 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3496 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003497 }
3498
Douglas Gregore254f902009-02-04 00:32:51 +00003499 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003500 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003501 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003502 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003503 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3504 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003505 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003506
3507 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003508 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003509 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3510 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003511 if (const FunctionProtoType *FPT =
3512 dyn_cast<FunctionProtoType>(BO->getType())) {
3513 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003514
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003515 ExprOwningPtr<CXXMemberCallExpr>
3516 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3517 NumArgs, ResultTy,
3518 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003519
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003520 if (CheckCallReturnType(FPT->getResultType(),
3521 BO->getRHS()->getSourceRange().getBegin(),
3522 TheCall.get(), 0))
3523 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003524
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003525 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3526 RParenLoc))
3527 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003528
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003529 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3530 }
3531 return ExprError(Diag(Fn->getLocStart(),
3532 diag::err_typecheck_call_not_function)
3533 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003534 }
3535 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003536 }
3537
Douglas Gregore254f902009-02-04 00:32:51 +00003538 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003539 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003540 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003541
Eli Friedmane14b1992009-12-26 03:35:45 +00003542 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-12-16 12:17:52 +00003543 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3544 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3545 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3546 CommaLocs, RParenLoc);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003547 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003548
John McCall57500772009-12-16 12:17:52 +00003549 NamedDecl *NDecl = 0;
3550 if (isa<DeclRefExpr>(NakedFn))
3551 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3552
John McCall2d74de92009-12-01 22:10:20 +00003553 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3554}
3555
John McCall57500772009-12-16 12:17:52 +00003556/// BuildResolvedCallExpr - Build a call to a resolved expression,
3557/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003558/// unary-convert to an expression of function-pointer or
3559/// block-pointer type.
3560///
3561/// \param NDecl the declaration being called, if available
3562Sema::OwningExprResult
3563Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3564 SourceLocation LParenLoc,
3565 Expr **Args, unsigned NumArgs,
3566 SourceLocation RParenLoc) {
3567 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3568
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003569 // Promote the function operand.
3570 UsualUnaryConversions(Fn);
3571
Chris Lattner08464942007-12-28 05:29:59 +00003572 // Make the call expr early, before semantic checks. This guarantees cleanup
3573 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003574 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3575 Args, NumArgs,
3576 Context.BoolTy,
3577 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003578
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003579 const FunctionType *FuncT;
3580 if (!Fn->getType()->isBlockPointerType()) {
3581 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3582 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003583 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003584 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003585 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3586 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003587 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003588 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003589 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003590 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003591 }
Chris Lattner08464942007-12-28 05:29:59 +00003592 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003593 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3594 << Fn->getType() << Fn->getSourceRange());
3595
Eli Friedman3164fb12009-03-22 22:00:50 +00003596 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003597 if (CheckCallReturnType(FuncT->getResultType(),
3598 Fn->getSourceRange().getBegin(), TheCall.get(),
3599 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003600 return ExprError();
3601
Chris Lattner08464942007-12-28 05:29:59 +00003602 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003603 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003604
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003605 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003606 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003607 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003608 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003609 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003610 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003611
Douglas Gregord8e97de2009-04-02 15:37:10 +00003612 if (FDecl) {
3613 // Check if we have too few/too many template arguments, based
3614 // on our knowledge of the function definition.
3615 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003616 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003617 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003618 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003619 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3620 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3621 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3622 }
3623 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003624 }
3625
Steve Naroff0b661582007-08-28 23:30:39 +00003626 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003627 for (unsigned i = 0; i != NumArgs; i++) {
3628 Expr *Arg = Args[i];
3629 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003630 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3631 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003632 PDiag(diag::err_call_incomplete_argument)
3633 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003634 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003635 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003636 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003637 }
Chris Lattner08464942007-12-28 05:29:59 +00003638
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003639 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3640 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003641 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3642 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003643
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003644 // Check for sentinels
3645 if (NDecl)
3646 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003647
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003648 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003649 if (FDecl) {
3650 if (CheckFunctionCall(FDecl, TheCall.get()))
3651 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003652
Douglas Gregor15fc9562009-09-12 00:22:50 +00003653 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003654 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3655 } else if (NDecl) {
3656 if (CheckBlockCall(NDecl, TheCall.get()))
3657 return ExprError();
3658 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003659
Anders Carlssonf8984012009-08-16 03:06:32 +00003660 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003661}
3662
Sebastian Redlb5d49352009-01-19 22:31:54 +00003663Action::OwningExprResult
3664Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3665 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003666 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003667 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003668 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003669
3670 TypeSourceInfo *TInfo;
3671 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3672 if (!TInfo)
3673 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3674
3675 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3676}
3677
3678Action::OwningExprResult
3679Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3680 SourceLocation RParenLoc, ExprArg InitExpr) {
3681 QualType literalType = TInfo->getType();
Sebastian Redlb5d49352009-01-19 22:31:54 +00003682 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003683
Eli Friedman37a186d2008-05-20 05:22:08 +00003684 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003685 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003686 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3687 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003688 } else if (!literalType->isDependentType() &&
3689 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003690 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003691 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003692 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003693 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003694
Douglas Gregor85dabae2009-12-16 01:38:02 +00003695 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003696 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003697 InitializationKind Kind
3698 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3699 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003700 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3701 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3702 MultiExprArg(*this, (void**)&literalExpr, 1),
3703 &literalType);
3704 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003705 return ExprError();
Eli Friedmana553d4a2009-12-22 02:35:53 +00003706 InitExpr.release();
3707 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffd32419d2008-01-14 18:19:28 +00003708
Chris Lattner79413952008-12-04 23:50:19 +00003709 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003710 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003711 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003712 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003713 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003714
3715 Result.release();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003716
John McCall5d7aa7f2010-01-19 22:33:45 +00003717 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003718 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003719}
3720
Sebastian Redlb5d49352009-01-19 22:31:54 +00003721Action::OwningExprResult
3722Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003723 SourceLocation RBraceLoc) {
3724 unsigned NumInit = initlist.size();
3725 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003726
Steve Naroff30d242c2007-09-15 18:49:24 +00003727 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003728 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003729
Mike Stump4e1f26a2009-02-19 03:04:26 +00003730 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003731 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003732 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003733 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003734}
3735
Anders Carlsson094c4592009-10-18 18:12:03 +00003736static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3737 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003738 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003739 return CastExpr::CK_NoOp;
3740
3741 if (SrcTy->hasPointerRepresentation()) {
3742 if (DestTy->hasPointerRepresentation())
Fariborz Jahanian2b9fc832009-12-15 21:34:52 +00003743 return DestTy->isObjCObjectPointerType() ?
3744 CastExpr::CK_AnyPointerToObjCPointerCast :
3745 CastExpr::CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003746 if (DestTy->isIntegerType())
3747 return CastExpr::CK_PointerToIntegral;
3748 }
3749
3750 if (SrcTy->isIntegerType()) {
3751 if (DestTy->isIntegerType())
3752 return CastExpr::CK_IntegralCast;
3753 if (DestTy->hasPointerRepresentation())
3754 return CastExpr::CK_IntegralToPointer;
3755 if (DestTy->isRealFloatingType())
3756 return CastExpr::CK_IntegralToFloating;
3757 }
3758
3759 if (SrcTy->isRealFloatingType()) {
3760 if (DestTy->isRealFloatingType())
3761 return CastExpr::CK_FloatingCast;
3762 if (DestTy->isIntegerType())
3763 return CastExpr::CK_FloatingToIntegral;
3764 }
3765
3766 // FIXME: Assert here.
3767 // assert(false && "Unhandled cast combination!");
3768 return CastExpr::CK_Unknown;
3769}
3770
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003771/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003772bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003773 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003774 CXXMethodDecl *& ConversionDecl,
3775 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003776 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003777 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3778 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003779
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003780 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003781
3782 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3783 // type needs to be scalar.
3784 if (castType->isVoidType()) {
3785 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003786 Kind = CastExpr::CK_ToVoid;
3787 return false;
3788 }
3789
3790 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003791 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003792 (castType->isStructureType() || castType->isUnionType())) {
3793 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003794 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003795 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3796 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003797 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003798 return false;
3799 }
3800
3801 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003802 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003803 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003804 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003805 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003806 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003807 if (Context.hasSameUnqualifiedType(Field->getType(),
3808 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003809 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3810 << castExpr->getSourceRange();
3811 break;
3812 }
3813 }
3814 if (Field == FieldEnd)
3815 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3816 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003817 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003818 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003819 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003820
3821 // Reject any other conversions to non-scalar types.
3822 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3823 << castType << castExpr->getSourceRange();
3824 }
3825
3826 if (!castExpr->getType()->isScalarType() &&
3827 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003828 return Diag(castExpr->getLocStart(),
3829 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003830 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003831 }
3832
Anders Carlsson43d70f82009-10-16 05:23:41 +00003833 if (castType->isExtVectorType())
3834 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3835
Anders Carlsson525b76b2009-10-16 02:48:28 +00003836 if (castType->isVectorType())
3837 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3838 if (castExpr->getType()->isVectorType())
3839 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3840
3841 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003842 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003843
Anders Carlsson43d70f82009-10-16 05:23:41 +00003844 if (isa<ObjCSelectorExpr>(castExpr))
3845 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3846
Anders Carlsson525b76b2009-10-16 02:48:28 +00003847 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003848 QualType castExprType = castExpr->getType();
3849 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3850 return Diag(castExpr->getLocStart(),
3851 diag::err_cast_pointer_from_non_pointer_int)
3852 << castExprType << castExpr->getSourceRange();
3853 } else if (!castExpr->getType()->isArithmeticType()) {
3854 if (!castType->isIntegralType() && castType->isArithmeticType())
3855 return Diag(castExpr->getLocStart(),
3856 diag::err_cast_pointer_to_non_pointer_int)
3857 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003858 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003859
3860 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003861 return false;
3862}
3863
Anders Carlsson525b76b2009-10-16 02:48:28 +00003864bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3865 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003866 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003867
Anders Carlssonde71adf2007-11-27 05:51:55 +00003868 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003869 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003870 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003871 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003872 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003873 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003874 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003875 } else
3876 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003877 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003878 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003879
Anders Carlsson525b76b2009-10-16 02:48:28 +00003880 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003881 return false;
3882}
3883
Anders Carlsson43d70f82009-10-16 05:23:41 +00003884bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3885 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003886 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003887
3888 QualType SrcTy = CastExpr->getType();
3889
Nate Begemanc8961a42009-06-27 22:05:55 +00003890 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3891 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003892 if (SrcTy->isVectorType()) {
3893 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3894 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3895 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003896 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003897 return false;
3898 }
3899
Nate Begemanbd956c42009-06-28 02:36:38 +00003900 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003901 // conversion will take place first from scalar to elt type, and then
3902 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003903 if (SrcTy->isPointerType())
3904 return Diag(R.getBegin(),
3905 diag::err_invalid_conversion_between_vector_and_scalar)
3906 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003907
3908 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3909 ImpCastExprToType(CastExpr, DestElemTy,
3910 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003911
3912 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003913 return false;
3914}
3915
Sebastian Redlb5d49352009-01-19 22:31:54 +00003916Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003917Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003918 SourceLocation RParenLoc, ExprArg Op) {
3919 assert((Ty != 0) && (Op.get() != 0) &&
3920 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003921
John McCall97513962010-01-15 18:39:57 +00003922 TypeSourceInfo *castTInfo;
3923 QualType castType = GetTypeFromParser(Ty, &castTInfo);
3924 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00003925 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00003926
Nate Begeman5ec4b312009-08-10 23:49:36 +00003927 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallebe54742010-01-15 18:56:44 +00003928 Expr *castExpr = (Expr *)Op.get();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003929 if (isa<ParenListExpr>(castExpr))
John McCalle15bbff2010-01-18 19:35:47 +00003930 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
3931 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00003932
3933 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
3934}
3935
3936Action::OwningExprResult
3937Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
3938 SourceLocation RParenLoc, ExprArg Op) {
3939 Expr *castExpr = static_cast<Expr*>(Op.get());
3940
Anders Carlssone9766d52009-09-09 21:33:21 +00003941 CXXMethodDecl *Method = 0;
John McCallebe54742010-01-15 18:56:44 +00003942 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3943 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003944 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003945 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003946
3947 if (Method) {
John McCallebe54742010-01-15 18:56:44 +00003948 // FIXME: preserve type source info here
3949 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, Ty->getType(),
3950 Kind, Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003951
Anders Carlssone9766d52009-09-09 21:33:21 +00003952 if (CastArg.isInvalid())
3953 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003954
Anders Carlssone9766d52009-09-09 21:33:21 +00003955 castExpr = CastArg.takeAs<Expr>();
3956 } else {
3957 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003958 }
Mike Stump11289f42009-09-09 15:08:12 +00003959
John McCallebe54742010-01-15 18:56:44 +00003960 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
3961 Kind, castExpr, Ty,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003962 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003963}
3964
Nate Begeman5ec4b312009-08-10 23:49:36 +00003965/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3966/// of comma binary operators.
3967Action::OwningExprResult
3968Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3969 Expr *expr = EA.takeAs<Expr>();
3970 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3971 if (!E)
3972 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003973
Nate Begeman5ec4b312009-08-10 23:49:36 +00003974 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003975
Nate Begeman5ec4b312009-08-10 23:49:36 +00003976 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3977 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3978 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003979
Nate Begeman5ec4b312009-08-10 23:49:36 +00003980 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3981}
3982
3983Action::OwningExprResult
3984Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3985 SourceLocation RParenLoc, ExprArg Op,
John McCalle15bbff2010-01-18 19:35:47 +00003986 TypeSourceInfo *TInfo) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003987 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCalle15bbff2010-01-18 19:35:47 +00003988 QualType Ty = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003989
3990 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003991 // then handle it as such.
3992 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3993 if (PE->getNumExprs() == 0) {
3994 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3995 return ExprError();
3996 }
3997
3998 llvm::SmallVector<Expr *, 8> initExprs;
3999 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4000 initExprs.push_back(PE->getExpr(i));
4001
4002 // FIXME: This means that pretty-printing the final AST will produce curly
4003 // braces instead of the original commas.
4004 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00004005 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004006 initExprs.size(), RParenLoc);
4007 E->setType(Ty);
John McCalle15bbff2010-01-18 19:35:47 +00004008 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004009 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004010 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004011 // sequence of BinOp comma operators.
4012 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCalle15bbff2010-01-18 19:35:47 +00004013 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004014 }
4015}
4016
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004017Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004018 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004019 MultiExprArg Val,
4020 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004021 unsigned nexprs = Val.size();
4022 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004023 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4024 Expr *expr;
4025 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4026 expr = new (Context) ParenExpr(L, R, exprs[0]);
4027 else
4028 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004029 return Owned(expr);
4030}
4031
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004032/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4033/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004034/// C99 6.5.15
4035QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4036 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004037 // C++ is sufficiently different to merit its own checker.
4038 if (getLangOptions().CPlusPlus)
4039 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4040
John McCall1fa36b72009-11-05 09:23:39 +00004041 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
4042
Chris Lattner432cff52009-02-18 04:28:32 +00004043 UsualUnaryConversions(Cond);
4044 UsualUnaryConversions(LHS);
4045 UsualUnaryConversions(RHS);
4046 QualType CondTy = Cond->getType();
4047 QualType LHSTy = LHS->getType();
4048 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004049
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004050 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004051 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4052 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4053 << CondTy;
4054 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004055 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004056
Chris Lattnere2949f42008-01-06 22:42:25 +00004057 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004058 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4059 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004060
Chris Lattnere2949f42008-01-06 22:42:25 +00004061 // If both operands have arithmetic type, do the usual arithmetic conversions
4062 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004063 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4064 UsualArithmeticConversions(LHS, RHS);
4065 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004066 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004067
Chris Lattnere2949f42008-01-06 22:42:25 +00004068 // If both operands are the same structure or union type, the result is that
4069 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004070 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4071 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004072 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004073 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004074 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004075 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004076 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004077 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004078
Chris Lattnere2949f42008-01-06 22:42:25 +00004079 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004080 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004081 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4082 if (!LHSTy->isVoidType())
4083 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4084 << RHS->getSourceRange();
4085 if (!RHSTy->isVoidType())
4086 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4087 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004088 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4089 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004090 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004091 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004092 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4093 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004094 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004095 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004096 // promote the null to a pointer.
4097 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004098 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004099 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004100 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004101 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004102 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004103 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004104 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004105
4106 // All objective-c pointer type analysis is done here.
4107 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4108 QuestionLoc);
4109 if (!compositeType.isNull())
4110 return compositeType;
4111
4112
Steve Naroff05efa972009-07-01 14:36:47 +00004113 // Handle block pointer types.
4114 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4115 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4116 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4117 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004118 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4119 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004120 return destType;
4121 }
4122 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004123 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004124 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004125 }
Steve Naroff05efa972009-07-01 14:36:47 +00004126 // We have 2 block pointer types.
4127 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4128 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004129 return LHSTy;
4130 }
Steve Naroff05efa972009-07-01 14:36:47 +00004131 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004132 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4133 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004134
Steve Naroff05efa972009-07-01 14:36:47 +00004135 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4136 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004137 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004138 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004139 // In this situation, we assume void* type. No especially good
4140 // reason, but this is what gcc does, and we do have to pick
4141 // to get a consistent AST.
4142 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004143 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4144 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004145 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004146 }
Steve Naroff05efa972009-07-01 14:36:47 +00004147 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004148 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4149 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004150 return LHSTy;
4151 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004152
Steve Naroff05efa972009-07-01 14:36:47 +00004153 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4154 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4155 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004156 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4157 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004158
4159 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4160 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4161 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004162 QualType destPointee
4163 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004164 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004165 // Add qualifiers if necessary.
4166 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4167 // Promote to void*.
4168 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004169 return destType;
4170 }
4171 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004172 QualType destPointee
4173 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004174 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004175 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004176 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004177 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004178 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004179 return destType;
4180 }
4181
4182 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4183 // Two identical pointer types are always compatible.
4184 return LHSTy;
4185 }
4186 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4187 rhptee.getUnqualifiedType())) {
4188 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4189 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4190 // In this situation, we assume void* type. No especially good
4191 // reason, but this is what gcc does, and we do have to pick
4192 // to get a consistent AST.
4193 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004194 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4195 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004196 return incompatTy;
4197 }
4198 // The pointer types are compatible.
4199 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4200 // differently qualified versions of compatible types, the result type is
4201 // a pointer to an appropriately qualified version of the *composite*
4202 // type.
4203 // FIXME: Need to calculate the composite type.
4204 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004205 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4206 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004207 return LHSTy;
4208 }
Mike Stump11289f42009-09-09 15:08:12 +00004209
Steve Naroff05efa972009-07-01 14:36:47 +00004210 // GCC compatibility: soften pointer/integer mismatch.
4211 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4212 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4213 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004214 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004215 return RHSTy;
4216 }
4217 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4218 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4219 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004220 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004221 return LHSTy;
4222 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004223
Chris Lattnere2949f42008-01-06 22:42:25 +00004224 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004225 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4226 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004227 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004228}
4229
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004230/// FindCompositeObjCPointerType - Helper method to find composite type of
4231/// two objective-c pointer types of the two input expressions.
4232QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4233 SourceLocation QuestionLoc) {
4234 QualType LHSTy = LHS->getType();
4235 QualType RHSTy = RHS->getType();
4236
4237 // Handle things like Class and struct objc_class*. Here we case the result
4238 // to the pseudo-builtin, because that will be implicitly cast back to the
4239 // redefinition type if an attempt is made to access its fields.
4240 if (LHSTy->isObjCClassType() &&
4241 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4242 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4243 return LHSTy;
4244 }
4245 if (RHSTy->isObjCClassType() &&
4246 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4247 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4248 return RHSTy;
4249 }
4250 // And the same for struct objc_object* / id
4251 if (LHSTy->isObjCIdType() &&
4252 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4253 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4254 return LHSTy;
4255 }
4256 if (RHSTy->isObjCIdType() &&
4257 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4258 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4259 return RHSTy;
4260 }
4261 // And the same for struct objc_selector* / SEL
4262 if (Context.isObjCSelType(LHSTy) &&
4263 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4264 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4265 return LHSTy;
4266 }
4267 if (Context.isObjCSelType(RHSTy) &&
4268 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4269 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4270 return RHSTy;
4271 }
4272 // Check constraints for Objective-C object pointers types.
4273 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4274
4275 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4276 // Two identical object pointer types are always compatible.
4277 return LHSTy;
4278 }
4279 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4280 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4281 QualType compositeType = LHSTy;
4282
4283 // If both operands are interfaces and either operand can be
4284 // assigned to the other, use that type as the composite
4285 // type. This allows
4286 // xxx ? (A*) a : (B*) b
4287 // where B is a subclass of A.
4288 //
4289 // Additionally, as for assignment, if either type is 'id'
4290 // allow silent coercion. Finally, if the types are
4291 // incompatible then make sure to use 'id' as the composite
4292 // type so the result is acceptable for sending messages to.
4293
4294 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4295 // It could return the composite type.
4296 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4297 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4298 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4299 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4300 } else if ((LHSTy->isObjCQualifiedIdType() ||
4301 RHSTy->isObjCQualifiedIdType()) &&
4302 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4303 // Need to handle "id<xx>" explicitly.
4304 // GCC allows qualified id and any Objective-C type to devolve to
4305 // id. Currently localizing to here until clear this should be
4306 // part of ObjCQualifiedIdTypesAreCompatible.
4307 compositeType = Context.getObjCIdType();
4308 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4309 compositeType = Context.getObjCIdType();
4310 } else if (!(compositeType =
4311 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4312 ;
4313 else {
4314 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4315 << LHSTy << RHSTy
4316 << LHS->getSourceRange() << RHS->getSourceRange();
4317 QualType incompatTy = Context.getObjCIdType();
4318 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4319 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4320 return incompatTy;
4321 }
4322 // The object pointer types are compatible.
4323 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4324 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4325 return compositeType;
4326 }
4327 // Check Objective-C object pointer types and 'void *'
4328 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4329 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4330 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4331 QualType destPointee
4332 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4333 QualType destType = Context.getPointerType(destPointee);
4334 // Add qualifiers if necessary.
4335 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4336 // Promote to void*.
4337 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4338 return destType;
4339 }
4340 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4341 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4342 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4343 QualType destPointee
4344 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4345 QualType destType = Context.getPointerType(destPointee);
4346 // Add qualifiers if necessary.
4347 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4348 // Promote to void*.
4349 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4350 return destType;
4351 }
4352 return QualType();
4353}
4354
Steve Naroff83895f72007-09-16 03:34:24 +00004355/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004356/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004357Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4358 SourceLocation ColonLoc,
4359 ExprArg Cond, ExprArg LHS,
4360 ExprArg RHS) {
4361 Expr *CondExpr = (Expr *) Cond.get();
4362 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004363
4364 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4365 // was the condition.
4366 bool isLHSNull = LHSExpr == 0;
4367 if (isLHSNull)
4368 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004369
4370 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004371 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004372 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004373 return ExprError();
4374
4375 Cond.release();
4376 LHS.release();
4377 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004378 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004379 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004380 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004381}
4382
Steve Naroff3f597292007-05-11 22:18:03 +00004383// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004384// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004385// routine is it effectively iqnores the qualifiers on the top level pointee.
4386// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4387// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004388Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004389Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004390 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004391
David Chisnall9f57c292009-08-17 16:35:33 +00004392 if ((lhsType->isObjCClassType() &&
4393 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4394 (rhsType->isObjCClassType() &&
4395 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4396 return Compatible;
4397 }
4398
Steve Naroff1f4d7272007-05-11 04:00:31 +00004399 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004400 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4401 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004402
Steve Naroff1f4d7272007-05-11 04:00:31 +00004403 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004404 lhptee = Context.getCanonicalType(lhptee);
4405 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004406
Chris Lattner9bad62c2008-01-04 18:04:52 +00004407 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004408
4409 // C99 6.5.16.1p1: This following citation is common to constraints
4410 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4411 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004412 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004413 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004414 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004415
Mike Stump4e1f26a2009-02-19 03:04:26 +00004416 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4417 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004418 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004419 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004420 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004421 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004422
Chris Lattner0a788432008-01-03 22:56:36 +00004423 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004424 assert(rhptee->isFunctionType());
4425 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004426 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004427
Chris Lattner0a788432008-01-03 22:56:36 +00004428 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004429 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004430 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004431
4432 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004433 assert(lhptee->isFunctionType());
4434 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004435 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004436 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004437 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004438 lhptee = lhptee.getUnqualifiedType();
4439 rhptee = rhptee.getUnqualifiedType();
4440 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4441 // Check if the pointee types are compatible ignoring the sign.
4442 // We explicitly check for char so that we catch "char" vs
4443 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004444 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004445 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004446 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004447 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004448
4449 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004450 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004451 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004452 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004453
Eli Friedman80160bd2009-03-22 23:59:44 +00004454 if (lhptee == rhptee) {
4455 // Types are compatible ignoring the sign. Qualifier incompatibility
4456 // takes priority over sign incompatibility because the sign
4457 // warning can be disabled.
4458 if (ConvTy != Compatible)
4459 return ConvTy;
4460 return IncompatiblePointerSign;
4461 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004462
4463 // If we are a multi-level pointer, it's possible that our issue is simply
4464 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4465 // the eventual target type is the same and the pointers have the same
4466 // level of indirection, this must be the issue.
4467 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4468 do {
4469 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4470 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4471
4472 lhptee = Context.getCanonicalType(lhptee);
4473 rhptee = Context.getCanonicalType(rhptee);
4474 } while (lhptee->isPointerType() && rhptee->isPointerType());
4475
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004476 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004477 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004478 }
4479
Eli Friedman80160bd2009-03-22 23:59:44 +00004480 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004481 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004482 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004483 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004484}
4485
Steve Naroff081c7422008-09-04 15:10:53 +00004486/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4487/// block pointer types are compatible or whether a block and normal pointer
4488/// are compatible. It is more restrict than comparing two function pointer
4489// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004490Sema::AssignConvertType
4491Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004492 QualType rhsType) {
4493 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004494
Steve Naroff081c7422008-09-04 15:10:53 +00004495 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004496 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4497 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004498
Steve Naroff081c7422008-09-04 15:10:53 +00004499 // make sure we operate on the canonical type
4500 lhptee = Context.getCanonicalType(lhptee);
4501 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004502
Steve Naroff081c7422008-09-04 15:10:53 +00004503 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004504
Steve Naroff081c7422008-09-04 15:10:53 +00004505 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004506 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004507 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004508
Eli Friedmana6638ca2009-06-08 05:08:54 +00004509 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004510 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004511 return ConvTy;
4512}
4513
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004514/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4515/// for assignment compatibility.
4516Sema::AssignConvertType
4517Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4518 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4519 return Compatible;
4520 QualType lhptee =
4521 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4522 QualType rhptee =
4523 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4524 // make sure we operate on the canonical type
4525 lhptee = Context.getCanonicalType(lhptee);
4526 rhptee = Context.getCanonicalType(rhptee);
4527 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4528 return CompatiblePointerDiscardsQualifiers;
4529
4530 if (Context.typesAreCompatible(lhsType, rhsType))
4531 return Compatible;
4532 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4533 return IncompatibleObjCQualifiedId;
4534 return IncompatiblePointer;
4535}
4536
Mike Stump4e1f26a2009-02-19 03:04:26 +00004537/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4538/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004539/// pointers. Here are some objectionable examples that GCC considers warnings:
4540///
4541/// int a, *pint;
4542/// short *pshort;
4543/// struct foo *pfoo;
4544///
4545/// pint = pshort; // warning: assignment from incompatible pointer type
4546/// a = pint; // warning: assignment makes integer from pointer without a cast
4547/// pint = a; // warning: assignment makes pointer from integer without a cast
4548/// pint = pfoo; // warning: assignment from incompatible pointer type
4549///
4550/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004551/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004552///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004553Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004554Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004555 // Get canonical types. We're not formatting these types, just comparing
4556 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004557 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4558 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004559
4560 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004561 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004562
David Chisnall9f57c292009-08-17 16:35:33 +00004563 if ((lhsType->isObjCClassType() &&
4564 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4565 (rhsType->isObjCClassType() &&
4566 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4567 return Compatible;
4568 }
4569
Douglas Gregor6b754842008-10-28 00:22:11 +00004570 // If the left-hand side is a reference type, then we are in a
4571 // (rare!) case where we've allowed the use of references in C,
4572 // e.g., as a parameter type in a built-in function. In this case,
4573 // just make sure that the type referenced is compatible with the
4574 // right-hand side type. The caller is responsible for adjusting
4575 // lhsType so that the resulting expression does not have reference
4576 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004577 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004578 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004579 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004580 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004581 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004582 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4583 // to the same ExtVector type.
4584 if (lhsType->isExtVectorType()) {
4585 if (rhsType->isExtVectorType())
4586 return lhsType == rhsType ? Compatible : Incompatible;
4587 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4588 return Compatible;
4589 }
Mike Stump11289f42009-09-09 15:08:12 +00004590
Nate Begeman191a6b12008-07-14 18:02:46 +00004591 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004592 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004593 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004594 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004595 if (getLangOptions().LaxVectorConversions &&
4596 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004597 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004598 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004599 }
4600 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004601 }
Eli Friedman3360d892008-05-30 18:07:22 +00004602
Chris Lattner881a2122008-01-04 23:32:24 +00004603 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004604 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004605
Chris Lattnerec646832008-04-07 06:49:41 +00004606 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004607 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004608 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004609
Chris Lattnerec646832008-04-07 06:49:41 +00004610 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004611 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004612
Steve Naroffaccc4882009-07-20 17:56:53 +00004613 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004614 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004615 if (lhsType->isVoidPointerType()) // an exception to the rule.
4616 return Compatible;
4617 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004618 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004619 if (rhsType->getAs<BlockPointerType>()) {
4620 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004621 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004622
4623 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004624 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004625 return Compatible;
4626 }
Steve Naroff081c7422008-09-04 15:10:53 +00004627 return Incompatible;
4628 }
4629
4630 if (isa<BlockPointerType>(lhsType)) {
4631 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004632 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004633
Steve Naroff32d072c2008-09-29 18:10:17 +00004634 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004635 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004636 return Compatible;
4637
Steve Naroff081c7422008-09-04 15:10:53 +00004638 if (rhsType->isBlockPointerType())
4639 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004640
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004641 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004642 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004643 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004644 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004645 return Incompatible;
4646 }
4647
Steve Naroff7cae42b2009-07-10 23:34:53 +00004648 if (isa<ObjCObjectPointerType>(lhsType)) {
4649 if (rhsType->isIntegerType())
4650 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004651
Steve Naroffaccc4882009-07-20 17:56:53 +00004652 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004653 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004654 if (rhsType->isVoidPointerType()) // an exception to the rule.
4655 return Compatible;
4656 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004657 }
4658 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004659 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004660 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004661 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004662 if (RHSPT->getPointeeType()->isVoidType())
4663 return Compatible;
4664 }
4665 // Treat block pointers as objects.
4666 if (rhsType->isBlockPointerType())
4667 return Compatible;
4668 return Incompatible;
4669 }
Chris Lattnerec646832008-04-07 06:49:41 +00004670 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004671 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004672 if (lhsType == Context.BoolTy)
4673 return Compatible;
4674
4675 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004676 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004677
Mike Stump4e1f26a2009-02-19 03:04:26 +00004678 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004679 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004680
4681 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004682 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004683 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004684 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004685 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004686 if (isa<ObjCObjectPointerType>(rhsType)) {
4687 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4688 if (lhsType == Context.BoolTy)
4689 return Compatible;
4690
4691 if (lhsType->isIntegerType())
4692 return PointerToInt;
4693
Steve Naroffaccc4882009-07-20 17:56:53 +00004694 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004695 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004696 if (lhsType->isVoidPointerType()) // an exception to the rule.
4697 return Compatible;
4698 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004699 }
4700 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004701 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004702 return Compatible;
4703 return Incompatible;
4704 }
Eli Friedman3360d892008-05-30 18:07:22 +00004705
Chris Lattnera52c2f22008-01-04 23:18:45 +00004706 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004707 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004708 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004709 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004710 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004711}
4712
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004713/// \brief Constructs a transparent union from an expression that is
4714/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004715static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004716 QualType UnionType, FieldDecl *Field) {
4717 // Build an initializer list that designates the appropriate member
4718 // of the transparent union.
4719 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4720 &E, 1,
4721 SourceLocation());
4722 Initializer->setType(UnionType);
4723 Initializer->setInitializedFieldInUnion(Field);
4724
4725 // Build a compound literal constructing a value of the transparent
4726 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00004727 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00004728 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCalle15bbff2010-01-18 19:35:47 +00004729 Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004730}
4731
4732Sema::AssignConvertType
4733Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4734 QualType FromType = rExpr->getType();
4735
Mike Stump11289f42009-09-09 15:08:12 +00004736 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004737 // transparent_union GCC extension.
4738 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004739 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004740 return Incompatible;
4741
4742 // The field to initialize within the transparent union.
4743 RecordDecl *UD = UT->getDecl();
4744 FieldDecl *InitField = 0;
4745 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004746 for (RecordDecl::field_iterator it = UD->field_begin(),
4747 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004748 it != itend; ++it) {
4749 if (it->getType()->isPointerType()) {
4750 // If the transparent union contains a pointer type, we allow:
4751 // 1) void pointer
4752 // 2) null pointer constant
4753 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004754 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004755 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004756 InitField = *it;
4757 break;
4758 }
Mike Stump11289f42009-09-09 15:08:12 +00004759
Douglas Gregor56751b52009-09-25 04:25:58 +00004760 if (rExpr->isNullPointerConstant(Context,
4761 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004762 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004763 InitField = *it;
4764 break;
4765 }
4766 }
4767
4768 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4769 == Compatible) {
4770 InitField = *it;
4771 break;
4772 }
4773 }
4774
4775 if (!InitField)
4776 return Incompatible;
4777
4778 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4779 return Compatible;
4780}
4781
Chris Lattner9bad62c2008-01-04 18:04:52 +00004782Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004783Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004784 if (getLangOptions().CPlusPlus) {
4785 if (!lhsType->isRecordType()) {
4786 // C++ 5.17p3: If the left operand is not of class type, the
4787 // expression is implicitly converted (C++ 4) to the
4788 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004789 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004790 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00004791 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004792 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004793 }
4794
4795 // FIXME: Currently, we fall through and treat C++ classes like C
4796 // structures.
4797 }
4798
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004799 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4800 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004801 if ((lhsType->isPointerType() ||
4802 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004803 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004804 && rExpr->isNullPointerConstant(Context,
4805 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004806 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004807 return Compatible;
4808 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004809
Chris Lattnere6dcd502007-10-16 02:55:40 +00004810 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004811 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004812 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004813 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004814 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004815 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004816 if (!lhsType->isReferenceType())
4817 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004818
Chris Lattner9bad62c2008-01-04 18:04:52 +00004819 Sema::AssignConvertType result =
4820 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004821
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004822 // C99 6.5.16.1p2: The value of the right operand is converted to the
4823 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004824 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4825 // so that we can use references in built-in functions even in C.
4826 // The getNonReferenceType() call makes sure that the resulting expression
4827 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004828 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004829 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4830 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004831 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004832}
4833
Chris Lattner326f7572008-11-18 01:30:42 +00004834QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004835 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004836 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004837 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004838 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004839}
4840
Chris Lattnerfaa54172010-01-12 21:23:57 +00004841QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004842 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004843 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004844 QualType lhsType =
4845 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4846 QualType rhsType =
4847 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004848
Nate Begeman191a6b12008-07-14 18:02:46 +00004849 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004850 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004851 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004852
Nate Begeman191a6b12008-07-14 18:02:46 +00004853 // Handle the case of a vector & extvector type of the same size and element
4854 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004855 if (getLangOptions().LaxVectorConversions) {
4856 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004857 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4858 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004859 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004860 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004861 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004862 }
4863 }
4864 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004865
Nate Begemanbd956c42009-06-28 02:36:38 +00004866 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4867 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4868 bool swapped = false;
4869 if (rhsType->isExtVectorType()) {
4870 swapped = true;
4871 std::swap(rex, lex);
4872 std::swap(rhsType, lhsType);
4873 }
Mike Stump11289f42009-09-09 15:08:12 +00004874
Nate Begeman886448d2009-06-28 19:12:57 +00004875 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004876 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004877 QualType EltTy = LV->getElementType();
4878 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4879 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004880 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004881 if (swapped) std::swap(rex, lex);
4882 return lhsType;
4883 }
4884 }
4885 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4886 rhsType->isRealFloatingType()) {
4887 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004888 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004889 if (swapped) std::swap(rex, lex);
4890 return lhsType;
4891 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004892 }
4893 }
Mike Stump11289f42009-09-09 15:08:12 +00004894
Nate Begeman886448d2009-06-28 19:12:57 +00004895 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004896 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004897 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004898 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004899 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004900}
4901
Chris Lattnerfaa54172010-01-12 21:23:57 +00004902QualType Sema::CheckMultiplyDivideOperands(
4903 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004904 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004905 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004906
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004907 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004908
Chris Lattnerfaa54172010-01-12 21:23:57 +00004909 if (!lex->getType()->isArithmeticType() ||
4910 !rex->getType()->isArithmeticType())
4911 return InvalidOperands(Loc, lex, rex);
4912
4913 // Check for division by zero.
4914 if (isDiv &&
4915 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004916 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
4917 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004918
4919 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004920}
4921
Chris Lattnerfaa54172010-01-12 21:23:57 +00004922QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004923 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004924 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4925 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4926 return CheckVectorOperands(Loc, lex, rex);
4927 return InvalidOperands(Loc, lex, rex);
4928 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004929
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004930 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004931
Chris Lattnerfaa54172010-01-12 21:23:57 +00004932 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4933 return InvalidOperands(Loc, lex, rex);
4934
4935 // Check for remainder by zero.
4936 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004937 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4938 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004939
4940 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004941}
4942
Chris Lattnerfaa54172010-01-12 21:23:57 +00004943QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004944 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004945 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4946 QualType compType = CheckVectorOperands(Loc, lex, rex);
4947 if (CompLHSTy) *CompLHSTy = compType;
4948 return compType;
4949 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004950
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004951 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004952
Steve Naroffe4718892007-04-27 18:30:00 +00004953 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004954 if (lex->getType()->isArithmeticType() &&
4955 rex->getType()->isArithmeticType()) {
4956 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004957 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004958 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004959
Eli Friedman8e122982008-05-18 18:08:51 +00004960 // Put any potential pointer into PExp
4961 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004962 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004963 std::swap(PExp, IExp);
4964
Steve Naroff6b712a72009-07-14 18:25:06 +00004965 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004966
Eli Friedman8e122982008-05-18 18:08:51 +00004967 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004968 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004969
Chris Lattner12bdebb2009-04-24 23:50:08 +00004970 // Check for arithmetic on pointers to incomplete types.
4971 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004972 if (getLangOptions().CPlusPlus) {
4973 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004974 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004975 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004976 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004977
4978 // GNU extension: arithmetic on pointer to void
4979 Diag(Loc, diag::ext_gnu_void_ptr)
4980 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004981 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004982 if (getLangOptions().CPlusPlus) {
4983 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4984 << lex->getType() << lex->getSourceRange();
4985 return QualType();
4986 }
4987
4988 // GNU extension: arithmetic on pointer to function
4989 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4990 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004991 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004992 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004993 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004994 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004995 PExp->getType()->isObjCObjectPointerType()) &&
4996 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004997 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4998 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004999 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005000 return QualType();
5001 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00005002 // Diagnose bad cases where we step over interface counts.
5003 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5004 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5005 << PointeeTy << PExp->getSourceRange();
5006 return QualType();
5007 }
Mike Stump11289f42009-09-09 15:08:12 +00005008
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005009 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00005010 QualType LHSTy = Context.isPromotableBitField(lex);
5011 if (LHSTy.isNull()) {
5012 LHSTy = lex->getType();
5013 if (LHSTy->isPromotableIntegerType())
5014 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005015 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005016 *CompLHSTy = LHSTy;
5017 }
Eli Friedman8e122982008-05-18 18:08:51 +00005018 return PExp->getType();
5019 }
5020 }
5021
Chris Lattner326f7572008-11-18 01:30:42 +00005022 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005023}
5024
Chris Lattner2a3569b2008-04-07 05:30:13 +00005025// C99 6.5.6
5026QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005027 SourceLocation Loc, QualType* CompLHSTy) {
5028 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5029 QualType compType = CheckVectorOperands(Loc, lex, rex);
5030 if (CompLHSTy) *CompLHSTy = compType;
5031 return compType;
5032 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005033
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005034 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005035
Chris Lattner4d62f422007-12-09 21:53:25 +00005036 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005037
Chris Lattner4d62f422007-12-09 21:53:25 +00005038 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00005039 if (lex->getType()->isArithmeticType()
5040 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005041 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005042 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005043 }
Mike Stump11289f42009-09-09 15:08:12 +00005044
Chris Lattner4d62f422007-12-09 21:53:25 +00005045 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00005046 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00005047 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005048
Douglas Gregorac1fb652009-03-24 19:52:54 +00005049 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005050
Douglas Gregorac1fb652009-03-24 19:52:54 +00005051 bool ComplainAboutVoid = false;
5052 Expr *ComplainAboutFunc = 0;
5053 if (lpointee->isVoidType()) {
5054 if (getLangOptions().CPlusPlus) {
5055 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5056 << lex->getSourceRange() << rex->getSourceRange();
5057 return QualType();
5058 }
5059
5060 // GNU C extension: arithmetic on pointer to void
5061 ComplainAboutVoid = true;
5062 } else if (lpointee->isFunctionType()) {
5063 if (getLangOptions().CPlusPlus) {
5064 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005065 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005066 return QualType();
5067 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005068
5069 // GNU C extension: arithmetic on pointer to function
5070 ComplainAboutFunc = lex;
5071 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005072 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005073 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005074 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005075 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005076 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005077
Chris Lattner12bdebb2009-04-24 23:50:08 +00005078 // Diagnose bad cases where we step over interface counts.
5079 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5080 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5081 << lpointee << lex->getSourceRange();
5082 return QualType();
5083 }
Mike Stump11289f42009-09-09 15:08:12 +00005084
Chris Lattner4d62f422007-12-09 21:53:25 +00005085 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005086 if (rex->getType()->isIntegerType()) {
5087 if (ComplainAboutVoid)
5088 Diag(Loc, diag::ext_gnu_void_ptr)
5089 << lex->getSourceRange() << rex->getSourceRange();
5090 if (ComplainAboutFunc)
5091 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005092 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005093 << ComplainAboutFunc->getSourceRange();
5094
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005095 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005096 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005097 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005098
Chris Lattner4d62f422007-12-09 21:53:25 +00005099 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005100 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005101 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005102
Douglas Gregorac1fb652009-03-24 19:52:54 +00005103 // RHS must be a completely-type object type.
5104 // Handle the GNU void* extension.
5105 if (rpointee->isVoidType()) {
5106 if (getLangOptions().CPlusPlus) {
5107 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5108 << lex->getSourceRange() << rex->getSourceRange();
5109 return QualType();
5110 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005111
Douglas Gregorac1fb652009-03-24 19:52:54 +00005112 ComplainAboutVoid = true;
5113 } else if (rpointee->isFunctionType()) {
5114 if (getLangOptions().CPlusPlus) {
5115 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005116 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005117 return QualType();
5118 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005119
5120 // GNU extension: arithmetic on pointer to function
5121 if (!ComplainAboutFunc)
5122 ComplainAboutFunc = rex;
5123 } else if (!rpointee->isDependentType() &&
5124 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005125 PDiag(diag::err_typecheck_sub_ptr_object)
5126 << rex->getSourceRange()
5127 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005128 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005129
Eli Friedman168fe152009-05-16 13:54:38 +00005130 if (getLangOptions().CPlusPlus) {
5131 // Pointee types must be the same: C++ [expr.add]
5132 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5133 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5134 << lex->getType() << rex->getType()
5135 << lex->getSourceRange() << rex->getSourceRange();
5136 return QualType();
5137 }
5138 } else {
5139 // Pointee types must be compatible C99 6.5.6p3
5140 if (!Context.typesAreCompatible(
5141 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5142 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5143 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5144 << lex->getType() << rex->getType()
5145 << lex->getSourceRange() << rex->getSourceRange();
5146 return QualType();
5147 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005148 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005149
Douglas Gregorac1fb652009-03-24 19:52:54 +00005150 if (ComplainAboutVoid)
5151 Diag(Loc, diag::ext_gnu_void_ptr)
5152 << lex->getSourceRange() << rex->getSourceRange();
5153 if (ComplainAboutFunc)
5154 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005155 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005156 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005157
5158 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005159 return Context.getPointerDiffType();
5160 }
5161 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005162
Chris Lattner326f7572008-11-18 01:30:42 +00005163 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005164}
5165
Chris Lattner2a3569b2008-04-07 05:30:13 +00005166// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00005167QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00005168 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005169 // C99 6.5.7p2: Each of the operands shall have integer type.
5170 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00005171 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005172
Nate Begemane46ee9a2009-10-25 02:26:48 +00005173 // Vector shifts promote their scalar inputs to vector type.
5174 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5175 return CheckVectorOperands(Loc, lex, rex);
5176
Chris Lattner5c11c412007-12-12 05:47:28 +00005177 // Shifts don't perform usual arithmetic conversions, they just do integer
5178 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005179 QualType LHSTy = Context.isPromotableBitField(lex);
5180 if (LHSTy.isNull()) {
5181 LHSTy = lex->getType();
5182 if (LHSTy->isPromotableIntegerType())
5183 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005184 }
Chris Lattner3c133402007-12-13 07:28:16 +00005185 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005186 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005187
Chris Lattner5c11c412007-12-12 05:47:28 +00005188 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005189
Ryan Flynnf53fab82009-08-07 16:20:20 +00005190 // Sanity-check shift operands
5191 llvm::APSInt Right;
5192 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005193 if (!rex->isValueDependent() &&
5194 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005195 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005196 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5197 else {
5198 llvm::APInt LeftBits(Right.getBitWidth(),
5199 Context.getTypeSize(lex->getType()));
5200 if (Right.uge(LeftBits))
5201 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5202 }
5203 }
5204
Chris Lattner5c11c412007-12-12 05:47:28 +00005205 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005206 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005207}
5208
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005209// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005210QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005211 unsigned OpaqueOpc, bool isRelational) {
5212 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5213
Chris Lattner9a152e22009-12-05 05:40:13 +00005214 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005215 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005216 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005217
John McCall99ce6bf2009-11-06 08:49:08 +00005218 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5219 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005220
Chris Lattnerb620c342007-08-26 01:18:55 +00005221 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005222 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5223 UsualArithmeticConversions(lex, rex);
5224 else {
5225 UsualUnaryConversions(lex);
5226 UsualUnaryConversions(rex);
5227 }
Steve Naroff31090012007-07-16 21:54:35 +00005228 QualType lType = lex->getType();
5229 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005230
Mike Stumpf70bcf72009-05-07 18:43:07 +00005231 if (!lType->isFloatingType()
5232 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005233 // For non-floating point types, check for self-comparisons of the form
5234 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5235 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005236 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005237 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005238 Expr *LHSStripped = lex->IgnoreParens();
5239 Expr *RHSStripped = rex->IgnoreParens();
5240 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5241 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005242 if (DRL->getDecl() == DRR->getDecl() &&
5243 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregor49862b82010-01-12 23:18:54 +00005244 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump11289f42009-09-09 15:08:12 +00005245
Chris Lattner222b8bd2009-03-08 19:39:53 +00005246 if (isa<CastExpr>(LHSStripped))
5247 LHSStripped = LHSStripped->IgnoreParenCasts();
5248 if (isa<CastExpr>(RHSStripped))
5249 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005250
Chris Lattner222b8bd2009-03-08 19:39:53 +00005251 // Warn about comparisons against a string constant (unless the other
5252 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005253 Expr *literalString = 0;
5254 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005255 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005256 !RHSStripped->isNullPointerConstant(Context,
5257 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005258 literalString = lex;
5259 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005260 } else if ((isa<StringLiteral>(RHSStripped) ||
5261 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005262 !LHSStripped->isNullPointerConstant(Context,
5263 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005264 literalString = rex;
5265 literalStringStripped = RHSStripped;
5266 }
5267
5268 if (literalString) {
5269 std::string resultComparison;
5270 switch (Opc) {
5271 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5272 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5273 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5274 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5275 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5276 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5277 default: assert(false && "Invalid comparison operator");
5278 }
Douglas Gregor49862b82010-01-12 23:18:54 +00005279
5280 DiagRuntimeBehavior(Loc,
5281 PDiag(diag::warn_stringcompare)
5282 << isa<ObjCEncodeExpr>(literalStringStripped)
5283 << literalString->getSourceRange()
5284 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5285 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5286 "strcmp(")
5287 << CodeModificationHint::CreateInsertion(
5288 PP.getLocForEndOfToken(rex->getLocEnd()),
5289 resultComparison));
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005290 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005291 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005292
Douglas Gregorca63811b2008-11-19 03:25:36 +00005293 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005294 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005295
Chris Lattnerb620c342007-08-26 01:18:55 +00005296 if (isRelational) {
5297 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005298 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005299 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005300 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005301 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005302 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005303
Chris Lattnerb620c342007-08-26 01:18:55 +00005304 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005305 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005306 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005307
Douglas Gregor56751b52009-09-25 04:25:58 +00005308 bool LHSIsNull = lex->isNullPointerConstant(Context,
5309 Expr::NPC_ValueDependentIsNull);
5310 bool RHSIsNull = rex->isNullPointerConstant(Context,
5311 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005312
Chris Lattnerb620c342007-08-26 01:18:55 +00005313 // All of the following pointer related warnings are GCC extensions, except
5314 // when handling null pointer constants. One day, we can consider making them
5315 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005316 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005317 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005318 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005319 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005320 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005321
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005322 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005323 if (LCanPointeeTy == RCanPointeeTy)
5324 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005325 if (!isRelational &&
5326 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5327 // Valid unless comparison between non-null pointer and function pointer
5328 // This is a gcc extension compatibility comparison.
5329 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5330 && !LHSIsNull && !RHSIsNull) {
5331 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5332 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5333 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5334 return ResultTy;
5335 }
5336 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005337 // C++ [expr.rel]p2:
5338 // [...] Pointer conversions (4.10) and qualification
5339 // conversions (4.4) are performed on pointer operands (or on
5340 // a pointer operand and a null pointer constant) to bring
5341 // them to their composite pointer type. [...]
5342 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005343 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005344 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005345 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005346 if (T.isNull()) {
5347 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5348 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5349 return QualType();
5350 }
5351
Eli Friedman06ed2a52009-10-20 08:27:19 +00005352 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5353 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005354 return ResultTy;
5355 }
Eli Friedman16c209612009-08-23 00:27:47 +00005356 // C99 6.5.9p2 and C99 6.5.8p2
5357 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5358 RCanPointeeTy.getUnqualifiedType())) {
5359 // Valid unless a relational comparison of function pointers
5360 if (isRelational && LCanPointeeTy->isFunctionType()) {
5361 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5362 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5363 }
5364 } else if (!isRelational &&
5365 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5366 // Valid unless comparison between non-null pointer and function pointer
5367 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5368 && !LHSIsNull && !RHSIsNull) {
5369 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5370 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5371 }
5372 } else {
5373 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005374 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005375 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005376 }
Eli Friedman16c209612009-08-23 00:27:47 +00005377 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005378 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005379 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005380 }
Mike Stump11289f42009-09-09 15:08:12 +00005381
Sebastian Redl576fd422009-05-10 18:38:11 +00005382 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005383 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005384 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005385 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005386 (lType->isPointerType() ||
5387 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005388 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005389 return ResultTy;
5390 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005391 if (LHSIsNull &&
5392 (rType->isPointerType() ||
5393 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005394 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005395 return ResultTy;
5396 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005397
5398 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005399 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005400 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5401 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005402 // In addition, pointers to members can be compared, or a pointer to
5403 // member and a null pointer constant. Pointer to member conversions
5404 // (4.11) and qualification conversions (4.4) are performed to bring
5405 // them to a common type. If one operand is a null pointer constant,
5406 // the common type is the type of the other operand. Otherwise, the
5407 // common type is a pointer to member type similar (4.4) to the type
5408 // of one of the operands, with a cv-qualification signature (4.4)
5409 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005410 // types.
5411 QualType T = FindCompositePointerType(lex, rex);
5412 if (T.isNull()) {
5413 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5414 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5415 return QualType();
5416 }
Mike Stump11289f42009-09-09 15:08:12 +00005417
Eli Friedman06ed2a52009-10-20 08:27:19 +00005418 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5419 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005420 return ResultTy;
5421 }
Mike Stump11289f42009-09-09 15:08:12 +00005422
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005423 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005424 if (lType->isNullPtrType() && rType->isNullPtrType())
5425 return ResultTy;
5426 }
Mike Stump11289f42009-09-09 15:08:12 +00005427
Steve Naroff081c7422008-09-04 15:10:53 +00005428 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005429 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005430 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5431 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005432
Steve Naroff081c7422008-09-04 15:10:53 +00005433 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005434 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005435 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005436 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005437 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005438 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005439 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005440 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005441 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005442 if (!isRelational
5443 && ((lType->isBlockPointerType() && rType->isPointerType())
5444 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005445 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005446 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005447 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005448 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005449 ->getPointeeType()->isVoidType())))
5450 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5451 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005452 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005453 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005454 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005455 }
Steve Naroff081c7422008-09-04 15:10:53 +00005456
Steve Naroff7cae42b2009-07-10 23:34:53 +00005457 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005458 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005459 const PointerType *LPT = lType->getAs<PointerType>();
5460 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005461 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005462 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005463 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005464 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005465
Steve Naroff753567f2008-11-17 19:49:16 +00005466 if (!LPtrToVoid && !RPtrToVoid &&
5467 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005468 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005469 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005470 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005471 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005472 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005473 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005474 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005475 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005476 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5477 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005478 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005479 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005480 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005481 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005482 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005483 unsigned DiagID = 0;
5484 if (RHSIsNull) {
5485 if (isRelational)
5486 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5487 } else if (isRelational)
5488 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5489 else
5490 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005491
Chris Lattnerd99bd522009-08-23 00:03:44 +00005492 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005493 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005494 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005495 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005496 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005497 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005498 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005499 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005500 unsigned DiagID = 0;
5501 if (LHSIsNull) {
5502 if (isRelational)
5503 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5504 } else if (isRelational)
5505 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5506 else
5507 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005508
Chris Lattnerd99bd522009-08-23 00:03:44 +00005509 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005510 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005511 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005512 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005513 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005514 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005515 }
Steve Naroff4b191572008-09-04 16:56:14 +00005516 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005517 if (!isRelational && RHSIsNull
5518 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005519 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005520 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005521 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005522 if (!isRelational && LHSIsNull
5523 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005524 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005525 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005526 }
Chris Lattner326f7572008-11-18 01:30:42 +00005527 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005528}
5529
Nate Begeman191a6b12008-07-14 18:02:46 +00005530/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005531/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005532/// like a scalar comparison, a vector comparison produces a vector of integer
5533/// types.
5534QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005535 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005536 bool isRelational) {
5537 // Check to make sure we're operating on vectors of the same type and width,
5538 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005539 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005540 if (vType.isNull())
5541 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005542
Nate Begeman191a6b12008-07-14 18:02:46 +00005543 QualType lType = lex->getType();
5544 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005545
Nate Begeman191a6b12008-07-14 18:02:46 +00005546 // For non-floating point types, check for self-comparisons of the form
5547 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5548 // often indicate logic errors in the program.
5549 if (!lType->isFloatingType()) {
5550 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5551 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5552 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregor49862b82010-01-12 23:18:54 +00005553 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begeman191a6b12008-07-14 18:02:46 +00005554 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005555
Nate Begeman191a6b12008-07-14 18:02:46 +00005556 // Check for comparisons of floating point operands using != and ==.
5557 if (!isRelational && lType->isFloatingType()) {
5558 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005559 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005560 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005561
Nate Begeman191a6b12008-07-14 18:02:46 +00005562 // Return the type for the comparison, which is the same as vector type for
5563 // integer vectors, or an integer type of identical size and number of
5564 // elements for floating point vectors.
5565 if (lType->isIntegerType())
5566 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005567
John McCall9dd450b2009-09-21 23:43:11 +00005568 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005569 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005570 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005571 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005572 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005573 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5574
Mike Stump4e1f26a2009-02-19 03:04:26 +00005575 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005576 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005577 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5578}
5579
Steve Naroff218bc2b2007-05-04 21:54:46 +00005580inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005581 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005582 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005583 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005584
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005585 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005586
Steve Naroffdbd9e892007-07-17 00:58:39 +00005587 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005588 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005589 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005590}
5591
Steve Naroff218bc2b2007-05-04 21:54:46 +00005592inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005593 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005594 if (!Context.getLangOptions().CPlusPlus) {
5595 UsualUnaryConversions(lex);
5596 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005597
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005598 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5599 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005600
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005601 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005602 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005603
5604 // C++ [expr.log.and]p1
5605 // C++ [expr.log.or]p1
5606 // The operands are both implicitly converted to type bool (clause 4).
5607 StandardConversionSequence LHS;
5608 if (!IsStandardConversion(lex, Context.BoolTy,
5609 /*InOverloadResolution=*/false, LHS))
5610 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005611
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005612 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005613 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005614 return InvalidOperands(Loc, lex, rex);
5615
5616 StandardConversionSequence RHS;
5617 if (!IsStandardConversion(rex, Context.BoolTy,
5618 /*InOverloadResolution=*/false, RHS))
5619 return InvalidOperands(Loc, lex, rex);
5620
5621 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005622 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005623 return InvalidOperands(Loc, lex, rex);
5624
5625 // C++ [expr.log.and]p2
5626 // C++ [expr.log.or]p2
5627 // The result is a bool.
5628 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005629}
5630
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005631/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5632/// is a read-only property; return true if so. A readonly property expression
5633/// depends on various declarations and thus must be treated specially.
5634///
Mike Stump11289f42009-09-09 15:08:12 +00005635static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005636 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5637 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5638 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5639 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005640 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005641 BaseType->getAsObjCInterfacePointerType())
5642 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5643 if (S.isPropertyReadonly(PDecl, IFace))
5644 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005645 }
5646 }
5647 return false;
5648}
5649
Chris Lattner30bd3272008-11-18 01:22:49 +00005650/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5651/// emit an error and return true. If so, return false.
5652static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005653 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005654 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005655 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005656 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5657 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005658 if (IsLV == Expr::MLV_Valid)
5659 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005660
Chris Lattner30bd3272008-11-18 01:22:49 +00005661 unsigned Diag = 0;
5662 bool NeedType = false;
5663 switch (IsLV) { // C99 6.5.16p2
5664 default: assert(0 && "Unknown result from isModifiableLvalue!");
5665 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005666 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005667 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5668 NeedType = true;
5669 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005670 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005671 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5672 NeedType = true;
5673 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005674 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005675 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5676 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005677 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005678 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5679 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005680 case Expr::MLV_IncompleteType:
5681 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005682 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005683 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5684 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005685 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005686 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5687 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005688 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005689 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5690 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005691 case Expr::MLV_ReadonlyProperty:
5692 Diag = diag::error_readonly_property_assignment;
5693 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005694 case Expr::MLV_NoSetterProperty:
5695 Diag = diag::error_nosetter_property_assignment;
5696 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00005697 case Expr::MLV_SubObjCPropertySetting:
5698 Diag = diag::error_no_subobject_property_setting;
5699 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005700 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005701
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005702 SourceRange Assign;
5703 if (Loc != OrigLoc)
5704 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005705 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005706 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005707 else
Mike Stump11289f42009-09-09 15:08:12 +00005708 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005709 return true;
5710}
5711
5712
5713
5714// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005715QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5716 SourceLocation Loc,
5717 QualType CompoundType) {
5718 // Verify that LHS is a modifiable lvalue, and emit error if not.
5719 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005720 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005721
5722 QualType LHSType = LHS->getType();
5723 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005724
Chris Lattner9bad62c2008-01-04 18:04:52 +00005725 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005726 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005727 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005728 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005729 // Special case of NSObject attributes on c-style pointer types.
5730 if (ConvTy == IncompatiblePointer &&
5731 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005732 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005733 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005734 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005735 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005736
Chris Lattnerea714382008-08-21 18:04:13 +00005737 // If the RHS is a unary plus or minus, check to see if they = and + are
5738 // right next to each other. If so, the user may have typo'd "x =+ 4"
5739 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005740 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005741 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5742 RHSCheck = ICE->getSubExpr();
5743 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5744 if ((UO->getOpcode() == UnaryOperator::Plus ||
5745 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005746 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005747 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005748 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5749 // And there is a space or other character before the subexpr of the
5750 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005751 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5752 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005753 Diag(Loc, diag::warn_not_compound_assign)
5754 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5755 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005756 }
Chris Lattnerea714382008-08-21 18:04:13 +00005757 }
5758 } else {
5759 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005760 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005761 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005762
Chris Lattner326f7572008-11-18 01:30:42 +00005763 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005764 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005765 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005766
Steve Naroff98cf3e92007-06-06 18:38:38 +00005767 // C99 6.5.16p3: The type of an assignment expression is the type of the
5768 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005769 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005770 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5771 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005772 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005773 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005774 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005775}
5776
Chris Lattner326f7572008-11-18 01:30:42 +00005777// C99 6.5.17
5778QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005779 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005780 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005781
5782 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5783 // incomplete in C++).
5784
Chris Lattner326f7572008-11-18 01:30:42 +00005785 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005786}
5787
Steve Naroff7a5af782007-07-13 16:58:59 +00005788/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5789/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005790QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5791 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005792 if (Op->isTypeDependent())
5793 return Context.DependentTy;
5794
Chris Lattner6b0cf142008-11-21 07:05:48 +00005795 QualType ResType = Op->getType();
5796 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005797
Sebastian Redle10c2c32008-12-20 09:35:34 +00005798 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5799 // Decrement of bool is not allowed.
5800 if (!isInc) {
5801 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5802 return QualType();
5803 }
5804 // Increment of bool sets it to true, but is deprecated.
5805 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5806 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005807 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005808 } else if (ResType->isAnyPointerType()) {
5809 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005810
Chris Lattner6b0cf142008-11-21 07:05:48 +00005811 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005812 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005813 if (getLangOptions().CPlusPlus) {
5814 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5815 << Op->getSourceRange();
5816 return QualType();
5817 }
5818
5819 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005820 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005821 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005822 if (getLangOptions().CPlusPlus) {
5823 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5824 << Op->getType() << Op->getSourceRange();
5825 return QualType();
5826 }
5827
5828 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005829 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005830 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005831 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005832 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005833 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005834 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005835 // Diagnose bad cases where we step over interface counts.
5836 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5837 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5838 << PointeeTy << Op->getSourceRange();
5839 return QualType();
5840 }
Eli Friedman090addd2010-01-03 00:20:48 +00005841 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005842 // C99 does not support ++/-- on complex types, we allow as an extension.
5843 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005844 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005845 } else {
5846 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00005847 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005848 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005849 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005850 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005851 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005852 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005853 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005854 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005855}
5856
Anders Carlsson806700f2008-02-01 07:15:58 +00005857/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005858/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005859/// where the declaration is needed for type checking. We only need to
5860/// handle cases when the expression references a function designator
5861/// or is an lvalue. Here are some examples:
5862/// - &(x) => x
5863/// - &*****f => f for f a function designator.
5864/// - &s.xx => s
5865/// - &s.zz[1].yy -> s, if zz is an array
5866/// - *(x + 1) -> x, if x is an array
5867/// - &"123"[2] -> 0
5868/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005869static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005870 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005871 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005872 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005873 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005874 // If this is an arrow operator, the address is an offset from
5875 // the base's value, so the object the base refers to is
5876 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005877 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005878 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005879 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005880 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005881 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005882 // FIXME: This code shouldn't be necessary! We should catch the implicit
5883 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005884 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5885 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5886 if (ICE->getSubExpr()->getType()->isArrayType())
5887 return getPrimaryDecl(ICE->getSubExpr());
5888 }
5889 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005890 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005891 case Stmt::UnaryOperatorClass: {
5892 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005893
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005894 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005895 case UnaryOperator::Real:
5896 case UnaryOperator::Imag:
5897 case UnaryOperator::Extension:
5898 return getPrimaryDecl(UO->getSubExpr());
5899 default:
5900 return 0;
5901 }
5902 }
Steve Naroff47500512007-04-19 23:00:49 +00005903 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005904 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005905 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005906 // If the result of an implicit cast is an l-value, we care about
5907 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005908 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005909 default:
5910 return 0;
5911 }
5912}
5913
5914/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005915/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005916/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005917/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005918/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005919/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005920/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005921QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005922 // Make sure to ignore parentheses in subsequent checks
5923 op = op->IgnoreParens();
5924
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005925 if (op->isTypeDependent())
5926 return Context.DependentTy;
5927
Steve Naroff826e91a2008-01-13 17:10:08 +00005928 if (getLangOptions().C99) {
5929 // Implement C99-only parts of addressof rules.
5930 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5931 if (uOp->getOpcode() == UnaryOperator::Deref)
5932 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5933 // (assuming the deref expression is valid).
5934 return uOp->getSubExpr()->getType();
5935 }
5936 // Technically, there should be a check for array subscript
5937 // expressions here, but the result of one is always an lvalue anyway.
5938 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005939 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005940 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005941
Sebastian Redl9a8dd0d2010-01-11 15:56:56 +00005942 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5943 if (lval == Expr::LV_MemberFunction && ME &&
5944 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5945 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5946 // &f where f is a member of the current object, or &o.f, or &p->f
5947 // All these are not allowed, and we need to catch them before the dcl
5948 // branch of the if, below.
5949 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5950 << dcl;
5951 // FIXME: Improve this diagnostic and provide a fixit.
5952
5953 // Now recover by acting as if the function had been accessed qualified.
5954 return Context.getMemberPointerType(op->getType(),
5955 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5956 .getTypePtr());
5957 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00005958 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005959 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005960 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005961 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005962 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5963 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005964 return QualType();
5965 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005966 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005967 // The operand cannot be a bit-field
5968 Diag(OpLoc, diag::err_typecheck_address_of)
5969 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005970 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005971 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5972 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005973 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005974 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005975 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005976 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005977 } else if (isa<ObjCPropertyRefExpr>(op)) {
5978 // cannot take address of a property expression.
5979 Diag(OpLoc, diag::err_typecheck_address_of)
5980 << "property expression" << op->getSourceRange();
5981 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005982 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5983 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005984 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5985 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005986 } else if (isa<UnresolvedLookupExpr>(op)) {
5987 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005988 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005989 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005990 // with the register storage-class specifier.
5991 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005992 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005993 Diag(OpLoc, diag::err_typecheck_address_of)
5994 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005995 return QualType();
5996 }
John McCalld14a8642009-11-21 08:51:07 +00005997 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005998 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005999 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00006000 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006001 // Could be a pointer to member, though, if there is an explicit
6002 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006003 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006004 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00006005 if (Ctx && Ctx->isRecord()) {
6006 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006007 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00006008 diag::err_cannot_form_pointer_to_member_of_reference_type)
6009 << FD->getDeclName() << FD->getType();
6010 return QualType();
6011 }
Mike Stump11289f42009-09-09 15:08:12 +00006012
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006013 return Context.getMemberPointerType(op->getType(),
6014 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00006015 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006016 }
Anders Carlsson5b535762009-05-16 21:43:42 +00006017 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00006018 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006019 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006020 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6021 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00006022 return Context.getMemberPointerType(op->getType(),
6023 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6024 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00006025 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00006026 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006027
Eli Friedmance7f9002009-05-16 23:27:50 +00006028 if (lval == Expr::LV_IncompleteVoidType) {
6029 // Taking the address of a void variable is technically illegal, but we
6030 // allow it in cases which are otherwise valid.
6031 // Example: "extern void x; void* y = &x;".
6032 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6033 }
6034
Steve Naroff47500512007-04-19 23:00:49 +00006035 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00006036 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00006037}
6038
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006039QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006040 if (Op->isTypeDependent())
6041 return Context.DependentTy;
6042
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006043 UsualUnaryConversions(Op);
6044 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006045
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006046 // Note that per both C89 and C99, this is always legal, even if ptype is an
6047 // incomplete type or void. It would be possible to warn about dereferencing
6048 // a void pointer, but it's completely well-defined, and such a warning is
6049 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006050 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00006051 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006052
John McCall9dd450b2009-09-21 23:43:11 +00006053 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00006054 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006055
Chris Lattner29e812b2008-11-20 06:06:08 +00006056 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006057 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006058 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00006059}
Steve Naroff218bc2b2007-05-04 21:54:46 +00006060
6061static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6062 tok::TokenKind Kind) {
6063 BinaryOperator::Opcode Opc;
6064 switch (Kind) {
6065 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00006066 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6067 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006068 case tok::star: Opc = BinaryOperator::Mul; break;
6069 case tok::slash: Opc = BinaryOperator::Div; break;
6070 case tok::percent: Opc = BinaryOperator::Rem; break;
6071 case tok::plus: Opc = BinaryOperator::Add; break;
6072 case tok::minus: Opc = BinaryOperator::Sub; break;
6073 case tok::lessless: Opc = BinaryOperator::Shl; break;
6074 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6075 case tok::lessequal: Opc = BinaryOperator::LE; break;
6076 case tok::less: Opc = BinaryOperator::LT; break;
6077 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6078 case tok::greater: Opc = BinaryOperator::GT; break;
6079 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6080 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6081 case tok::amp: Opc = BinaryOperator::And; break;
6082 case tok::caret: Opc = BinaryOperator::Xor; break;
6083 case tok::pipe: Opc = BinaryOperator::Or; break;
6084 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6085 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6086 case tok::equal: Opc = BinaryOperator::Assign; break;
6087 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6088 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6089 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6090 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6091 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6092 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6093 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6094 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6095 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6096 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6097 case tok::comma: Opc = BinaryOperator::Comma; break;
6098 }
6099 return Opc;
6100}
6101
Steve Naroff35d85152007-05-07 00:24:15 +00006102static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6103 tok::TokenKind Kind) {
6104 UnaryOperator::Opcode Opc;
6105 switch (Kind) {
6106 default: assert(0 && "Unknown unary op!");
6107 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6108 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6109 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6110 case tok::star: Opc = UnaryOperator::Deref; break;
6111 case tok::plus: Opc = UnaryOperator::Plus; break;
6112 case tok::minus: Opc = UnaryOperator::Minus; break;
6113 case tok::tilde: Opc = UnaryOperator::Not; break;
6114 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006115 case tok::kw___real: Opc = UnaryOperator::Real; break;
6116 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00006117 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006118 }
6119 return Opc;
6120}
6121
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006122/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6123/// operator @p Opc at location @c TokLoc. This routine only supports
6124/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006125Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6126 unsigned Op,
6127 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006128 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006129 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006130 // The following two variables are used for compound assignment operators
6131 QualType CompLHSTy; // Type of LHS after promotions for computation
6132 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006133
6134 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006135 case BinaryOperator::Assign:
6136 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6137 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006138 case BinaryOperator::PtrMemD:
6139 case BinaryOperator::PtrMemI:
6140 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6141 Opc == BinaryOperator::PtrMemI);
6142 break;
6143 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006144 case BinaryOperator::Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006145 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6146 Opc == BinaryOperator::Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006147 break;
6148 case BinaryOperator::Rem:
6149 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6150 break;
6151 case BinaryOperator::Add:
6152 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6153 break;
6154 case BinaryOperator::Sub:
6155 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6156 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006157 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006158 case BinaryOperator::Shr:
6159 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6160 break;
6161 case BinaryOperator::LE:
6162 case BinaryOperator::LT:
6163 case BinaryOperator::GE:
6164 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006165 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006166 break;
6167 case BinaryOperator::EQ:
6168 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006169 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006170 break;
6171 case BinaryOperator::And:
6172 case BinaryOperator::Xor:
6173 case BinaryOperator::Or:
6174 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6175 break;
6176 case BinaryOperator::LAnd:
6177 case BinaryOperator::LOr:
6178 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6179 break;
6180 case BinaryOperator::MulAssign:
6181 case BinaryOperator::DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006182 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6183 Opc == BinaryOperator::DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006184 CompLHSTy = CompResultTy;
6185 if (!CompResultTy.isNull())
6186 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006187 break;
6188 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006189 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6190 CompLHSTy = CompResultTy;
6191 if (!CompResultTy.isNull())
6192 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006193 break;
6194 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006195 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6196 if (!CompResultTy.isNull())
6197 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006198 break;
6199 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006200 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6201 if (!CompResultTy.isNull())
6202 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006203 break;
6204 case BinaryOperator::ShlAssign:
6205 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006206 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6207 CompLHSTy = CompResultTy;
6208 if (!CompResultTy.isNull())
6209 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006210 break;
6211 case BinaryOperator::AndAssign:
6212 case BinaryOperator::XorAssign:
6213 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006214 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6215 CompLHSTy = CompResultTy;
6216 if (!CompResultTy.isNull())
6217 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006218 break;
6219 case BinaryOperator::Comma:
6220 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6221 break;
6222 }
6223 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006224 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006225 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006226 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6227 else
6228 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006229 CompLHSTy, CompResultTy,
6230 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006231}
6232
Sebastian Redl44615072009-10-27 12:10:02 +00006233/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6234/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006235static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6236 const PartialDiagnostic &PD,
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006237 SourceRange ParenRange,
6238 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6239 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006240 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6241 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6242 // We can't display the parentheses, so just dig the
6243 // warning/error and return.
6244 Self.Diag(Loc, PD);
6245 return;
6246 }
6247
6248 Self.Diag(Loc, PD)
6249 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6250 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006251
6252 if (!SecondPD.getDiagID())
6253 return;
6254
6255 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6256 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6257 // We can't display the parentheses, so just dig the
6258 // warning/error and return.
6259 Self.Diag(Loc, SecondPD);
6260 return;
6261 }
6262
6263 Self.Diag(Loc, SecondPD)
6264 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6265 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006266}
6267
Sebastian Redl44615072009-10-27 12:10:02 +00006268/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6269/// operators are mixed in a way that suggests that the programmer forgot that
6270/// comparison operators have higher precedence. The most typical example of
6271/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006272static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6273 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006274 typedef BinaryOperator BinOp;
6275 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6276 rhsopc = static_cast<BinOp::Opcode>(-1);
6277 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006278 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006279 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006280 rhsopc = BO->getOpcode();
6281
6282 // Subs are not binary operators.
6283 if (lhsopc == -1 && rhsopc == -1)
6284 return;
6285
6286 // Bitwise operations are sometimes used as eager logical ops.
6287 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006288 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6289 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006290 return;
6291
Sebastian Redl44615072009-10-27 12:10:02 +00006292 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006293 SuggestParentheses(Self, OpLoc,
6294 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006295 << SourceRange(lhs->getLocStart(), OpLoc)
6296 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006297 lhs->getSourceRange(),
6298 PDiag(diag::note_precedence_bitwise_first)
6299 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006300 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6301 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006302 SuggestParentheses(Self, OpLoc,
6303 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006304 << SourceRange(OpLoc, rhs->getLocEnd())
6305 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006306 rhs->getSourceRange(),
6307 PDiag(diag::note_precedence_bitwise_first)
6308 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006309 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006310}
6311
6312/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6313/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6314/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6315static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6316 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006317 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006318 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6319}
6320
Steve Naroff218bc2b2007-05-04 21:54:46 +00006321// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006322Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6323 tok::TokenKind Kind,
6324 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006325 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006326 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006327
Steve Naroff83895f72007-09-16 03:34:24 +00006328 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6329 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006330
Sebastian Redl43028242009-10-26 15:24:15 +00006331 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6332 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6333
Douglas Gregor5287f092009-11-05 00:51:44 +00006334 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6335}
6336
6337Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6338 BinaryOperator::Opcode Opc,
6339 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006340 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006341 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006342 rhs->getType()->isOverloadableType())) {
6343 // Find all of the overloaded operators visible from this
6344 // point. We perform both an operator-name lookup from the local
6345 // scope and an argument-dependent lookup based on the types of
6346 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006347 UnresolvedSet<16> Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006348 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006349 if (S && OverOp != OO_None)
6350 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6351 Functions);
Douglas Gregor5287f092009-11-05 00:51:44 +00006352
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006353 // Build the (potentially-overloaded, potentially-dependent)
6354 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006355 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006356 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006357
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006358 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006359 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006360}
6361
Douglas Gregor084d8552009-03-13 23:49:33 +00006362Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006363 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006364 ExprArg InputArg) {
6365 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006366
Mike Stump87c57ac2009-05-16 07:39:55 +00006367 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006368 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006369 QualType resultType;
6370 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006371 case UnaryOperator::OffsetOf:
6372 assert(false && "Invalid unary operator");
6373 break;
6374
Steve Naroff35d85152007-05-07 00:24:15 +00006375 case UnaryOperator::PreInc:
6376 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006377 case UnaryOperator::PostInc:
6378 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006379 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006380 Opc == UnaryOperator::PreInc ||
6381 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006382 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006383 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006384 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006385 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006386 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00006387 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006388 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006389 break;
6390 case UnaryOperator::Plus:
6391 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006392 UsualUnaryConversions(Input);
6393 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006394 if (resultType->isDependentType())
6395 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006396 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6397 break;
6398 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6399 resultType->isEnumeralType())
6400 break;
6401 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6402 Opc == UnaryOperator::Plus &&
6403 resultType->isPointerType())
6404 break;
6405
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006406 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6407 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006408 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006409 UsualUnaryConversions(Input);
6410 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006411 if (resultType->isDependentType())
6412 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006413 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6414 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6415 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006416 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006417 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006418 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006419 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6420 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006421 break;
6422 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006423 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00006424 DefaultFunctionArrayConversion(Input);
6425 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006426 if (resultType->isDependentType())
6427 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006428 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006429 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6430 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006431 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006432 // In C++, it's bool. C++ 5.3.1p8
6433 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006434 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006435 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006436 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006437 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006438 break;
Chris Lattner86554282007-06-08 22:32:33 +00006439 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006440 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006441 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006442 }
6443 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006444 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006445
6446 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006447 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006448}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006449
Douglas Gregor5287f092009-11-05 00:51:44 +00006450Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6451 UnaryOperator::Opcode Opc,
6452 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006453 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006454 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6455 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006456 // Find all of the overloaded operators visible from this
6457 // point. We perform both an operator-name lookup from the local
6458 // scope and an argument-dependent lookup based on the types of
6459 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006460 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00006461 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006462 if (S && OverOp != OO_None)
6463 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6464 Functions);
Douglas Gregor5287f092009-11-05 00:51:44 +00006465
Douglas Gregor084d8552009-03-13 23:49:33 +00006466 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6467 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006468
Douglas Gregor084d8552009-03-13 23:49:33 +00006469 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6470}
6471
Douglas Gregor5287f092009-11-05 00:51:44 +00006472// Unary Operators. 'Tok' is the token for the operator.
6473Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6474 tok::TokenKind Op, ExprArg input) {
6475 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6476}
6477
Steve Naroff66356bd2007-09-16 14:56:35 +00006478/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006479Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6480 SourceLocation LabLoc,
6481 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006482 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006483 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006484
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006485 // If we haven't seen this label yet, create a forward reference. It
6486 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006487 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006488 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006489
Chris Lattnereefa10e2007-05-28 06:56:27 +00006490 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006491 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6492 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006493}
6494
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006495Sema::OwningExprResult
6496Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6497 SourceLocation RPLoc) { // "({..})"
6498 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006499 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6500 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6501
Eli Friedman52cc0162009-01-24 23:09:00 +00006502 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006503 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006504 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006505
Chris Lattner366727f2007-07-24 16:58:17 +00006506 // FIXME: there are a variety of strange constraints to enforce here, for
6507 // example, it is not possible to goto into a stmt expression apparently.
6508 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006509
Chris Lattner366727f2007-07-24 16:58:17 +00006510 // If there are sub stmts in the compound stmt, take the type of the last one
6511 // as the type of the stmtexpr.
6512 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006513
Chris Lattner944d3062008-07-26 19:51:01 +00006514 if (!Compound->body_empty()) {
6515 Stmt *LastStmt = Compound->body_back();
6516 // If LastStmt is a label, skip down through into the body.
6517 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6518 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006519
Chris Lattner944d3062008-07-26 19:51:01 +00006520 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006521 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006522 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006523
Eli Friedmanba961a92009-03-23 00:24:07 +00006524 // FIXME: Check that expression type is complete/non-abstract; statement
6525 // expressions are not lvalues.
6526
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006527 substmt.release();
6528 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006529}
Steve Naroff78864672007-08-01 22:05:33 +00006530
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006531Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6532 SourceLocation BuiltinLoc,
6533 SourceLocation TypeLoc,
6534 TypeTy *argty,
6535 OffsetOfComponent *CompPtr,
6536 unsigned NumComponents,
6537 SourceLocation RPLoc) {
6538 // FIXME: This function leaks all expressions in the offset components on
6539 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006540 // FIXME: Preserve type source info.
6541 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006542 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006543
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006544 bool Dependent = ArgTy->isDependentType();
6545
Chris Lattnerf17bd422007-08-30 17:45:32 +00006546 // We must have at least one component that refers to the type, and the first
6547 // one is known to be a field designator. Verify that the ArgTy represents
6548 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006549 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006550 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006551
Eli Friedmanba961a92009-03-23 00:24:07 +00006552 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6553 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006554
Eli Friedman988a16b2009-02-27 06:44:11 +00006555 // Otherwise, create a null pointer as the base, and iteratively process
6556 // the offsetof designators.
6557 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6558 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006559 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006560 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006561
Chris Lattner78502cf2007-08-31 21:49:13 +00006562 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6563 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006564 // FIXME: This diagnostic isn't actually visible because the location is in
6565 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006566 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006567 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6568 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006569
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006570 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006571 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006572
John McCall9eff4e62009-11-04 03:03:43 +00006573 if (RequireCompleteType(TypeLoc, Res->getType(),
6574 diag::err_offsetof_incomplete_type))
6575 return ExprError();
6576
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006577 // FIXME: Dependent case loses a lot of information here. And probably
6578 // leaks like a sieve.
6579 for (unsigned i = 0; i != NumComponents; ++i) {
6580 const OffsetOfComponent &OC = CompPtr[i];
6581 if (OC.isBrackets) {
6582 // Offset of an array sub-field. TODO: Should we allow vector elements?
6583 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6584 if (!AT) {
6585 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006586 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6587 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006588 }
6589
6590 // FIXME: C++: Verify that operator[] isn't overloaded.
6591
Eli Friedman988a16b2009-02-27 06:44:11 +00006592 // Promote the array so it looks more like a normal array subscript
6593 // expression.
6594 DefaultFunctionArrayConversion(Res);
6595
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006596 // C99 6.5.2.1p1
6597 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006598 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006599 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006600 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006601 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006602 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006603
6604 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6605 OC.LocEnd);
6606 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006607 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006608
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006609 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006610 if (!RC) {
6611 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006612 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6613 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006614 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006615
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006616 // Get the decl corresponding to this.
6617 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006618 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00006619 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6620 DiagRuntimeBehavior(BuiltinLoc,
6621 PDiag(diag::warn_offsetof_non_pod_type)
6622 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6623 << Res->getType()))
6624 DidWarnAboutNonPOD = true;
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006625 }
Mike Stump11289f42009-09-09 15:08:12 +00006626
John McCall27b18f82009-11-17 02:14:36 +00006627 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6628 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006629
John McCall67c00872009-12-02 08:25:40 +00006630 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006631 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006632 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006633 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6634 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006635
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006636 // FIXME: C++: Verify that MemberDecl isn't a static field.
6637 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006638 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006639 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006640 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006641 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006642 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006643 // MemberDecl->getType() doesn't get the right qualifiers, but it
6644 // doesn't matter here.
6645 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6646 MemberDecl->getType().getNonReferenceType());
6647 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006648 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006649 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006650
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006651 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6652 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006653}
6654
6655
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006656Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6657 TypeTy *arg1,TypeTy *arg2,
6658 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006659 // FIXME: Preserve type source info.
6660 QualType argT1 = GetTypeFromParser(arg1);
6661 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006662
Steve Naroff78864672007-08-01 22:05:33 +00006663 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006664
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006665 if (getLangOptions().CPlusPlus) {
6666 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6667 << SourceRange(BuiltinLoc, RPLoc);
6668 return ExprError();
6669 }
6670
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006671 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6672 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006673}
6674
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006675Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6676 ExprArg cond,
6677 ExprArg expr1, ExprArg expr2,
6678 SourceLocation RPLoc) {
6679 Expr *CondExpr = static_cast<Expr*>(cond.get());
6680 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6681 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006682
Steve Naroff9efdabc2007-08-03 21:21:27 +00006683 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6684
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006685 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006686 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006687 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006688 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006689 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006690 } else {
6691 // The conditional expression is required to be a constant expression.
6692 llvm::APSInt condEval(32);
6693 SourceLocation ExpLoc;
6694 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006695 return ExprError(Diag(ExpLoc,
6696 diag::err_typecheck_choose_expr_requires_constant)
6697 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006698
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006699 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6700 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006701 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6702 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006703 }
6704
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006705 cond.release(); expr1.release(); expr2.release();
6706 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006707 resType, RPLoc,
6708 resType->isDependentType(),
6709 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006710}
6711
Steve Naroffc540d662008-09-03 18:15:37 +00006712//===----------------------------------------------------------------------===//
6713// Clang Extensions.
6714//===----------------------------------------------------------------------===//
6715
6716/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006717void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006718 // Analyze block parameters.
6719 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006720
Steve Naroffc540d662008-09-03 18:15:37 +00006721 // Add BSI to CurBlock.
6722 BSI->PrevBlockInfo = CurBlock;
6723 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006724
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006725 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006726 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006727 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006728 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006729 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6730 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006731
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006732 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006733 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006734 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006735}
6736
Mike Stump82f071f2009-02-04 22:31:32 +00006737void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006738 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006739
6740 if (ParamInfo.getNumTypeObjects() == 0
6741 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006742 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006743 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6744
Mike Stumpd456c482009-04-28 01:10:27 +00006745 if (T->isArrayType()) {
6746 Diag(ParamInfo.getSourceRange().getBegin(),
6747 diag::err_block_returns_array);
6748 return;
6749 }
6750
Mike Stump82f071f2009-02-04 22:31:32 +00006751 // The parameter list is optional, if there was none, assume ().
6752 if (!T->isFunctionType())
6753 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6754
6755 CurBlock->hasPrototype = true;
6756 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006757 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006758 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006759 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006760 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006761 // FIXME: remove the attribute.
6762 }
John McCall9dd450b2009-09-21 23:43:11 +00006763 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006764
Chris Lattner6de05082009-04-11 19:27:54 +00006765 // Do not allow returning a objc interface by-value.
6766 if (RetTy->isObjCInterfaceType()) {
6767 Diag(ParamInfo.getSourceRange().getBegin(),
6768 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6769 return;
6770 }
Mike Stump82f071f2009-02-04 22:31:32 +00006771 return;
6772 }
6773
Steve Naroffc540d662008-09-03 18:15:37 +00006774 // Analyze arguments to block.
6775 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6776 "Not a function declarator!");
6777 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006778
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006779 CurBlock->hasPrototype = FTI.hasPrototype;
6780 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006781
Steve Naroffc540d662008-09-03 18:15:37 +00006782 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6783 // no arguments, not a function that takes a single void argument.
6784 if (FTI.hasPrototype &&
6785 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006786 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6787 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006788 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006789 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006790 } else if (FTI.hasPrototype) {
6791 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006792 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006793 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006794 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006795 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006796 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006797 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006798 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006799 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00006800 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
6801 (*AI)->setOwningFunction(CurBlock->TheDecl);
6802
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006803 // If this has an identifier, add it to the scope stack.
6804 if ((*AI)->getIdentifier())
6805 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCallf7b2fb52010-01-22 00:28:27 +00006806 }
Chris Lattner6de05082009-04-11 19:27:54 +00006807
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006808 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006809 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006810 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006811 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006812 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006813 // FIXME: remove the attribute.
6814 }
Mike Stump11289f42009-09-09 15:08:12 +00006815
Chris Lattner6de05082009-04-11 19:27:54 +00006816 // Analyze the return type.
6817 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006818 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006819
Chris Lattner6de05082009-04-11 19:27:54 +00006820 // Do not allow returning a objc interface by-value.
6821 if (RetTy->isObjCInterfaceType()) {
6822 Diag(ParamInfo.getSourceRange().getBegin(),
6823 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6824 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006825 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006826}
6827
6828/// ActOnBlockError - If there is an error parsing a block, this callback
6829/// is invoked to pop the information about the block from the action impl.
6830void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6831 // Ensure that CurBlock is deleted.
6832 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006833
Chris Lattner45542ea2009-04-19 05:28:12 +00006834 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6835
Steve Naroffc540d662008-09-03 18:15:37 +00006836 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006837 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006838 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006839 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006840}
6841
6842/// ActOnBlockStmtExpr - This is called when the body of a block statement
6843/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006844Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6845 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006846 // If blocks are disabled, emit an error.
6847 if (!LangOpts.Blocks)
6848 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006849
Steve Naroffc540d662008-09-03 18:15:37 +00006850 // Ensure that CurBlock is deleted.
6851 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006852
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006853 PopDeclContext();
6854
Steve Naroffc540d662008-09-03 18:15:37 +00006855 // Pop off CurBlock, handle nested blocks.
6856 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006857
Steve Naroffc540d662008-09-03 18:15:37 +00006858 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006859 if (!BSI->ReturnType.isNull())
6860 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006861
Steve Naroffc540d662008-09-03 18:15:37 +00006862 llvm::SmallVector<QualType, 8> ArgTypes;
6863 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6864 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006865
Mike Stump3bf1ab42009-07-28 22:04:01 +00006866 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006867 QualType BlockTy;
6868 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006869 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6870 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006871 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006872 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006873 BSI->isVariadic, 0, false, false, 0, 0,
6874 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006875
Eli Friedmanba961a92009-03-23 00:24:07 +00006876 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006877 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006878 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006879
Chris Lattner45542ea2009-04-19 05:28:12 +00006880 // If needed, diagnose invalid gotos and switches in the block.
6881 if (CurFunctionNeedsScopeChecking)
6882 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6883 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006884
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006885 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump314825b2010-01-19 23:08:01 +00006886
6887 bool Good = true;
6888 // Check goto/label use.
6889 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
6890 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
6891 LabelStmt *L = I->second;
6892
6893 // Verify that we have no forward references left. If so, there was a goto
6894 // or address of a label taken, but no definition of it.
6895 if (L->getSubStmt() != 0)
6896 continue;
6897
6898 // Emit error.
6899 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
6900 Good = false;
6901 }
6902 BSI->LabelMap.clear();
6903 if (!Good)
6904 return ExprError();
6905
Mike Stump1bacb812010-01-13 02:59:54 +00006906 AnalysisContext AC(BSI->TheDecl);
6907 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody(), AC);
6908 CheckUnreachable(AC);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006909 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6910 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006911}
6912
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006913Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6914 ExprArg expr, TypeTy *type,
6915 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006916 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006917 Expr *E = static_cast<Expr*>(expr.get());
6918 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006919
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006920 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006921
6922 // Get the va_list type
6923 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006924 if (VaListType->isArrayType()) {
6925 // Deal with implicit array decay; for example, on x86-64,
6926 // va_list is an array, but it's supposed to decay to
6927 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006928 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006929 // Make sure the input expression also decays appropriately.
6930 UsualUnaryConversions(E);
6931 } else {
6932 // Otherwise, the va_list argument must be an l-value because
6933 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006934 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006935 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006936 return ExprError();
6937 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006938
Douglas Gregorad3150c2009-05-19 23:10:31 +00006939 if (!E->isTypeDependent() &&
6940 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006941 return ExprError(Diag(E->getLocStart(),
6942 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006943 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006944 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006945
Eli Friedmanba961a92009-03-23 00:24:07 +00006946 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006947 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006948
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006949 expr.release();
6950 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6951 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006952}
6953
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006954Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006955 // The type of __null will be int or long, depending on the size of
6956 // pointers on the target.
6957 QualType Ty;
6958 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6959 Ty = Context.IntTy;
6960 else
6961 Ty = Context.LongTy;
6962
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006963 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006964}
6965
Anders Carlssonace5d072009-11-10 04:46:30 +00006966static void
6967MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6968 QualType DstType,
6969 Expr *SrcExpr,
6970 CodeModificationHint &Hint) {
6971 if (!SemaRef.getLangOptions().ObjC1)
6972 return;
6973
6974 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6975 if (!PT)
6976 return;
6977
6978 // Check if the destination is of type 'id'.
6979 if (!PT->isObjCIdType()) {
6980 // Check if the destination is the 'NSString' interface.
6981 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6982 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6983 return;
6984 }
6985
6986 // Strip off any parens and casts.
6987 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6988 if (!SL || SL->isWide())
6989 return;
6990
6991 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6992}
6993
Chris Lattner9bad62c2008-01-04 18:04:52 +00006994bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6995 SourceLocation Loc,
6996 QualType DstType, QualType SrcType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006997 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00006998 // Decode the result (notice that AST's are still created for extensions).
6999 bool isInvalid = false;
7000 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00007001 CodeModificationHint Hint;
7002
Chris Lattner9bad62c2008-01-04 18:04:52 +00007003 switch (ConvTy) {
7004 default: assert(0 && "Unknown conversion type");
7005 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007006 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00007007 DiagKind = diag::ext_typecheck_convert_pointer_int;
7008 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007009 case IntToPointer:
7010 DiagKind = diag::ext_typecheck_convert_int_pointer;
7011 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007012 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00007013 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007014 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7015 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00007016 case IncompatiblePointerSign:
7017 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7018 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007019 case FunctionVoidPointer:
7020 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7021 break;
7022 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00007023 // If the qualifiers lost were because we were applying the
7024 // (deprecated) C++ conversion from a string literal to a char*
7025 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7026 // Ideally, this check would be performed in
7027 // CheckPointerTypesForAssignment. However, that would require a
7028 // bit of refactoring (so that the second argument is an
7029 // expression, rather than a type), which should be done as part
7030 // of a larger effort to fix CheckPointerTypesForAssignment for
7031 // C++ semantics.
7032 if (getLangOptions().CPlusPlus &&
7033 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7034 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007035 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7036 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00007037 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00007038 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007039 break;
Steve Naroff081c7422008-09-04 15:10:53 +00007040 case IntToBlockPointer:
7041 DiagKind = diag::err_int_to_block_pointer;
7042 break;
7043 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00007044 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00007045 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00007046 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00007047 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00007048 // it can give a more specific diagnostic.
7049 DiagKind = diag::warn_incompatible_qualified_id;
7050 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007051 case IncompatibleVectors:
7052 DiagKind = diag::warn_incompatible_vectors;
7053 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007054 case Incompatible:
7055 DiagKind = diag::err_typecheck_convert_incompatible;
7056 isInvalid = true;
7057 break;
7058 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007059
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007060 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00007061 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007062 return isInvalid;
7063}
Anders Carlssone54e8a12008-11-30 19:50:32 +00007064
Chris Lattnerc71d08b2009-04-25 21:59:05 +00007065bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007066 llvm::APSInt ICEResult;
7067 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7068 if (Result)
7069 *Result = ICEResult;
7070 return false;
7071 }
7072
Anders Carlssone54e8a12008-11-30 19:50:32 +00007073 Expr::EvalResult EvalResult;
7074
Mike Stump4e1f26a2009-02-19 03:04:26 +00007075 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00007076 EvalResult.HasSideEffects) {
7077 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7078
7079 if (EvalResult.Diag) {
7080 // We only show the note if it's not the usual "invalid subexpression"
7081 // or if it's actually in a subexpression.
7082 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7083 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7084 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7085 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007086
Anders Carlssone54e8a12008-11-30 19:50:32 +00007087 return true;
7088 }
7089
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007090 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7091 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00007092
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007093 if (EvalResult.Diag &&
7094 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7095 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007096
Anders Carlssone54e8a12008-11-30 19:50:32 +00007097 if (Result)
7098 *Result = EvalResult.Val.getInt();
7099 return false;
7100}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007101
Douglas Gregorff790f12009-11-26 00:44:06 +00007102void
Mike Stump11289f42009-09-09 15:08:12 +00007103Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00007104 ExprEvalContexts.push_back(
7105 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007106}
7107
Mike Stump11289f42009-09-09 15:08:12 +00007108void
Douglas Gregorff790f12009-11-26 00:44:06 +00007109Sema::PopExpressionEvaluationContext() {
7110 // Pop the current expression evaluation context off the stack.
7111 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7112 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007113
Douglas Gregorfab31f42009-12-12 07:57:52 +00007114 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7115 if (Rec.PotentiallyReferenced) {
7116 // Mark any remaining declarations in the current position of the stack
7117 // as "referenced". If they were not meant to be referenced, semantic
7118 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7119 for (PotentiallyReferencedDecls::iterator
7120 I = Rec.PotentiallyReferenced->begin(),
7121 IEnd = Rec.PotentiallyReferenced->end();
7122 I != IEnd; ++I)
7123 MarkDeclarationReferenced(I->first, I->second);
7124 }
7125
7126 if (Rec.PotentiallyDiagnosed) {
7127 // Emit any pending diagnostics.
7128 for (PotentiallyEmittedDiagnostics::iterator
7129 I = Rec.PotentiallyDiagnosed->begin(),
7130 IEnd = Rec.PotentiallyDiagnosed->end();
7131 I != IEnd; ++I)
7132 Diag(I->first, I->second);
7133 }
Douglas Gregorff790f12009-11-26 00:44:06 +00007134 }
7135
7136 // When are coming out of an unevaluated context, clear out any
7137 // temporaries that we may have created as part of the evaluation of
7138 // the expression in that context: they aren't relevant because they
7139 // will never be constructed.
7140 if (Rec.Context == Unevaluated &&
7141 ExprTemporaries.size() > Rec.NumTemporaries)
7142 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7143 ExprTemporaries.end());
7144
7145 // Destroy the popped expression evaluation record.
7146 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007147}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007148
7149/// \brief Note that the given declaration was referenced in the source code.
7150///
7151/// This routine should be invoke whenever a given declaration is referenced
7152/// in the source code, and where that reference occurred. If this declaration
7153/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7154/// C99 6.9p3), then the declaration will be marked as used.
7155///
7156/// \param Loc the location where the declaration was referenced.
7157///
7158/// \param D the declaration that has been referenced by the source code.
7159void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7160 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007161
Douglas Gregor77b50e12009-06-22 23:06:13 +00007162 if (D->isUsed())
7163 return;
Mike Stump11289f42009-09-09 15:08:12 +00007164
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007165 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7166 // template or not. The reason for this is that unevaluated expressions
7167 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7168 // -Wunused-parameters)
7169 if (isa<ParmVarDecl>(D) ||
7170 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007171 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00007172
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007173 // Do not mark anything as "used" within a dependent context; wait for
7174 // an instantiation.
7175 if (CurContext->isDependentContext())
7176 return;
Mike Stump11289f42009-09-09 15:08:12 +00007177
Douglas Gregorff790f12009-11-26 00:44:06 +00007178 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007179 case Unevaluated:
7180 // We are in an expression that is not potentially evaluated; do nothing.
7181 return;
Mike Stump11289f42009-09-09 15:08:12 +00007182
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007183 case PotentiallyEvaluated:
7184 // We are in a potentially-evaluated expression, so this declaration is
7185 // "used"; handle this below.
7186 break;
Mike Stump11289f42009-09-09 15:08:12 +00007187
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007188 case PotentiallyPotentiallyEvaluated:
7189 // We are in an expression that may be potentially evaluated; queue this
7190 // declaration reference until we know whether the expression is
7191 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007192 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007193 return;
7194 }
Mike Stump11289f42009-09-09 15:08:12 +00007195
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007196 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007197 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007198 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007199 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7200 if (!Constructor->isUsed())
7201 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007202 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007203 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007204 if (!Constructor->isUsed())
7205 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7206 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007207
7208 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007209 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7210 if (Destructor->isImplicit() && !Destructor->isUsed())
7211 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00007212
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007213 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7214 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7215 MethodDecl->getOverloadedOperator() == OO_Equal) {
7216 if (!MethodDecl->isUsed())
7217 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7218 }
7219 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007220 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007221 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007222 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00007223 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007224 bool AlreadyInstantiated = false;
7225 if (FunctionTemplateSpecializationInfo *SpecInfo
7226 = Function->getTemplateSpecializationInfo()) {
7227 if (SpecInfo->getPointOfInstantiation().isInvalid())
7228 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007229 else if (SpecInfo->getTemplateSpecializationKind()
7230 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007231 AlreadyInstantiated = true;
7232 } else if (MemberSpecializationInfo *MSInfo
7233 = Function->getMemberSpecializationInfo()) {
7234 if (MSInfo->getPointOfInstantiation().isInvalid())
7235 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007236 else if (MSInfo->getTemplateSpecializationKind()
7237 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007238 AlreadyInstantiated = true;
7239 }
7240
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007241 if (!AlreadyInstantiated) {
7242 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7243 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7244 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7245 Loc));
7246 else
7247 PendingImplicitInstantiations.push_back(std::make_pair(Function,
7248 Loc));
7249 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007250 }
7251
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007252 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007253 Function->setUsed(true);
7254 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007255 }
Mike Stump11289f42009-09-09 15:08:12 +00007256
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007257 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007258 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007259 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007260 Var->getInstantiatedFromStaticDataMember()) {
7261 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7262 assert(MSInfo && "Missing member specialization information?");
7263 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7264 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7265 MSInfo->setPointOfInstantiation(Loc);
7266 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7267 }
7268 }
Mike Stump11289f42009-09-09 15:08:12 +00007269
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007270 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007271
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007272 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007273 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007274 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007275}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007276
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007277/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7278/// of the program being compiled.
7279///
7280/// This routine emits the given diagnostic when the code currently being
7281/// type-checked is "potentially evaluated", meaning that there is a
7282/// possibility that the code will actually be executable. Code in sizeof()
7283/// expressions, code used only during overload resolution, etc., are not
7284/// potentially evaluated. This routine will suppress such diagnostics or,
7285/// in the absolutely nutty case of potentially potentially evaluated
7286/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7287/// later.
7288///
7289/// This routine should be used for all diagnostics that describe the run-time
7290/// behavior of a program, such as passing a non-POD value through an ellipsis.
7291/// Failure to do so will likely result in spurious diagnostics or failures
7292/// during overload resolution or within sizeof/alignof/typeof/typeid.
7293bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7294 const PartialDiagnostic &PD) {
7295 switch (ExprEvalContexts.back().Context ) {
7296 case Unevaluated:
7297 // The argument will never be evaluated, so don't complain.
7298 break;
7299
7300 case PotentiallyEvaluated:
7301 Diag(Loc, PD);
7302 return true;
7303
7304 case PotentiallyPotentiallyEvaluated:
7305 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7306 break;
7307 }
7308
7309 return false;
7310}
7311
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007312bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7313 CallExpr *CE, FunctionDecl *FD) {
7314 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7315 return false;
7316
7317 PartialDiagnostic Note =
7318 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7319 << FD->getDeclName() : PDiag();
7320 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7321
7322 if (RequireCompleteType(Loc, ReturnType,
7323 FD ?
7324 PDiag(diag::err_call_function_incomplete_return)
7325 << CE->getSourceRange() << FD->getDeclName() :
7326 PDiag(diag::err_call_incomplete_return)
7327 << CE->getSourceRange(),
7328 std::make_pair(NoteLoc, Note)))
7329 return true;
7330
7331 return false;
7332}
7333
John McCalld5707ab2009-10-12 21:59:07 +00007334// Diagnose the common s/=/==/ typo. Note that adding parentheses
7335// will prevent this condition from triggering, which is what we want.
7336void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7337 SourceLocation Loc;
7338
John McCall0506e4a2009-11-11 02:41:58 +00007339 unsigned diagnostic = diag::warn_condition_is_assignment;
7340
John McCalld5707ab2009-10-12 21:59:07 +00007341 if (isa<BinaryOperator>(E)) {
7342 BinaryOperator *Op = cast<BinaryOperator>(E);
7343 if (Op->getOpcode() != BinaryOperator::Assign)
7344 return;
7345
John McCallb0e419e2009-11-12 00:06:05 +00007346 // Greylist some idioms by putting them into a warning subcategory.
7347 if (ObjCMessageExpr *ME
7348 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7349 Selector Sel = ME->getSelector();
7350
John McCallb0e419e2009-11-12 00:06:05 +00007351 // self = [<foo> init...]
7352 if (isSelfExpr(Op->getLHS())
7353 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7354 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7355
7356 // <foo> = [<bar> nextObject]
7357 else if (Sel.isUnarySelector() &&
7358 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7359 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7360 }
John McCall0506e4a2009-11-11 02:41:58 +00007361
John McCalld5707ab2009-10-12 21:59:07 +00007362 Loc = Op->getOperatorLoc();
7363 } else if (isa<CXXOperatorCallExpr>(E)) {
7364 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7365 if (Op->getOperator() != OO_Equal)
7366 return;
7367
7368 Loc = Op->getOperatorLoc();
7369 } else {
7370 // Not an assignment.
7371 return;
7372 }
7373
John McCalld5707ab2009-10-12 21:59:07 +00007374 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007375 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007376
John McCall0506e4a2009-11-11 02:41:58 +00007377 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007378 << E->getSourceRange()
7379 << CodeModificationHint::CreateInsertion(Open, "(")
7380 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007381 Diag(Loc, diag::note_condition_assign_to_comparison)
7382 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00007383}
7384
7385bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7386 DiagnoseAssignmentAsCondition(E);
7387
7388 if (!E->isTypeDependent()) {
7389 DefaultFunctionArrayConversion(E);
7390
7391 QualType T = E->getType();
7392
7393 if (getLangOptions().CPlusPlus) {
7394 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7395 return true;
7396 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7397 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7398 << T << E->getSourceRange();
7399 return true;
7400 }
7401 }
7402
7403 return false;
7404}