blob: 91c1fa5a1225054b743be5c0077615090ba9d1c0 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000020#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
David Chisnall44663db2009-08-17 16:35:33 +000030
Douglas Gregoraa57e862009-02-18 21:56:37 +000031/// \brief Determine whether the use of this declaration is valid, and
32/// emit any corresponding diagnostics.
33///
34/// This routine diagnoses various problems with referencing
35/// declarations that can occur when using a declaration. For example,
36/// it might warn if a deprecated or unavailable declaration is being
37/// used, or produce an error (and return true) if a C++0x deleted
38/// function is being used.
39///
40/// \returns true if there was an error (this declaration cannot be
41/// referenced), false otherwise.
42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000043 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000044 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000045 // Implementing deprecated stuff requires referencing deprecated
46 // stuff. Don't warn if we are implementing a deprecated
47 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000048 bool isSilenced = false;
49
50 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
51 // If this reference happens *in* a deprecated function or method, don't
52 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000053 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000054
55 // If this is an Objective-C method implementation, check to see if the
56 // method was deprecated on the declaration, not the definition.
57 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
58 // The semantic decl context of a ObjCMethodDecl is the
59 // ObjCImplementationDecl.
60 if (ObjCImplementationDecl *Impl
61 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
62
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000063 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000064 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000065 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000066 }
67 }
68 }
69
70 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000071 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
72 }
73
Douglas Gregoraa57e862009-02-18 21:56:37 +000074 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000075 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000076 if (FD->isDeleted()) {
77 Diag(Loc, diag::err_deleted_function_use);
78 Diag(D->getLocation(), diag::note_unavailable_here) << true;
79 return true;
80 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000081 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000082
83 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000084 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000085 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000086 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
87 }
88
Douglas Gregoraa57e862009-02-18 21:56:37 +000089 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000090}
91
Fariborz Jahanian180f3412009-05-13 18:09:35 +000092/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
93/// (and other functions in future), which have been declared with sentinel
94/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
97 Expr **Args, unsigned NumArgs)
98{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000099 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000100 if (!attr)
101 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000102 int sentinelPos = attr->getSentinel();
103 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000104
Mike Stumpe127ae32009-05-16 07:39:55 +0000105 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
106 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000107 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000108 bool warnNotEnoughArgs = false;
109 int isMethod = 0;
110 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
111 // skip over named parameters.
112 ObjCMethodDecl::param_iterator P, E = MD->param_end();
113 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
114 if (nullPos)
115 --nullPos;
116 else
117 ++i;
118 }
119 warnNotEnoughArgs = (P != E || i >= NumArgs);
120 isMethod = 1;
Mike Stump90fc78e2009-08-04 21:02:39 +0000121 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000122 // skip over named parameters.
123 ObjCMethodDecl::param_iterator P, E = FD->param_end();
124 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
125 if (nullPos)
126 --nullPos;
127 else
128 ++i;
129 }
130 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump90fc78e2009-08-04 21:02:39 +0000131 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000132 // block or function pointer call.
133 QualType Ty = V->getType();
134 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
135 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000136 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
137 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000138 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
139 unsigned NumArgsInProto = Proto->getNumArgs();
140 unsigned k;
141 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
142 if (nullPos)
143 --nullPos;
144 else
145 ++i;
146 }
147 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
148 }
149 if (Ty->isBlockPointerType())
150 isMethod = 2;
Mike Stump90fc78e2009-08-04 21:02:39 +0000151 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000152 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000153 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000154 return;
155
156 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000157 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000158 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000159 return;
160 }
161 int sentinel = i;
162 while (sentinelPos > 0 && i < NumArgs-1) {
163 --sentinelPos;
164 ++i;
165 }
166 if (sentinelPos > 0) {
167 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000168 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000169 return;
170 }
171 while (i < NumArgs-1) {
172 ++i;
173 ++sentinel;
174 }
175 Expr *sentinelExpr = Args[sentinel];
176 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
177 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000178 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000179 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000180 }
181 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000182}
183
Douglas Gregor3bb30002009-02-26 21:00:50 +0000184SourceRange Sema::getExprRange(ExprTy *E) const {
185 Expr *Ex = (Expr *)E;
186 return Ex? Ex->getSourceRange() : SourceRange();
187}
188
Chris Lattner299b8842008-07-25 21:10:04 +0000189//===----------------------------------------------------------------------===//
190// Standard Promotions and Conversions
191//===----------------------------------------------------------------------===//
192
Chris Lattner299b8842008-07-25 21:10:04 +0000193/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
194void Sema::DefaultFunctionArrayConversion(Expr *&E) {
195 QualType Ty = E->getType();
196 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
197
Chris Lattner299b8842008-07-25 21:10:04 +0000198 if (Ty->isFunctionType())
199 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000200 else if (Ty->isArrayType()) {
201 // In C90 mode, arrays only promote to pointers if the array expression is
202 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
203 // type 'array of type' is converted to an expression that has type 'pointer
204 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
205 // that has type 'array of type' ...". The relevant change is "an lvalue"
206 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000207 //
208 // C++ 4.2p1:
209 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
210 // T" can be converted to an rvalue of type "pointer to T".
211 //
212 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
213 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000214 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
215 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000216 }
Chris Lattner299b8842008-07-25 21:10:04 +0000217}
218
219/// UsualUnaryConversions - Performs various conversions that are common to most
220/// operators (C99 6.3). The conversions of array and function types are
221/// sometimes surpressed. For example, the array->pointer conversion doesn't
222/// apply if the array is an argument to the sizeof or address (&) operators.
223/// In these instances, this routine should *not* be called.
224Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
225 QualType Ty = Expr->getType();
226 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
227
Douglas Gregor70b307e2009-05-01 20:41:21 +0000228 // C99 6.3.1.1p2:
229 //
230 // The following may be used in an expression wherever an int or
231 // unsigned int may be used:
232 // - an object or expression with an integer type whose integer
233 // conversion rank is less than or equal to the rank of int
234 // and unsigned int.
235 // - A bit-field of type _Bool, int, signed int, or unsigned int.
236 //
237 // If an int can represent all values of the original type, the
238 // value is converted to an int; otherwise, it is converted to an
239 // unsigned int. These are called the integer promotions. All
240 // other types are unchanged by the integer promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000241 QualType PTy = Context.isPromotableBitField(Expr);
242 if (!PTy.isNull()) {
243 ImpCastExprToType(Expr, PTy);
244 return Expr;
245 }
Douglas Gregor70b307e2009-05-01 20:41:21 +0000246 if (Ty->isPromotableIntegerType()) {
Eli Friedman6ae7d112009-08-19 07:44:53 +0000247 QualType PT = Context.getPromotedIntegerType(Ty);
248 ImpCastExprToType(Expr, PT);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000249 return Expr;
Eli Friedman1931cc82009-08-20 04:21:42 +0000250 }
251
Douglas Gregor70b307e2009-05-01 20:41:21 +0000252 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000253 return Expr;
254}
255
Chris Lattner9305c3d2008-07-25 22:25:12 +0000256/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
257/// do not have a prototype. Arguments that have type float are promoted to
258/// double. All other argument types are converted by UsualUnaryConversions().
259void Sema::DefaultArgumentPromotion(Expr *&Expr) {
260 QualType Ty = Expr->getType();
261 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
262
263 // If this is a 'float' (CVR qualified or typedef) promote to double.
264 if (const BuiltinType *BT = Ty->getAsBuiltinType())
265 if (BT->getKind() == BuiltinType::Float)
266 return ImpCastExprToType(Expr, Context.DoubleTy);
267
268 UsualUnaryConversions(Expr);
269}
270
Chris Lattner81f00ed2009-04-12 08:11:20 +0000271/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
272/// will warn if the resulting type is not a POD type, and rejects ObjC
273/// interfaces passed by value. This returns true if the argument type is
274/// completely illegal.
275bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000276 DefaultArgumentPromotion(Expr);
277
Chris Lattner81f00ed2009-04-12 08:11:20 +0000278 if (Expr->getType()->isObjCInterfaceType()) {
279 Diag(Expr->getLocStart(),
280 diag::err_cannot_pass_objc_interface_to_vararg)
281 << Expr->getType() << CT;
282 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000283 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000284
285 if (!Expr->getType()->isPODType())
286 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
287 << Expr->getType() << CT;
288
289 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000290}
291
292
Chris Lattner299b8842008-07-25 21:10:04 +0000293/// UsualArithmeticConversions - Performs various conversions that are common to
294/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
295/// routine returns the first non-arithmetic type found. The client is
296/// responsible for emitting appropriate error diagnostics.
297/// FIXME: verify the conversion rules for "complex int" are consistent with
298/// GCC.
299QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
300 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000301 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000302 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000303
304 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000305
Chris Lattner299b8842008-07-25 21:10:04 +0000306 // For conversion purposes, we ignore any qualifiers.
307 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000308 QualType lhs =
309 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
310 QualType rhs =
311 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000312
313 // If both types are identical, no conversion is needed.
314 if (lhs == rhs)
315 return lhs;
316
317 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
318 // The caller can deal with this (e.g. pointer + int).
319 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
320 return lhs;
321
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000322 // Perform bitfield promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000323 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000324 if (!LHSBitfieldPromoteTy.isNull())
325 lhs = LHSBitfieldPromoteTy;
Eli Friedman1931cc82009-08-20 04:21:42 +0000326 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000327 if (!RHSBitfieldPromoteTy.isNull())
328 rhs = RHSBitfieldPromoteTy;
329
Eli Friedman6ae7d112009-08-19 07:44:53 +0000330 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000331 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000332 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000333 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000334 return destType;
335}
336
Chris Lattner299b8842008-07-25 21:10:04 +0000337//===----------------------------------------------------------------------===//
338// Semantic Analysis for various Expression Types
339//===----------------------------------------------------------------------===//
340
341
Steve Naroff87d58b42007-09-16 03:34:24 +0000342/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000343/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
344/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
345/// multiple tokens. However, the common case is that StringToks points to one
346/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000347///
348Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000349Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000350 assert(NumStringToks && "Must have at least one string!");
351
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000352 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000353 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000354 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000355
356 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
357 for (unsigned i = 0; i != NumStringToks; ++i)
358 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000359
Chris Lattnera6dcce32008-02-11 00:02:17 +0000360 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000361 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000362 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000363
364 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
365 if (getLangOptions().CPlusPlus)
366 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000367
Chris Lattnera6dcce32008-02-11 00:02:17 +0000368 // Get an array type for the string, according to C99 6.4.5. This includes
369 // the nul terminator character as well as the string length for pascal
370 // strings.
371 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000372 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000373 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000374
Chris Lattner4b009652007-07-25 00:24:17 +0000375 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000376 return Owned(StringLiteral::Create(Context, Literal.GetString(),
377 Literal.GetStringLength(),
378 Literal.AnyWide, StrTy,
379 &StringTokLocs[0],
380 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000381}
382
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000383/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
384/// CurBlock to VD should cause it to be snapshotted (as we do for auto
385/// variables defined outside the block) or false if this is not needed (e.g.
386/// for values inside the block or for globals).
387///
Chris Lattner0b464252009-04-21 22:26:47 +0000388/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
389/// up-to-date.
390///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000391static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
392 ValueDecl *VD) {
393 // If the value is defined inside the block, we couldn't snapshot it even if
394 // we wanted to.
395 if (CurBlock->TheDecl == VD->getDeclContext())
396 return false;
397
398 // If this is an enum constant or function, it is constant, don't snapshot.
399 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
400 return false;
401
402 // If this is a reference to an extern, static, or global variable, no need to
403 // snapshot it.
404 // FIXME: What about 'const' variables in C++?
405 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000406 if (!Var->hasLocalStorage())
407 return false;
408
409 // Blocks that have these can't be constant.
410 CurBlock->hasBlockDeclRefExprs = true;
411
412 // If we have nested blocks, the decl may be declared in an outer block (in
413 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
414 // be defined outside all of the current blocks (in which case the blocks do
415 // all get the bit). Walk the nesting chain.
416 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
417 NextBlock = NextBlock->PrevBlockInfo) {
418 // If we found the defining block for the variable, don't mark the block as
419 // having a reference outside it.
420 if (NextBlock->TheDecl == VD->getDeclContext())
421 break;
422
423 // Otherwise, the DeclRef from the inner block causes the outer one to need
424 // a snapshot as well.
425 NextBlock->hasBlockDeclRefExprs = true;
426 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000427
428 return true;
429}
430
431
432
Steve Naroff0acc9c92007-09-15 18:49:24 +0000433/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000434/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000435/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000436/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000437/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000438Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
439 IdentifierInfo &II,
440 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000441 const CXXScopeSpec *SS,
442 bool isAddressOfOperand) {
443 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000444 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000445}
446
Douglas Gregor566782a2009-01-06 05:10:23 +0000447/// BuildDeclRefExpr - Build either a DeclRefExpr or a
448/// QualifiedDeclRefExpr based on whether or not SS is a
449/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000450Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000451Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
452 bool TypeDependent, bool ValueDependent,
453 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000454 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
455 Diag(Loc,
456 diag::err_auto_variable_cannot_appear_in_own_initializer)
457 << D->getDeclName();
458 return ExprError();
459 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000460
461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
462 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
463 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
464 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
465 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
466 << D->getIdentifier() << FD->getDeclName();
467 Diag(D->getLocation(), diag::note_local_variable_declared_here)
468 << D->getIdentifier();
469 return ExprError();
470 }
471 }
472 }
473 }
474
Douglas Gregor98189262009-06-19 23:52:42 +0000475 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000476
477 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000478 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000479 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
480 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000481 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000482 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000483 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
484
485 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000486}
487
Douglas Gregor723d3332009-01-07 00:43:41 +0000488/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
489/// variable corresponding to the anonymous union or struct whose type
490/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000491static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
492 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000493 assert(Record->isAnonymousStructOrUnion() &&
494 "Record must be an anonymous struct or union!");
495
Mike Stumpe127ae32009-05-16 07:39:55 +0000496 // FIXME: Once Decls are directly linked together, this will be an O(1)
497 // operation rather than a slow walk through DeclContext's vector (which
498 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000499 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000500 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
501 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000502 D != DEnd; ++D) {
503 if (*D == Record) {
504 // The object for the anonymous struct/union directly
505 // follows its type in the list of declarations.
506 ++D;
507 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000508 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000509 return *D;
510 }
511 }
512
513 assert(false && "Missing object for anonymous record");
514 return 0;
515}
516
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000517/// \brief Given a field that represents a member of an anonymous
518/// struct/union, build the path from that field's context to the
519/// actual member.
520///
521/// Construct the sequence of field member references we'll have to
522/// perform to get to the field in the anonymous union/struct. The
523/// list of members is built from the field outward, so traverse it
524/// backwards to go from an object in the current context to the field
525/// we found.
526///
527/// \returns The variable from which the field access should begin,
528/// for an anonymous struct/union that is not a member of another
529/// class. Otherwise, returns NULL.
530VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
531 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000532 assert(Field->getDeclContext()->isRecord() &&
533 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
534 && "Field must be stored inside an anonymous struct or union");
535
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000536 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000537 VarDecl *BaseObject = 0;
538 DeclContext *Ctx = Field->getDeclContext();
539 do {
540 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000541 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000542 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000543 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000544 else {
545 BaseObject = cast<VarDecl>(AnonObject);
546 break;
547 }
548 Ctx = Ctx->getParent();
549 } while (Ctx->isRecord() &&
550 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000551
552 return BaseObject;
553}
554
555Sema::OwningExprResult
556Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
557 FieldDecl *Field,
558 Expr *BaseObjectExpr,
559 SourceLocation OpLoc) {
560 llvm::SmallVector<FieldDecl *, 4> AnonFields;
561 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
562 AnonFields);
563
Douglas Gregor723d3332009-01-07 00:43:41 +0000564 // Build the expression that refers to the base object, from
565 // which we will build a sequence of member references to each
566 // of the anonymous union objects and, eventually, the field we
567 // found via name lookup.
568 bool BaseObjectIsPointer = false;
569 unsigned ExtraQuals = 0;
570 if (BaseObject) {
571 // BaseObject is an anonymous struct/union variable (and is,
572 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000573 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000574 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000575 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000576 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000577 ExtraQuals
578 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
579 } else if (BaseObjectExpr) {
580 // The caller provided the base object expression. Determine
581 // whether its a pointer and whether it adds any qualifiers to the
582 // anonymous struct/union fields we're looking into.
583 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000584 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000585 BaseObjectIsPointer = true;
586 ObjectType = ObjectPtr->getPointeeType();
587 }
588 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
589 } else {
590 // We've found a member of an anonymous struct/union that is
591 // inside a non-anonymous struct/union, so in a well-formed
592 // program our base object expression is "this".
593 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
594 if (!MD->isStatic()) {
595 QualType AnonFieldType
596 = Context.getTagDeclType(
597 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
598 QualType ThisType = Context.getTagDeclType(MD->getParent());
599 if ((Context.getCanonicalType(AnonFieldType)
600 == Context.getCanonicalType(ThisType)) ||
601 IsDerivedFrom(ThisType, AnonFieldType)) {
602 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000603 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000604 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000605 BaseObjectIsPointer = true;
606 }
607 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000608 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
609 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000610 }
611 ExtraQuals = MD->getTypeQualifiers();
612 }
613
614 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000615 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
616 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000617 }
618
619 // Build the implicit member references to the field of the
620 // anonymous struct/union.
621 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000622 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000623 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
624 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
625 FI != FIEnd; ++FI) {
626 QualType MemberType = (*FI)->getType();
627 if (!(*FI)->isMutable()) {
628 unsigned combinedQualifiers
629 = MemberType.getCVRQualifiers() | ExtraQuals;
630 MemberType = MemberType.getQualifiedType(combinedQualifiers);
631 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000632 if (BaseAddrSpace != MemberType.getAddressSpace())
633 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000634 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregore399ad42009-08-26 22:36:53 +0000635 // FIXME: Might this end up being a qualified name?
Steve Naroff774e4152009-01-21 00:14:39 +0000636 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
637 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000638 BaseObjectIsPointer = false;
639 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000640 }
641
Sebastian Redlcd883f72009-01-18 18:53:16 +0000642 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000643}
644
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000645/// ActOnDeclarationNameExpr - The parser has read some kind of name
646/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
647/// performs lookup on that name and returns an expression that refers
648/// to that name. This routine isn't directly called from the parser,
649/// because the parser doesn't know about DeclarationName. Rather,
650/// this routine is called by ActOnIdentifierExpr,
651/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
652/// which form the DeclarationName from the corresponding syntactic
653/// forms.
654///
655/// HasTrailingLParen indicates whether this identifier is used in a
656/// function call context. LookupCtx is only used for a C++
657/// qualified-id (foo::bar) to indicate the class or namespace that
658/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000659///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000660/// isAddressOfOperand means that this expression is the direct operand
661/// of an address-of operator. This matters because this is the only
662/// situation where a qualified name referencing a non-static member may
663/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000664Sema::OwningExprResult
665Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
666 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000667 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000668 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000669 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000670 if (SS && SS->isInvalid())
671 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000672
673 // C++ [temp.dep.expr]p3:
674 // An id-expression is type-dependent if it contains:
675 // -- a nested-name-specifier that contains a class-name that
676 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000677 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000678 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000679 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
680 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000681 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
682 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000683 }
684
Douglas Gregor411889e2009-02-13 23:20:09 +0000685 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
686 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000687
Sebastian Redlcd883f72009-01-18 18:53:16 +0000688 if (Lookup.isAmbiguous()) {
689 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
690 SS && SS->isSet() ? SS->getRange()
691 : SourceRange());
692 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000693 }
694
695 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000696
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000697 // If this reference is in an Objective-C method, then ivar lookup happens as
698 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000699 IdentifierInfo *II = Name.getAsIdentifierInfo();
700 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000701 // There are two cases to handle here. 1) scoped lookup could have failed,
702 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000703 // found a decl, but that decl is outside the current instance method (i.e.
704 // a global variable). In these two cases, we do a lookup for an ivar with
705 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000706 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000707 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000708 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000709 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000710 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000711 if (DiagnoseUseOfDecl(IV, Loc))
712 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000713
714 // If we're referencing an invalid decl, just return this as a silent
715 // error node. The error diagnostic was already emitted on the decl.
716 if (IV->isInvalidDecl())
717 return ExprError();
718
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000719 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
720 // If a class method attemps to use a free standing ivar, this is
721 // an error.
722 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
723 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
724 << IV->getDeclName());
725 // If a class method uses a global variable, even if an ivar with
726 // same name exists, use the global.
727 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000728 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
729 ClassDeclared != IFace)
730 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000731 // FIXME: This should use a new expr for a direct reference, don't
732 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000733 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000734 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
735 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000736 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000737 return Owned(new (Context)
738 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000739 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000740 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000741 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000742 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000743 // We should warn if a local variable hides an ivar.
744 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000745 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000746 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000747 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
748 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000749 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000750 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000751 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000752 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000753 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000754 QualType T;
755
756 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000757 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
758 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000759 else
760 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000761 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000762 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000763 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000764
Douglas Gregoraa57e862009-02-18 21:56:37 +0000765 // Determine whether this name might be a candidate for
766 // argument-dependent lookup.
767 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
768 HasTrailingLParen;
769
770 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000771 // We've seen something of the form
772 //
773 // identifier(
774 //
775 // and we did not find any entity by the name
776 // "identifier". However, this identifier is still subject to
777 // argument-dependent lookup, so keep track of the name.
778 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
779 Context.OverloadTy,
780 Loc));
781 }
782
Chris Lattner4b009652007-07-25 00:24:17 +0000783 if (D == 0) {
784 // Otherwise, this could be an implicitly declared function reference (legal
785 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000786 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000787 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000788 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000789 else {
790 // If this name wasn't predeclared and if this is not a function call,
791 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000792 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000793 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
794 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000795 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
796 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000797 return ExprError(Diag(Loc, diag::err_undeclared_use)
798 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000799 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000800 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000801 }
802 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000803
804 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
805 // Warn about constructs like:
806 // if (void *X = foo()) { ... } else { X }.
807 // In the else block, the pointer is always false.
808
809 // FIXME: In a template instantiation, we don't have scope
810 // information to check this property.
811 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
812 Scope *CheckS = S;
813 while (CheckS) {
814 if (CheckS->isWithinElse() &&
815 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
816 if (Var->getType()->isBooleanType())
817 ExprError(Diag(Loc, diag::warn_value_always_false)
818 << Var->getDeclName());
819 else
820 ExprError(Diag(Loc, diag::warn_value_always_zero)
821 << Var->getDeclName());
822 break;
823 }
824
825 // Move up one more control parent to check again.
826 CheckS = CheckS->getControlParent();
827 if (CheckS)
828 CheckS = CheckS->getParent();
829 }
830 }
831 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
832 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
833 // C99 DR 316 says that, if a function type comes from a
834 // function definition (without a prototype), that type is only
835 // used for checking compatibility. Therefore, when referencing
836 // the function, we pretend that we don't have the full function
837 // type.
838 if (DiagnoseUseOfDecl(Func, Loc))
839 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000840
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000841 QualType T = Func->getType();
842 QualType NoProtoType = T;
843 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
844 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
845 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
846 }
847 }
848
849 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
850}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000851/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000852bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000853Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
854 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
855 if (CXXRecordDecl *RD =
856 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
857 QualType DestType =
858 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000859 if (DestType->isDependentType() || From->getType()->isDependentType())
860 return false;
861 QualType FromRecordType = From->getType();
862 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000863 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000864 DestType = Context.getPointerType(DestType);
865 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000866 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000867 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
868 CheckDerivedToBaseConversion(FromRecordType,
869 DestRecordType,
870 From->getSourceRange().getBegin(),
871 From->getSourceRange()))
872 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000873 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
874 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000875 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000876 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000877}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000878
Douglas Gregore399ad42009-08-26 22:36:53 +0000879/// \brief Build a MemberExpr or CXXQualifiedMemberExpr, as appropriate.
880static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
881 const CXXScopeSpec *SS, NamedDecl *Member,
882 SourceLocation Loc, QualType Ty) {
883 if (SS && SS->isSet())
884 return new (C) CXXQualifiedMemberExpr(Base, isArrow,
885 (NestedNameSpecifier *)SS->getScopeRep(),
886 SS->getRange(),
887 Member, Loc, Ty);
888
889 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
890}
891
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000892/// \brief Complete semantic analysis for a reference to the given declaration.
893Sema::OwningExprResult
894Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
895 bool HasTrailingLParen,
896 const CXXScopeSpec *SS,
897 bool isAddressOfOperand) {
898 assert(D && "Cannot refer to a NULL declaration");
899 DeclarationName Name = D->getDeclName();
900
Sebastian Redl0c9da212009-02-03 20:19:35 +0000901 // If this is an expression of the form &Class::member, don't build an
902 // implicit member ref, because we want a pointer to the member in general,
903 // not any specific instance's member.
904 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000905 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000906 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000907 QualType DType;
908 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
909 DType = FD->getType().getNonReferenceType();
910 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
911 DType = Method->getType();
912 } else if (isa<OverloadedFunctionDecl>(D)) {
913 DType = Context.OverloadTy;
914 }
915 // Could be an inner type. That's diagnosed below, so ignore it here.
916 if (!DType.isNull()) {
917 // The pointer is type- and value-dependent if it points into something
918 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000919 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000920 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000921 }
922 }
923 }
924
Douglas Gregor723d3332009-01-07 00:43:41 +0000925 // We may have found a field within an anonymous union or struct
926 // (C++ [class.union]).
927 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
928 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
929 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000930
Douglas Gregor3257fb52008-12-22 05:46:06 +0000931 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
932 if (!MD->isStatic()) {
933 // C++ [class.mfct.nonstatic]p2:
934 // [...] if name lookup (3.4.1) resolves the name in the
935 // id-expression to a nonstatic nontype member of class X or of
936 // a base class of X, the id-expression is transformed into a
937 // class member access expression (5.2.5) using (*this) (9.3.2)
938 // as the postfix-expression to the left of the '.' operator.
939 DeclContext *Ctx = 0;
940 QualType MemberType;
941 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
942 Ctx = FD->getDeclContext();
943 MemberType = FD->getType();
944
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000945 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000946 MemberType = RefType->getPointeeType();
947 else if (!FD->isMutable()) {
948 unsigned combinedQualifiers
949 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
950 MemberType = MemberType.getQualifiedType(combinedQualifiers);
951 }
952 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
953 if (!Method->isStatic()) {
954 Ctx = Method->getParent();
955 MemberType = Method->getType();
956 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000957 } else if (FunctionTemplateDecl *FunTmpl
958 = dyn_cast<FunctionTemplateDecl>(D)) {
959 if (CXXMethodDecl *Method
960 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
961 if (!Method->isStatic()) {
962 Ctx = Method->getParent();
963 MemberType = Context.OverloadTy;
964 }
965 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000966 } else if (OverloadedFunctionDecl *Ovl
967 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000968 // FIXME: We need an abstraction for iterating over one or more function
969 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000970 for (OverloadedFunctionDecl::function_iterator
971 Func = Ovl->function_begin(),
972 FuncEnd = Ovl->function_end();
973 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000974 CXXMethodDecl *DMethod = 0;
975 if (FunctionTemplateDecl *FunTmpl
976 = dyn_cast<FunctionTemplateDecl>(*Func))
977 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
978 else
979 DMethod = dyn_cast<CXXMethodDecl>(*Func);
980
981 if (DMethod && !DMethod->isStatic()) {
982 Ctx = DMethod->getDeclContext();
983 MemberType = Context.OverloadTy;
984 break;
985 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000986 }
987 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000988
989 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000990 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
991 QualType ThisType = Context.getTagDeclType(MD->getParent());
992 if ((Context.getCanonicalType(CtxType)
993 == Context.getCanonicalType(ThisType)) ||
994 IsDerivedFrom(ThisType, CtxType)) {
995 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000996 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000997 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +0000998 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000999 if (PerformObjectMemberConversion(This, D))
1000 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001001 if (DiagnoseUseOfDecl(D, Loc))
1002 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00001003 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1004 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001005 }
1006 }
1007 }
1008 }
1009
Douglas Gregor8acb7272008-12-11 16:49:14 +00001010 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001011 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1012 if (MD->isStatic())
1013 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001014 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1015 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001016 }
1017
Douglas Gregor3257fb52008-12-22 05:46:06 +00001018 // Any other ways we could have found the field in a well-formed
1019 // program would have been turned into implicit member expressions
1020 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001021 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1022 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001023 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001024
Chris Lattner4b009652007-07-25 00:24:17 +00001025 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001026 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001027 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001028 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001029 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001030 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001031
Steve Naroffd6163f32008-09-05 22:11:13 +00001032 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001033 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001034 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1035 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001036 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001037 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1038 false, false, SS);
Steve Naroffd6163f32008-09-05 22:11:13 +00001039 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001040
Douglas Gregoraa57e862009-02-18 21:56:37 +00001041 // Check whether this declaration can be used. Note that we suppress
1042 // this check when we're going to perform argument-dependent lookup
1043 // on this function name, because this might not be the function
1044 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001045 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1046 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001047 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1048 return ExprError();
1049
Steve Naroffd6163f32008-09-05 22:11:13 +00001050 // Only create DeclRefExpr's for valid Decl's.
1051 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001052 return ExprError();
1053
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001054 // If the identifier reference is inside a block, and it refers to a value
1055 // that is outside the block, create a BlockDeclRefExpr instead of a
1056 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1057 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001058 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001059 // We do not do this for things like enum constants, global variables, etc,
1060 // as they do not get snapshotted.
1061 //
1062 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001063 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001064 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001065 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001066 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001067 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001068 // This is to record that a 'const' was actually synthesize and added.
1069 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001070 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001071
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001072 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001073 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1074 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001075 }
1076 // If this reference is not in a block or if the referenced variable is
1077 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001078
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001079 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001080 bool ValueDependent = false;
1081 if (getLangOptions().CPlusPlus) {
1082 // C++ [temp.dep.expr]p3:
1083 // An id-expression is type-dependent if it contains:
1084 // - an identifier that was declared with a dependent type,
1085 if (VD->getType()->isDependentType())
1086 TypeDependent = true;
1087 // - FIXME: a template-id that is dependent,
1088 // - a conversion-function-id that specifies a dependent type,
1089 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1090 Name.getCXXNameType()->isDependentType())
1091 TypeDependent = true;
1092 // - a nested-name-specifier that contains a class-name that
1093 // names a dependent type.
1094 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001095 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001096 DC; DC = DC->getParent()) {
1097 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001098 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001099 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1100 if (Context.getTypeDeclType(Record)->isDependentType()) {
1101 TypeDependent = true;
1102 break;
1103 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001104 }
1105 }
1106 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001107
Douglas Gregora5d84612008-12-10 20:57:37 +00001108 // C++ [temp.dep.constexpr]p2:
1109 //
1110 // An identifier is value-dependent if it is:
1111 // - a name declared with a dependent type,
1112 if (TypeDependent)
1113 ValueDependent = true;
1114 // - the name of a non-type template parameter,
1115 else if (isa<NonTypeTemplateParmDecl>(VD))
1116 ValueDependent = true;
1117 // - a constant with integral or enumeration type and is
1118 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001119 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1120 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1121 Dcl->getInit()) {
1122 ValueDependent = Dcl->getInit()->isValueDependent();
1123 }
1124 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001125 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001126
Anders Carlsson4571d812009-06-24 00:10:43 +00001127 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1128 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001129}
1130
Sebastian Redlcd883f72009-01-18 18:53:16 +00001131Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1132 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001133 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001134
Chris Lattner4b009652007-07-25 00:24:17 +00001135 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001136 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001137 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1138 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1139 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001140 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001141
Chris Lattner7e637512008-01-12 08:14:25 +00001142 // Pre-defined identifiers are of type char[x], where x is the length of the
1143 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001144 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001145 if (FunctionDecl *FD = getCurFunctionDecl())
1146 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001147 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1148 Length = MD->getSynthesizedMethodSize();
1149 else {
1150 Diag(Loc, diag::ext_predef_outside_function);
1151 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1152 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1153 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001154
1155
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001156 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001157 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001158 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001159 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001160}
1161
Sebastian Redlcd883f72009-01-18 18:53:16 +00001162Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001163 llvm::SmallString<16> CharBuffer;
1164 CharBuffer.resize(Tok.getLength());
1165 const char *ThisTokBegin = &CharBuffer[0];
1166 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001167
Chris Lattner4b009652007-07-25 00:24:17 +00001168 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1169 Tok.getLocation(), PP);
1170 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001171 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001172
1173 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1174
Sebastian Redl75324932009-01-20 22:23:13 +00001175 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1176 Literal.isWide(),
1177 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001178}
1179
Sebastian Redlcd883f72009-01-18 18:53:16 +00001180Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1181 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001182 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1183 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001184 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001185 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001186 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001187 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001188 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001189
Chris Lattner4b009652007-07-25 00:24:17 +00001190 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001191 // Add padding so that NumericLiteralParser can overread by one character.
1192 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001193 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001194
Chris Lattner4b009652007-07-25 00:24:17 +00001195 // Get the spelling of the token, which eliminates trigraphs, etc.
1196 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001197
Chris Lattner4b009652007-07-25 00:24:17 +00001198 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1199 Tok.getLocation(), PP);
1200 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001201 return ExprError();
1202
Chris Lattner1de66eb2007-08-26 03:42:43 +00001203 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001204
Chris Lattner1de66eb2007-08-26 03:42:43 +00001205 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001206 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001207 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001208 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001209 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001210 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001211 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001212 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001213
1214 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1215
Ted Kremenekddedbe22007-11-29 00:56:49 +00001216 // isExact will be set by GetFloatValue().
1217 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001218 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1219 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001220
Chris Lattner1de66eb2007-08-26 03:42:43 +00001221 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001222 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001223 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001224 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001225
Neil Booth7421e9c2007-08-29 22:00:19 +00001226 // long long is a C99 feature.
1227 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001228 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001229 Diag(Tok.getLocation(), diag::ext_longlong);
1230
Chris Lattner4b009652007-07-25 00:24:17 +00001231 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001232 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001233
Chris Lattner4b009652007-07-25 00:24:17 +00001234 if (Literal.GetIntegerValue(ResultVal)) {
1235 // If this value didn't fit into uintmax_t, warn and force to ull.
1236 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001237 Ty = Context.UnsignedLongLongTy;
1238 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001239 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001240 } else {
1241 // If this value fits into a ULL, try to figure out what else it fits into
1242 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001243
Chris Lattner4b009652007-07-25 00:24:17 +00001244 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1245 // be an unsigned int.
1246 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1247
1248 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001249 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001250 if (!Literal.isLong && !Literal.isLongLong) {
1251 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001252 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001253
Chris Lattner4b009652007-07-25 00:24:17 +00001254 // Does it fit in a unsigned int?
1255 if (ResultVal.isIntN(IntSize)) {
1256 // Does it fit in a signed int?
1257 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001258 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001259 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001260 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001261 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001262 }
Chris Lattner4b009652007-07-25 00:24:17 +00001263 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001264
Chris Lattner4b009652007-07-25 00:24:17 +00001265 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001266 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001267 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001268
Chris Lattner4b009652007-07-25 00:24:17 +00001269 // Does it fit in a unsigned long?
1270 if (ResultVal.isIntN(LongSize)) {
1271 // Does it fit in a signed long?
1272 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001273 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001274 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001275 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001276 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001277 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001278 }
1279
Chris Lattner4b009652007-07-25 00:24:17 +00001280 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001281 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001282 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001283
Chris Lattner4b009652007-07-25 00:24:17 +00001284 // Does it fit in a unsigned long long?
1285 if (ResultVal.isIntN(LongLongSize)) {
1286 // Does it fit in a signed long long?
1287 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001288 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001289 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001290 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001291 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001292 }
1293 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001294
Chris Lattner4b009652007-07-25 00:24:17 +00001295 // If we still couldn't decide a type, we probably have something that
1296 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001297 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001298 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001299 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001300 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001301 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001302
Chris Lattnere4068872008-05-09 05:59:00 +00001303 if (ResultVal.getBitWidth() != Width)
1304 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001305 }
Sebastian Redl75324932009-01-20 22:23:13 +00001306 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001307 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001308
Chris Lattner1de66eb2007-08-26 03:42:43 +00001309 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1310 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001311 Res = new (Context) ImaginaryLiteral(Res,
1312 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001313
1314 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001315}
1316
Sebastian Redlcd883f72009-01-18 18:53:16 +00001317Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1318 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001319 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001320 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001321 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001322}
1323
1324/// The UsualUnaryConversions() function is *not* called by this routine.
1325/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001326bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001327 SourceLocation OpLoc,
1328 const SourceRange &ExprRange,
1329 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001330 if (exprType->isDependentType())
1331 return false;
1332
Chris Lattner4b009652007-07-25 00:24:17 +00001333 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001334 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001335 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001336 if (isSizeof)
1337 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1338 return false;
1339 }
1340
Chris Lattner95933c12009-04-24 00:30:45 +00001341 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001342 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001343 Diag(OpLoc, diag::ext_sizeof_void_type)
1344 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001345 return false;
1346 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001347
Chris Lattner95933c12009-04-24 00:30:45 +00001348 if (RequireCompleteType(OpLoc, exprType,
1349 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssona21e7872009-08-26 23:45:07 +00001350 PDiag(diag::err_alignof_incomplete_type)
1351 << ExprRange))
Chris Lattner95933c12009-04-24 00:30:45 +00001352 return true;
1353
1354 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001355 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001356 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001357 << exprType << isSizeof << ExprRange;
1358 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001359 }
1360
Chris Lattner95933c12009-04-24 00:30:45 +00001361 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001362}
1363
Chris Lattner8d9f7962009-01-24 20:17:12 +00001364bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1365 const SourceRange &ExprRange) {
1366 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001367
Chris Lattner8d9f7962009-01-24 20:17:12 +00001368 // alignof decl is always ok.
1369 if (isa<DeclRefExpr>(E))
1370 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001371
1372 // Cannot know anything else if the expression is dependent.
1373 if (E->isTypeDependent())
1374 return false;
1375
Douglas Gregor531434b2009-05-02 02:18:30 +00001376 if (E->getBitField()) {
1377 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1378 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001379 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001380
1381 // Alignment of a field access is always okay, so long as it isn't a
1382 // bit-field.
1383 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001384 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001385 return false;
1386
Chris Lattner8d9f7962009-01-24 20:17:12 +00001387 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1388}
1389
Douglas Gregor396f1142009-03-13 21:01:28 +00001390/// \brief Build a sizeof or alignof expression given a type operand.
1391Action::OwningExprResult
1392Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1393 bool isSizeOf, SourceRange R) {
1394 if (T.isNull())
1395 return ExprError();
1396
1397 if (!T->isDependentType() &&
1398 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1399 return ExprError();
1400
1401 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1402 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1403 Context.getSizeType(), OpLoc,
1404 R.getEnd()));
1405}
1406
1407/// \brief Build a sizeof or alignof expression given an expression
1408/// operand.
1409Action::OwningExprResult
1410Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1411 bool isSizeOf, SourceRange R) {
1412 // Verify that the operand is valid.
1413 bool isInvalid = false;
1414 if (E->isTypeDependent()) {
1415 // Delay type-checking for type-dependent expressions.
1416 } else if (!isSizeOf) {
1417 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001418 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001419 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1420 isInvalid = true;
1421 } else {
1422 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1423 }
1424
1425 if (isInvalid)
1426 return ExprError();
1427
1428 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1429 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1430 Context.getSizeType(), OpLoc,
1431 R.getEnd()));
1432}
1433
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001434/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1435/// the same for @c alignof and @c __alignof
1436/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001437Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001438Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1439 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001440 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001441 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001442
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001443 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001444 // FIXME: Preserve type source info.
1445 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001446 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1447 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001448
Douglas Gregor396f1142009-03-13 21:01:28 +00001449 // Get the end location.
1450 Expr *ArgEx = (Expr *)TyOrEx;
1451 Action::OwningExprResult Result
1452 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1453
1454 if (Result.isInvalid())
1455 DeleteExpr(ArgEx);
1456
1457 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001458}
1459
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001460QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001461 if (V->isTypeDependent())
1462 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001463
Chris Lattnera16e42d2007-08-26 05:39:26 +00001464 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001465 if (const ComplexType *CT = V->getType()->getAsComplexType())
1466 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001467
1468 // Otherwise they pass through real integer and floating point types here.
1469 if (V->getType()->isArithmeticType())
1470 return V->getType();
1471
1472 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001473 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1474 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001475 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001476}
1477
1478
Chris Lattner4b009652007-07-25 00:24:17 +00001479
Sebastian Redl8b769972009-01-19 00:08:26 +00001480Action::OwningExprResult
1481Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1482 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001483 // Since this might be a postfix expression, get rid of ParenListExprs.
1484 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001485 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001486
Chris Lattner4b009652007-07-25 00:24:17 +00001487 UnaryOperator::Opcode Opc;
1488 switch (Kind) {
1489 default: assert(0 && "Unknown unary op!");
1490 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1491 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1492 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001493
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001494 if (getLangOptions().CPlusPlus &&
1495 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1496 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001497 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001498 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1499
1500 // C++ [over.inc]p1:
1501 //
1502 // [...] If the function is a member function with one
1503 // parameter (which shall be of type int) or a non-member
1504 // function with two parameters (the second of which shall be
1505 // of type int), it defines the postfix increment operator ++
1506 // for objects of that type. When the postfix increment is
1507 // called as a result of using the ++ operator, the int
1508 // argument will have value zero.
1509 Expr *Args[2] = {
1510 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001511 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1512 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001513 };
1514
1515 // Build the candidate set for overloading
1516 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001517 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001518
1519 // Perform overload resolution.
1520 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001521 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001522 case OR_Success: {
1523 // We found a built-in operator or an overloaded operator.
1524 FunctionDecl *FnDecl = Best->Function;
1525
1526 if (FnDecl) {
1527 // We matched an overloaded operator. Build a call to that
1528 // operator.
1529
1530 // Convert the arguments.
1531 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1532 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001533 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001534 } else {
1535 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001536 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001537 FnDecl->getParamDecl(0)->getType(),
1538 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001539 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001540 }
1541
1542 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001543 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001544 = FnDecl->getType()->getAsFunctionType()->getResultType();
1545 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001546
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001547 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001548 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001549 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001550 UsualUnaryConversions(FnExpr);
1551
Sebastian Redl8b769972009-01-19 00:08:26 +00001552 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001553 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001554 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1555 Args, 2, ResultTy,
1556 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001557 } else {
1558 // We matched a built-in operator. Convert the arguments, then
1559 // break out so that we will build the appropriate built-in
1560 // operator node.
1561 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1562 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001563 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001564
1565 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001566 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001567 }
1568
1569 case OR_No_Viable_Function:
1570 // No viable function; fall through to handling this as a
1571 // built-in operator, which will produce an error message for us.
1572 break;
1573
1574 case OR_Ambiguous:
1575 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1576 << UnaryOperator::getOpcodeStr(Opc)
1577 << Arg->getSourceRange();
1578 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001579 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001580
1581 case OR_Deleted:
1582 Diag(OpLoc, diag::err_ovl_deleted_oper)
1583 << Best->Function->isDeleted()
1584 << UnaryOperator::getOpcodeStr(Opc)
1585 << Arg->getSourceRange();
1586 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1587 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001588 }
1589
1590 // Either we found no viable overloaded operator or we matched a
1591 // built-in operator. In either case, fall through to trying to
1592 // build a built-in operation.
1593 }
1594
Eli Friedman94d30952009-07-22 23:24:42 +00001595 Input.release();
1596 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001597 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001598}
1599
Sebastian Redl8b769972009-01-19 00:08:26 +00001600Action::OwningExprResult
1601Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1602 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001603 // Since this might be a postfix expression, get rid of ParenListExprs.
1604 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1605
Sebastian Redl8b769972009-01-19 00:08:26 +00001606 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1607 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001608
Douglas Gregor80723c52008-11-19 17:17:41 +00001609 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001610 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1611 Base.release();
1612 Idx.release();
1613 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1614 Context.DependentTy, RLoc));
1615 }
1616
1617 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001618 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001619 LHSExp->getType()->isEnumeralType() ||
1620 RHSExp->getType()->isRecordType() ||
1621 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001622 // Add the appropriate overloaded operators (C++ [over.match.oper])
1623 // to the candidate set.
1624 OverloadCandidateSet CandidateSet;
1625 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001626 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1627 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001628
Douglas Gregor80723c52008-11-19 17:17:41 +00001629 // Perform overload resolution.
1630 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001631 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001632 case OR_Success: {
1633 // We found a built-in operator or an overloaded operator.
1634 FunctionDecl *FnDecl = Best->Function;
1635
1636 if (FnDecl) {
1637 // We matched an overloaded operator. Build a call to that
1638 // operator.
1639
1640 // Convert the arguments.
1641 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1642 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1643 PerformCopyInitialization(RHSExp,
1644 FnDecl->getParamDecl(0)->getType(),
1645 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001646 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001647 } else {
1648 // Convert the arguments.
1649 if (PerformCopyInitialization(LHSExp,
1650 FnDecl->getParamDecl(0)->getType(),
1651 "passing") ||
1652 PerformCopyInitialization(RHSExp,
1653 FnDecl->getParamDecl(1)->getType(),
1654 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001655 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001656 }
1657
1658 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001659 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001660 = FnDecl->getType()->getAsFunctionType()->getResultType();
1661 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001662
Douglas Gregor80723c52008-11-19 17:17:41 +00001663 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001664 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1665 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001666 UsualUnaryConversions(FnExpr);
1667
Sebastian Redl8b769972009-01-19 00:08:26 +00001668 Base.release();
1669 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001670 Args[0] = LHSExp;
1671 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001672 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1673 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001674 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001675 } else {
1676 // We matched a built-in operator. Convert the arguments, then
1677 // break out so that we will build the appropriate built-in
1678 // operator node.
1679 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1680 "passing") ||
1681 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1682 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001683 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001684
1685 break;
1686 }
1687 }
1688
1689 case OR_No_Viable_Function:
1690 // No viable function; fall through to handling this as a
1691 // built-in operator, which will produce an error message for us.
1692 break;
1693
1694 case OR_Ambiguous:
1695 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1696 << "[]"
1697 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1698 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001699 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001700
1701 case OR_Deleted:
1702 Diag(LLoc, diag::err_ovl_deleted_oper)
1703 << Best->Function->isDeleted()
1704 << "[]"
1705 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1706 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1707 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001708 }
1709
1710 // Either we found no viable overloaded operator or we matched a
1711 // built-in operator. In either case, fall through to trying to
1712 // build a built-in operation.
1713 }
1714
Chris Lattner4b009652007-07-25 00:24:17 +00001715 // Perform default conversions.
1716 DefaultFunctionArrayConversion(LHSExp);
1717 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001718
Chris Lattner4b009652007-07-25 00:24:17 +00001719 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1720
1721 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001722 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001723 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001724 // and index from the expression types.
1725 Expr *BaseExpr, *IndexExpr;
1726 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001727 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1728 BaseExpr = LHSExp;
1729 IndexExpr = RHSExp;
1730 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001731 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001732 BaseExpr = LHSExp;
1733 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001734 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001735 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001736 // Handle the uncommon case of "123[Ptr]".
1737 BaseExpr = RHSExp;
1738 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001739 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001740 } else if (const ObjCObjectPointerType *PTy =
1741 LHSTy->getAsObjCObjectPointerType()) {
1742 BaseExpr = LHSExp;
1743 IndexExpr = RHSExp;
1744 ResultType = PTy->getPointeeType();
1745 } else if (const ObjCObjectPointerType *PTy =
1746 RHSTy->getAsObjCObjectPointerType()) {
1747 // Handle the uncommon case of "123[Ptr]".
1748 BaseExpr = RHSExp;
1749 IndexExpr = LHSExp;
1750 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001751 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1752 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001753 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001754
Chris Lattner4b009652007-07-25 00:24:17 +00001755 // FIXME: need to deal with const...
1756 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001757 } else if (LHSTy->isArrayType()) {
1758 // If we see an array that wasn't promoted by
1759 // DefaultFunctionArrayConversion, it must be an array that
1760 // wasn't promoted because of the C90 rule that doesn't
1761 // allow promoting non-lvalue arrays. Warn, then
1762 // force the promotion here.
1763 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1764 LHSExp->getSourceRange();
1765 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1766 LHSTy = LHSExp->getType();
1767
1768 BaseExpr = LHSExp;
1769 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001770 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001771 } else if (RHSTy->isArrayType()) {
1772 // Same as previous, except for 123[f().a] case
1773 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1774 RHSExp->getSourceRange();
1775 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1776 RHSTy = RHSExp->getType();
1777
1778 BaseExpr = RHSExp;
1779 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001780 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001781 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001782 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1783 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001784 }
Chris Lattner4b009652007-07-25 00:24:17 +00001785 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001786 if (!(IndexExpr->getType()->isIntegerType() &&
1787 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001788 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1789 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001790
Douglas Gregor05e28f62009-03-24 19:52:54 +00001791 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1792 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1793 // type. Note that Functions are not objects, and that (in C99 parlance)
1794 // incomplete types are not object types.
1795 if (ResultType->isFunctionType()) {
1796 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1797 << ResultType << BaseExpr->getSourceRange();
1798 return ExprError();
1799 }
Chris Lattner95933c12009-04-24 00:30:45 +00001800
Douglas Gregor05e28f62009-03-24 19:52:54 +00001801 if (!ResultType->isDependentType() &&
Anders Carlssona21e7872009-08-26 23:45:07 +00001802 RequireCompleteType(LLoc, ResultType,
1803 PDiag(diag::err_subscript_incomplete_type)
1804 << BaseExpr->getSourceRange()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00001805 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001806
1807 // Diagnose bad cases where we step over interface counts.
1808 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1809 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1810 << ResultType << BaseExpr->getSourceRange();
1811 return ExprError();
1812 }
1813
Sebastian Redl8b769972009-01-19 00:08:26 +00001814 Base.release();
1815 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001816 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001817 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001818}
1819
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001820QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001821CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001822 const IdentifierInfo *CompName,
1823 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001824 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001825
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001826 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001827 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001828
Mike Stump9afab102009-02-19 03:04:26 +00001829 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001830 // special names that indicate a subset of exactly half the elements are
1831 // to be selected.
1832 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001833
Nate Begeman1486b502009-01-18 01:47:54 +00001834 // This flag determines whether or not CompName has an 's' char prefix,
1835 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001836 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001837
1838 // Check that we've found one of the special components, or that the component
1839 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001840 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001841 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1842 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001843 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001844 do
1845 compStr++;
1846 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001847 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001848 do
1849 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001850 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001851 }
Nate Begeman1486b502009-01-18 01:47:54 +00001852
Mike Stump9afab102009-02-19 03:04:26 +00001853 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001854 // We didn't get to the end of the string. This means the component names
1855 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001856 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1857 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001858 return QualType();
1859 }
Mike Stump9afab102009-02-19 03:04:26 +00001860
Nate Begeman1486b502009-01-18 01:47:54 +00001861 // Ensure no component accessor exceeds the width of the vector type it
1862 // operates on.
1863 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001864 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001865
1866 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001867 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001868
1869 while (*compStr) {
1870 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1871 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1872 << baseType << SourceRange(CompLoc);
1873 return QualType();
1874 }
1875 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001876 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001877
Nate Begeman1486b502009-01-18 01:47:54 +00001878 // If this is a halving swizzle, verify that the base type has an even
1879 // number of elements.
1880 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001881 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001882 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001883 return QualType();
1884 }
Mike Stump9afab102009-02-19 03:04:26 +00001885
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001886 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001887 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001888 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001889 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001890 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001891 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001892 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001893 if (HexSwizzle)
1894 CompSize--;
1895
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001896 if (CompSize == 1)
1897 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001898
Nate Begemanaf6ed502008-04-18 23:10:10 +00001899 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001900 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001901 // diagostics look bad. We want extended vector types to appear built-in.
1902 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1903 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1904 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001905 }
1906 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001907}
1908
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001909static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001910 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001911 const Selector &Sel,
1912 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001913
Anders Carlsson9935ab92009-08-26 18:25:21 +00001914 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001915 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001916 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001917 return OMD;
1918
1919 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1920 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001921 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1922 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001923 return D;
1924 }
1925 return 0;
1926}
1927
Steve Naroffc75c1a82009-06-17 22:40:22 +00001928static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001929 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001930 const Selector &Sel,
1931 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001932 // Check protocols on qualified interfaces.
1933 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001934 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001935 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001936 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001937 GDecl = PD;
1938 break;
1939 }
1940 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001941 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001942 GDecl = OMD;
1943 break;
1944 }
1945 }
1946 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001947 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001948 E = QIdTy->qual_end(); I != E; ++I) {
1949 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001950 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001951 if (GDecl)
1952 return GDecl;
1953 }
1954 }
1955 return GDecl;
1956}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001957
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001958/// FindMethodInNestedImplementations - Look up a method in current and
1959/// all base class implementations.
1960///
1961ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1962 const ObjCInterfaceDecl *IFace,
1963 const Selector &Sel) {
1964 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001965 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001966 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001967
1968 if (!Method && IFace->getSuperClass())
1969 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1970 return Method;
1971}
Douglas Gregore399ad42009-08-26 22:36:53 +00001972
Anders Carlsson9935ab92009-08-26 18:25:21 +00001973Action::OwningExprResult
1974Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001975 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001976 DeclarationName MemberName,
Douglas Gregorda61ad22009-08-06 03:17:00 +00001977 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001978 if (SS && SS->isInvalid())
1979 return ExprError();
1980
Nate Begemane85f43d2009-08-10 23:49:36 +00001981 // Since this might be a postfix expression, get rid of ParenListExprs.
1982 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1983
Anders Carlssonc154a722009-05-01 19:30:39 +00001984 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001985 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00001986
Steve Naroff137e11d2007-12-16 21:42:28 +00001987 // Perform default conversions.
1988 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001989
Steve Naroff2cb66382007-07-26 03:11:44 +00001990 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00001991 // If this is an Objective-C pseudo-builtin and a definition is provided then
1992 // use that.
1993 if (BaseType->isObjCIdType()) {
1994 // We have an 'id' type. Rather than fall through, we check if this
1995 // is a reference to 'isa'.
1996 if (BaseType != Context.ObjCIdRedefinitionType) {
1997 BaseType = Context.ObjCIdRedefinitionType;
1998 ImpCastExprToType(BaseExpr, BaseType);
1999 }
2000 } else if (BaseType->isObjCClassType() &&
2001 BaseType != Context.ObjCClassRedefinitionType) {
2002 BaseType = Context.ObjCClassRedefinitionType;
2003 ImpCastExprToType(BaseExpr, BaseType);
2004 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002005 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002006
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002007 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2008 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002009 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002010 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002011 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2012 BaseExpr, true,
2013 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002014 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002015 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002016 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002017 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002018 else if (BaseType->isObjCObjectPointerType())
2019 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002020 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002021 return ExprError(Diag(MemberLoc,
2022 diag::err_typecheck_member_reference_arrow)
2023 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002024 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002025 if (BaseType->isDependentType()) {
2026 // Require that the base type isn't a pointer type
2027 // (so we'll report an error for)
2028 // T* t;
2029 // t.f;
2030 //
2031 // In Obj-C++, however, the above expression is valid, since it could be
2032 // accessing the 'f' property if T is an Obj-C interface. The extra check
2033 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002034 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002035
2036 if (!PT || (getLangOptions().ObjC1 &&
2037 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002038 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2039 BaseExpr, false,
2040 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002041 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002042 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002043 }
Chris Lattner4b009652007-07-25 00:24:17 +00002044 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002045
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002046 // Handle field access to simple records. This also handles access to fields
2047 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002048 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002049 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002050 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002051 PDiag(diag::err_typecheck_incomplete_tag)
2052 << BaseExpr->getSourceRange()))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002053 return ExprError();
2054
Douglas Gregorda61ad22009-08-06 03:17:00 +00002055 DeclContext *DC = RDecl;
2056 if (SS && SS->isSet()) {
2057 // If the member name was a qualified-id, look into the
2058 // nested-name-specifier.
2059 DC = computeDeclContext(*SS, false);
2060
2061 // FIXME: If DC is not computable, we should build a
2062 // CXXUnresolvedMemberExpr.
2063 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2064 }
2065
Steve Naroff2cb66382007-07-26 03:11:44 +00002066 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002067 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002068 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002069
Douglas Gregor12431cb2009-08-06 05:28:30 +00002070 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002071 QualType BaseTypeCanon
2072 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2073 QualType MemberTypeCanon
2074 = Context.getCanonicalType(
2075 Context.getTypeDeclType(
2076 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2077
2078 if (BaseTypeCanon != MemberTypeCanon &&
2079 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2080 return ExprError(Diag(SS->getBeginLoc(),
2081 diag::err_not_direct_base_or_virtual)
2082 << MemberTypeCanon << BaseTypeCanon);
2083 }
2084
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002085 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002086 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002087 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002088 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002089 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2090 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002091 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002092 }
2093
2094 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002095
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002096 // If the decl being referenced had an error, return an error for this
2097 // sub-expr without emitting another error, in order to avoid cascading
2098 // error cases.
2099 if (MemberDecl->isInvalidDecl())
2100 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002101
Douglas Gregoraa57e862009-02-18 21:56:37 +00002102 // Check the use of this field
2103 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2104 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002105
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002106 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002107 // We may have found a field within an anonymous union or struct
2108 // (C++ [class.union]).
2109 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002110 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002111 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002112
Douglas Gregor82d44772008-12-20 23:49:58 +00002113 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002114 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002115 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002116 MemberType = Ref->getPointeeType();
2117 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002118 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002119 unsigned combinedQualifiers =
2120 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002121 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002122 combinedQualifiers &= ~QualType::Const;
2123 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002124 if (BaseAddrSpace != MemberType.getAddressSpace())
2125 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002126 }
Eli Friedman76b49832008-02-06 22:48:16 +00002127
Douglas Gregorcad27f62009-06-22 23:06:13 +00002128 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002129 if (PerformObjectMemberConversion(BaseExpr, FD))
2130 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002131 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2132 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002133 }
2134
Douglas Gregorcad27f62009-06-22 23:06:13 +00002135 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2136 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002137 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2138 Var, MemberLoc,
2139 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002140 }
2141 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2142 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002143 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2144 MemberFn, MemberLoc,
2145 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002146 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002147 if (FunctionTemplateDecl *FunTmpl
2148 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2149 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002150 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2151 FunTmpl, MemberLoc,
2152 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002153 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002154 if (OverloadedFunctionDecl *Ovl
2155 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregore399ad42009-08-26 22:36:53 +00002156 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2157 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002158 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2159 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002160 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2161 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002162 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002163 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002164 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002165 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002166
Douglas Gregor82d44772008-12-20 23:49:58 +00002167 // We found a declaration kind that we didn't expect. This is a
2168 // generic error message that tells the user that she can't refer
2169 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002170 return ExprError(Diag(MemberLoc,
2171 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002172 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002173 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002174
Steve Naroff329ec222009-07-10 23:34:53 +00002175 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002176 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002177 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002178 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2179 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002180 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2181 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2182 ObjCMethodDecl *Getter;
2183 // FIXME: need to also look locally in the implementation.
2184 if ((Getter = IFace->lookupClassMethod(Sel))) {
2185 // Check the use of this method.
2186 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2187 return ExprError();
2188 }
2189 // If we found a getter then this may be a valid dot-reference, we
2190 // will look for the matching setter, in case it is needed.
2191 Selector SetterSel =
2192 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002193 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002194 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2195 if (!Setter) {
2196 // If this reference is in an @implementation, also check for 'private'
2197 // methods.
2198 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2199 }
2200 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002201 if (!Setter)
2202 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002203
2204 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2205 return ExprError();
2206
2207 if (Getter || Setter) {
2208 QualType PType;
2209
2210 if (Getter)
2211 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002212 else
2213 // Get the expression type from Setter's incoming parameter.
2214 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002215 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002216 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002217 Setter, MemberLoc, BaseExpr));
2218 }
2219 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002220 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002221 }
2222 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002223 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2224 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002225 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2226 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2227 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2228 const ObjCInterfaceType *IFaceT =
2229 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002230 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002231 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2232
Steve Naroff4e743962009-07-16 00:25:06 +00002233 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2234 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002235 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002236
2237 if (IV) {
2238 // If the decl being referenced had an error, return an error for this
2239 // sub-expr without emitting another error, in order to avoid cascading
2240 // error cases.
2241 if (IV->isInvalidDecl())
2242 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002243
Steve Naroff4e743962009-07-16 00:25:06 +00002244 // Check whether we can reference this field.
2245 if (DiagnoseUseOfDecl(IV, MemberLoc))
2246 return ExprError();
2247 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2248 IV->getAccessControl() != ObjCIvarDecl::Package) {
2249 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2250 if (ObjCMethodDecl *MD = getCurMethodDecl())
2251 ClassOfMethodDecl = MD->getClassInterface();
2252 else if (ObjCImpDecl && getCurFunctionDecl()) {
2253 // Case of a c-function declared inside an objc implementation.
2254 // FIXME: For a c-style function nested inside an objc implementation
2255 // class, there is no implementation context available, so we pass
2256 // down the context as argument to this routine. Ideally, this context
2257 // need be passed down in the AST node and somehow calculated from the
2258 // AST for a function decl.
2259 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2260 if (ObjCImplementationDecl *IMPD =
2261 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2262 ClassOfMethodDecl = IMPD->getClassInterface();
2263 else if (ObjCCategoryImplDecl* CatImplClass =
2264 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2265 ClassOfMethodDecl = CatImplClass->getClassInterface();
2266 }
2267
2268 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2269 if (ClassDeclared != IDecl ||
2270 ClassOfMethodDecl != ClassDeclared)
2271 Diag(MemberLoc, diag::error_private_ivar_access)
2272 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002273 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2274 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002275 Diag(MemberLoc, diag::error_protected_ivar_access)
2276 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002277 }
Steve Naroff4e743962009-07-16 00:25:06 +00002278
2279 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2280 MemberLoc, BaseExpr,
2281 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002282 }
Steve Naroff4e743962009-07-16 00:25:06 +00002283 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002284 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002285 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002286 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002287 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002288 // Handle properties on 'id' and qualified "id".
2289 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2290 BaseType->isObjCQualifiedIdType())) {
2291 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002292 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002293
Steve Naroff329ec222009-07-10 23:34:53 +00002294 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002295 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002296 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2297 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2298 // Check the use of this declaration
2299 if (DiagnoseUseOfDecl(PD, MemberLoc))
2300 return ExprError();
2301
2302 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2303 MemberLoc, BaseExpr));
2304 }
2305 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2306 // Check the use of this method.
2307 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2308 return ExprError();
2309
2310 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2311 OMD->getResultType(),
2312 OMD, OpLoc, MemberLoc,
2313 NULL, 0));
2314 }
2315 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002316
Steve Naroff329ec222009-07-10 23:34:53 +00002317 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002318 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002319 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002320 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2321 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002322 const ObjCObjectPointerType *OPT;
2323 if (OpKind == tok::period &&
2324 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2325 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2326 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002327 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002328
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002329 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002330 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002331 // Check whether we can reference this property.
2332 if (DiagnoseUseOfDecl(PD, MemberLoc))
2333 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002334 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002335 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002336 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002337 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2338 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002339 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002340 MemberLoc, BaseExpr));
2341 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002342 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002343 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2344 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002345 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002346 // Check whether we can reference this property.
2347 if (DiagnoseUseOfDecl(PD, MemberLoc))
2348 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002349
Steve Naroff774e4152009-01-21 00:14:39 +00002350 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002351 MemberLoc, BaseExpr));
2352 }
Steve Naroff329ec222009-07-10 23:34:53 +00002353 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2354 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002355 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002356 // Check whether we can reference this property.
2357 if (DiagnoseUseOfDecl(PD, MemberLoc))
2358 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002359
Steve Naroff329ec222009-07-10 23:34:53 +00002360 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2361 MemberLoc, BaseExpr));
2362 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002363 // If that failed, look for an "implicit" property by seeing if the nullary
2364 // selector is implemented.
2365
2366 // FIXME: The logic for looking up nullary and unary selectors should be
2367 // shared with the code in ActOnInstanceMessage.
2368
Anders Carlsson9935ab92009-08-26 18:25:21 +00002369 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002370 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002371
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002372 // If this reference is in an @implementation, check for 'private' methods.
2373 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002374 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002375
Steve Naroff04151f32008-10-22 19:16:27 +00002376 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002377 if (!Getter)
2378 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002379 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002380 // Check if we can reference this property.
2381 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2382 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002383 }
2384 // If we found a getter then this may be a valid dot-reference, we
2385 // will look for the matching setter, in case it is needed.
2386 Selector SetterSel =
2387 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002388 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002389 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002390 if (!Setter) {
2391 // If this reference is in an @implementation, also check for 'private'
2392 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002393 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002394 }
2395 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002396 if (!Setter)
2397 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002398
Steve Naroffdede0c92009-03-11 13:48:17 +00002399 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2400 return ExprError();
2401
2402 if (Getter || Setter) {
2403 QualType PType;
2404
2405 if (Getter)
2406 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002407 else
2408 // Get the expression type from Setter's incoming parameter.
2409 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002410 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002411 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002412 Setter, MemberLoc, BaseExpr));
2413 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002414 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002415 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002416 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002417
Steve Naroff29d293b2009-07-24 17:54:45 +00002418 // Handle the following exceptional case (*Obj).isa.
2419 if (OpKind == tok::period &&
2420 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002421 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002422 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2423 Context.getObjCIdType()));
2424
Chris Lattnera57cf472008-07-21 04:28:12 +00002425 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002426 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002427 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002428 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2429 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002430 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002431 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002432 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002433 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002434
Douglas Gregor762da552009-03-27 06:00:30 +00002435 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2436 << BaseType << BaseExpr->getSourceRange();
2437
2438 // If the user is trying to apply -> or . to a function or function
2439 // pointer, it's probably because they forgot parentheses to call
2440 // the function. Suggest the addition of those parentheses.
2441 if (BaseType == Context.OverloadTy ||
2442 BaseType->isFunctionType() ||
2443 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002444 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002445 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2446 Diag(Loc, diag::note_member_reference_needs_call)
2447 << CodeModificationHint::CreateInsertion(Loc, "()");
2448 }
2449
2450 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002451}
2452
Anders Carlsson9935ab92009-08-26 18:25:21 +00002453Action::OwningExprResult
2454Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2455 tok::TokenKind OpKind, SourceLocation MemberLoc,
2456 IdentifierInfo &Member,
2457 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2458 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2459 DeclarationName(&Member), ObjCImpDecl, SS);
2460}
2461
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002462Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2463 FunctionDecl *FD,
2464 ParmVarDecl *Param) {
2465 if (Param->hasUnparsedDefaultArg()) {
2466 Diag (CallLoc,
2467 diag::err_use_of_default_argument_to_function_declared_later) <<
2468 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2469 Diag(UnparsedDefaultArgLocs[Param],
2470 diag::note_default_argument_declared_here);
2471 } else {
2472 if (Param->hasUninstantiatedDefaultArg()) {
2473 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2474
2475 // Instantiate the expression.
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002476 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002477
2478 // FIXME: We should really make a new InstantiatingTemplate ctor
2479 // that has a better message - right now we're just piggy-backing
2480 // off the "default template argument" error message.
2481 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002482 ArgList.getInnermost().getFlatArgumentList(),
2483 ArgList.getInnermost().flat_size());
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002484
John McCall0ba26ee2009-08-25 22:02:44 +00002485 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002486 if (Result.isInvalid())
2487 return ExprError();
2488
2489 if (SetParamDefaultArgument(Param, move(Result),
2490 /*FIXME:EqualLoc*/
2491 UninstExpr->getSourceRange().getBegin()))
2492 return ExprError();
2493 }
2494
2495 Expr *DefaultExpr = Param->getDefaultArg();
2496
2497 // If the default expression creates temporaries, we need to
2498 // push them to the current stack of expression temporaries so they'll
2499 // be properly destroyed.
2500 if (CXXExprWithTemporaries *E
2501 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2502 assert(!E->shouldDestroyTemporaries() &&
2503 "Can't destroy temporaries in a default argument expr!");
2504 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2505 ExprTemporaries.push_back(E->getTemporary(I));
2506 }
2507 }
2508
2509 // We already type-checked the argument, so we know it works.
2510 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2511}
2512
Douglas Gregor3257fb52008-12-22 05:46:06 +00002513/// ConvertArgumentsForCall - Converts the arguments specified in
2514/// Args/NumArgs to the parameter types of the function FDecl with
2515/// function prototype Proto. Call is the call expression itself, and
2516/// Fn is the function expression. For a C++ member function, this
2517/// routine does not attempt to convert the object argument. Returns
2518/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002519bool
2520Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002521 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002522 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002523 Expr **Args, unsigned NumArgs,
2524 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002525 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002526 // assignment, to the types of the corresponding parameter, ...
2527 unsigned NumArgsInProto = Proto->getNumArgs();
2528 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002529 bool Invalid = false;
2530
Douglas Gregor3257fb52008-12-22 05:46:06 +00002531 // If too few arguments are available (and we don't have default
2532 // arguments for the remaining parameters), don't make the call.
2533 if (NumArgs < NumArgsInProto) {
2534 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2535 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2536 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2537 // Use default arguments for missing arguments
2538 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002539 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002540 }
2541
2542 // If too many are passed and not variadic, error on the extras and drop
2543 // them.
2544 if (NumArgs > NumArgsInProto) {
2545 if (!Proto->isVariadic()) {
2546 Diag(Args[NumArgsInProto]->getLocStart(),
2547 diag::err_typecheck_call_too_many_args)
2548 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2549 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2550 Args[NumArgs-1]->getLocEnd());
2551 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002552 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002553 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002554 }
2555 NumArgsToCheck = NumArgsInProto;
2556 }
Mike Stump9afab102009-02-19 03:04:26 +00002557
Douglas Gregor3257fb52008-12-22 05:46:06 +00002558 // Continue to check argument types (even if we have too few/many args).
2559 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2560 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002561
Douglas Gregor3257fb52008-12-22 05:46:06 +00002562 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002563 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002564 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002565
Eli Friedman83dec9e2009-03-22 22:00:50 +00002566 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2567 ProtoArgType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002568 PDiag(diag::err_call_incomplete_argument)
2569 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002570 return true;
2571
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002572 // Pass the argument.
2573 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2574 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002575 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002576 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002577
2578 OwningExprResult ArgExpr =
2579 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2580 FDecl, Param);
2581 if (ArgExpr.isInvalid())
2582 return true;
2583
2584 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002585 }
2586
Douglas Gregor3257fb52008-12-22 05:46:06 +00002587 Call->setArg(i, Arg);
2588 }
Mike Stump9afab102009-02-19 03:04:26 +00002589
Douglas Gregor3257fb52008-12-22 05:46:06 +00002590 // If this is a variadic call, handle args passed through "...".
2591 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002592 VariadicCallType CallType = VariadicFunction;
2593 if (Fn->getType()->isBlockPointerType())
2594 CallType = VariadicBlock; // Block
2595 else if (isa<MemberExpr>(Fn))
2596 CallType = VariadicMethod;
2597
Douglas Gregor3257fb52008-12-22 05:46:06 +00002598 // Promote the arguments (C99 6.5.2.2p7).
2599 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2600 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002601 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002602 Call->setArg(i, Arg);
2603 }
2604 }
2605
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002606 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002607}
2608
Steve Naroff87d58b42007-09-16 03:34:24 +00002609/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002610/// This provides the location of the left/right parens and a list of comma
2611/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002612Action::OwningExprResult
2613Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2614 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002615 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002616 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002617
2618 // Since this might be a postfix expression, get rid of ParenListExprs.
2619 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2620
Anders Carlssonc154a722009-05-01 19:30:39 +00002621 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002622 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002623 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002624 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002625 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002626 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002627
Douglas Gregor3257fb52008-12-22 05:46:06 +00002628 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002629 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002630 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002631 // FIXME: Will need to cache the results of name lookup (including ADL) in
2632 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002633 bool Dependent = false;
2634 if (Fn->isTypeDependent())
2635 Dependent = true;
2636 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2637 Dependent = true;
2638
2639 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002640 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002641 Context.DependentTy, RParenLoc));
2642
2643 // Determine whether this is a call to an object (C++ [over.call.object]).
2644 if (Fn->getType()->isRecordType())
2645 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2646 CommaLocs, RParenLoc));
2647
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002648 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002649 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2650 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2651 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2652 isa<CXXMethodDecl>(MemDecl) ||
2653 (isa<FunctionTemplateDecl>(MemDecl) &&
2654 isa<CXXMethodDecl>(
2655 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002656 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2657 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002658 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002659 }
2660
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002661 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002662 // Also, in C++, keep track of whether we should perform argument-dependent
2663 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002664 Expr *FnExpr = Fn;
2665 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002666 bool HasExplicitTemplateArgs = 0;
2667 const TemplateArgument *ExplicitTemplateArgs = 0;
2668 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002669 while (true) {
2670 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2671 FnExpr = IcExpr->getSubExpr();
2672 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002673 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002674 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002675 ADL = false;
2676 FnExpr = PExpr->getSubExpr();
2677 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002678 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002679 == UnaryOperator::AddrOf) {
2680 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002681 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002682 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2683 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002684 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002685 break;
Mike Stump9afab102009-02-19 03:04:26 +00002686 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002687 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2688 UnqualifiedName = DepName->getName();
2689 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002690 } else if (TemplateIdRefExpr *TemplateIdRef
2691 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2692 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002693 if (!NDecl)
2694 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002695 HasExplicitTemplateArgs = true;
2696 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2697 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2698
2699 // C++ [temp.arg.explicit]p6:
2700 // [Note: For simple function names, argument dependent lookup (3.4.2)
2701 // applies even when the function name is not visible within the
2702 // scope of the call. This is because the call still has the syntactic
2703 // form of a function call (3.4.1). But when a function template with
2704 // explicit template arguments is used, the call does not have the
2705 // correct syntactic form unless there is a function template with
2706 // that name visible at the point of the call. If no such name is
2707 // visible, the call is not syntactically well-formed and
2708 // argument-dependent lookup does not apply. If some such name is
2709 // visible, argument dependent lookup applies and additional function
2710 // templates may be found in other namespaces.
2711 //
2712 // The summary of this paragraph is that, if we get to this point and the
2713 // template-id was not a qualified name, then argument-dependent lookup
2714 // is still possible.
2715 if (TemplateIdRef->getQualifier())
2716 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002717 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002718 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002719 // Any kind of name that does not refer to a declaration (or
2720 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2721 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002722 break;
2723 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002724 }
Mike Stump9afab102009-02-19 03:04:26 +00002725
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002726 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002727 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002728 if (NDecl) {
2729 FDecl = dyn_cast<FunctionDecl>(NDecl);
2730 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002731 FDecl = FunctionTemplate->getTemplatedDecl();
2732 else
Douglas Gregor28857752009-06-30 22:34:41 +00002733 FDecl = dyn_cast<FunctionDecl>(NDecl);
2734 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002735 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002736
Douglas Gregorb60eb752009-06-25 22:08:12 +00002737 if (Ovl || FunctionTemplate ||
2738 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002739 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002740 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002741 ADL = false;
2742
Douglas Gregorfcb19192009-02-11 23:02:49 +00002743 // We don't perform ADL in C.
2744 if (!getLangOptions().CPlusPlus)
2745 ADL = false;
2746
Douglas Gregorb60eb752009-06-25 22:08:12 +00002747 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002748 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2749 HasExplicitTemplateArgs,
2750 ExplicitTemplateArgs,
2751 NumExplicitTemplateArgs,
2752 LParenLoc, Args, NumArgs, CommaLocs,
2753 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002754 if (!FDecl)
2755 return ExprError();
2756
2757 // Update Fn to refer to the actual function selected.
2758 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002759 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002760 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002761 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2762 QDRExpr->getLocation(),
2763 false, false,
2764 QDRExpr->getQualifierRange(),
2765 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002766 else
Mike Stump9afab102009-02-19 03:04:26 +00002767 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002768 Fn->getSourceRange().getBegin());
2769 Fn->Destroy(Context);
2770 Fn = NewFn;
2771 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002772 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002773
2774 // Promote the function operand.
2775 UsualUnaryConversions(Fn);
2776
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002777 // Make the call expr early, before semantic checks. This guarantees cleanup
2778 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002779 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2780 Args, NumArgs,
2781 Context.BoolTy,
2782 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002783
Steve Naroffd6163f32008-09-05 22:11:13 +00002784 const FunctionType *FuncT;
2785 if (!Fn->getType()->isBlockPointerType()) {
2786 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2787 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002788 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002789 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002790 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2791 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002792 FuncT = PT->getPointeeType()->getAsFunctionType();
2793 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002794 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002795 getAsFunctionType();
2796 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002797 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002798 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2799 << Fn->getType() << Fn->getSourceRange());
2800
Eli Friedman83dec9e2009-03-22 22:00:50 +00002801 // Check for a valid return type
2802 if (!FuncT->getResultType()->isVoidType() &&
2803 RequireCompleteType(Fn->getSourceRange().getBegin(),
2804 FuncT->getResultType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002805 PDiag(diag::err_call_incomplete_return)
2806 << TheCall->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002807 return ExprError();
2808
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002809 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002810 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002811
Douglas Gregor4fa58902009-02-26 23:50:07 +00002812 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002813 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002814 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002815 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002816 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002817 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002818
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002819 if (FDecl) {
2820 // Check if we have too few/too many template arguments, based
2821 // on our knowledge of the function definition.
2822 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002823 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002824 const FunctionProtoType *Proto =
2825 Def->getType()->getAsFunctionProtoType();
2826 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2827 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2828 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2829 }
2830 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002831 }
2832
Steve Naroffdb65e052007-08-28 23:30:39 +00002833 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002834 for (unsigned i = 0; i != NumArgs; i++) {
2835 Expr *Arg = Args[i];
2836 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002837 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2838 Arg->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002839 PDiag(diag::err_call_incomplete_argument)
2840 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002841 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002842 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002843 }
Chris Lattner4b009652007-07-25 00:24:17 +00002844 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002845
Douglas Gregor3257fb52008-12-22 05:46:06 +00002846 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2847 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002848 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2849 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002850
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002851 // Check for sentinels
2852 if (NDecl)
2853 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002854
Chris Lattner2e64c072007-08-10 20:18:51 +00002855 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002856 if (FDecl) {
2857 if (CheckFunctionCall(FDecl, TheCall.get()))
2858 return ExprError();
2859
2860 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2861 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2862 } else if (NDecl) {
2863 if (CheckBlockCall(NDecl, TheCall.get()))
2864 return ExprError();
2865 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002866
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002867 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002868}
2869
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002870Action::OwningExprResult
2871Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2872 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002873 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002874 //FIXME: Preserve type source info.
2875 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002876 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002877 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002878 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002879
Eli Friedman8c2173d2008-05-20 05:22:08 +00002880 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002881 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002882 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2883 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002884 } else if (!literalType->isDependentType() &&
2885 RequireCompleteType(LParenLoc, literalType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002886 PDiag(diag::err_typecheck_decl_incomplete_type)
2887 << SourceRange(LParenLoc,
2888 literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002889 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002890
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002891 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002892 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002893 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002894
Chris Lattnere5cb5862008-12-04 23:50:19 +00002895 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002896 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002897 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002898 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002899 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002900 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002901 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002902 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002903}
2904
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002905Action::OwningExprResult
2906Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002907 SourceLocation RBraceLoc) {
2908 unsigned NumInit = initlist.size();
2909 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002910
Steve Naroff0acc9c92007-09-15 18:49:24 +00002911 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002912 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002913
Mike Stump9afab102009-02-19 03:04:26 +00002914 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002915 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002916 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002917 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002918}
2919
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002920/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002921bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002922 CastExpr::CastKind& Kind,
2923 CXXMethodDecl *& ConversionDecl,
2924 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002925 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002926 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2927 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002928
Eli Friedman01e0f652009-08-15 19:02:19 +00002929 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002930
2931 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2932 // type needs to be scalar.
2933 if (castType->isVoidType()) {
2934 // Cast to void allows any expr type.
2935 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002936 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2937 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2938 (castType->isStructureType() || castType->isUnionType())) {
2939 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002940 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002941 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2942 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002943 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002944 } else if (castType->isUnionType()) {
2945 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002946 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002947 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002948 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002949 Field != FieldEnd; ++Field) {
2950 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2951 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2952 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2953 << castExpr->getSourceRange();
2954 break;
2955 }
2956 }
2957 if (Field == FieldEnd)
2958 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2959 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002960 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002961 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002962 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002963 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002964 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002965 }
Mike Stump9afab102009-02-19 03:04:26 +00002966 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002967 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002968 return Diag(castExpr->getLocStart(),
2969 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002970 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00002971 } else if (castType->isExtVectorType()) {
2972 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002973 return true;
2974 } else if (castType->isVectorType()) {
2975 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2976 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00002977 } else if (castExpr->getType()->isVectorType()) {
2978 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2979 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002980 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002981 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002982 } else if (!castType->isArithmeticType()) {
2983 QualType castExprType = castExpr->getType();
2984 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2985 return Diag(castExpr->getLocStart(),
2986 diag::err_cast_pointer_from_non_pointer_int)
2987 << castExprType << castExpr->getSourceRange();
2988 } else if (!castExpr->getType()->isArithmeticType()) {
2989 if (!castType->isIntegralType() && castType->isArithmeticType())
2990 return Diag(castExpr->getLocStart(),
2991 diag::err_cast_pointer_to_non_pointer_int)
2992 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002993 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00002994 if (isa<ObjCSelectorExpr>(castExpr))
2995 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002996 return false;
2997}
2998
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002999bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003000 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003001
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003002 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003003 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003004 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003005 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003006 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003007 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003008 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003009 } else
3010 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003011 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003012 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003013
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003014 return false;
3015}
3016
Nate Begemanbd42e022009-06-26 00:50:28 +00003017bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3018 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3019
Nate Begeman9e063702009-06-27 22:05:55 +00003020 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3021 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003022 if (SrcTy->isVectorType()) {
3023 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3024 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3025 << DestTy << SrcTy << R;
3026 return false;
3027 }
3028
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003029 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003030 // conversion will take place first from scalar to elt type, and then
3031 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003032 if (SrcTy->isPointerType())
3033 return Diag(R.getBegin(),
3034 diag::err_invalid_conversion_between_vector_and_scalar)
3035 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003036 return false;
3037}
3038
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003039Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003040Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003041 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003042 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3043
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003044 assert((Ty != 0) && (Op.get() != 0) &&
3045 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003046
Nate Begemane85f43d2009-08-10 23:49:36 +00003047 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003048 //FIXME: Preserve type source info.
3049 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003050
3051 // If the Expr being casted is a ParenListExpr, handle it specially.
3052 if (isa<ParenListExpr>(castExpr))
3053 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003054 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003055 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003056 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003057 return ExprError();
Nate Begemane85f43d2009-08-10 23:49:36 +00003058
3059 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003060 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003061 Kind, castExpr, castType,
3062 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003063}
3064
Nate Begemane85f43d2009-08-10 23:49:36 +00003065/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3066/// of comma binary operators.
3067Action::OwningExprResult
3068Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3069 Expr *expr = EA.takeAs<Expr>();
3070 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3071 if (!E)
3072 return Owned(expr);
3073
3074 OwningExprResult Result(*this, E->getExpr(0));
3075
3076 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3077 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3078 Owned(E->getExpr(i)));
3079
3080 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3081}
3082
3083Action::OwningExprResult
3084Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3085 SourceLocation RParenLoc, ExprArg Op,
3086 QualType Ty) {
3087 ParenListExpr *PE = (ParenListExpr *)Op.get();
3088
3089 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3090 // then handle it as such.
3091 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3092 if (PE->getNumExprs() == 0) {
3093 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3094 return ExprError();
3095 }
3096
3097 llvm::SmallVector<Expr *, 8> initExprs;
3098 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3099 initExprs.push_back(PE->getExpr(i));
3100
3101 // FIXME: This means that pretty-printing the final AST will produce curly
3102 // braces instead of the original commas.
3103 Op.release();
3104 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3105 initExprs.size(), RParenLoc);
3106 E->setType(Ty);
3107 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3108 Owned(E));
3109 } else {
3110 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3111 // sequence of BinOp comma operators.
3112 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3113 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3114 }
3115}
3116
3117Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3118 SourceLocation R,
3119 MultiExprArg Val) {
3120 unsigned nexprs = Val.size();
3121 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3122 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3123 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3124 return Owned(expr);
3125}
3126
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003127/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3128/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003129/// C99 6.5.15
3130QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3131 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003132 // C++ is sufficiently different to merit its own checker.
3133 if (getLangOptions().CPlusPlus)
3134 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3135
Chris Lattnere2897262009-02-18 04:28:32 +00003136 UsualUnaryConversions(Cond);
3137 UsualUnaryConversions(LHS);
3138 UsualUnaryConversions(RHS);
3139 QualType CondTy = Cond->getType();
3140 QualType LHSTy = LHS->getType();
3141 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003142
3143 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003144 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3145 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3146 << CondTy;
3147 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003148 }
Mike Stump9afab102009-02-19 03:04:26 +00003149
Chris Lattner992ae932008-01-06 22:42:25 +00003150 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003151 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3152 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003153
Chris Lattner992ae932008-01-06 22:42:25 +00003154 // If both operands have arithmetic type, do the usual arithmetic conversions
3155 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003156 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3157 UsualArithmeticConversions(LHS, RHS);
3158 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003159 }
Mike Stump9afab102009-02-19 03:04:26 +00003160
Chris Lattner992ae932008-01-06 22:42:25 +00003161 // If both operands are the same structure or union type, the result is that
3162 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003163 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3164 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003165 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003166 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003167 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003168 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003169 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003170 }
Mike Stump9afab102009-02-19 03:04:26 +00003171
Chris Lattner992ae932008-01-06 22:42:25 +00003172 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003173 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003174 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3175 if (!LHSTy->isVoidType())
3176 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3177 << RHS->getSourceRange();
3178 if (!RHSTy->isVoidType())
3179 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3180 << LHS->getSourceRange();
3181 ImpCastExprToType(LHS, Context.VoidTy);
3182 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003183 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003184 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003185 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3186 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003187 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003188 RHS->isNullPointerConstant(Context)) {
3189 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3190 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003191 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003192 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003193 LHS->isNullPointerConstant(Context)) {
3194 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3195 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003196 }
David Chisnall44663db2009-08-17 16:35:33 +00003197 // Handle things like Class and struct objc_class*. Here we case the result
3198 // to the pseudo-builtin, because that will be implicitly cast back to the
3199 // redefinition type if an attempt is made to access its fields.
3200 if (LHSTy->isObjCClassType() &&
3201 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3202 ImpCastExprToType(RHS, LHSTy);
3203 return LHSTy;
3204 }
3205 if (RHSTy->isObjCClassType() &&
3206 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3207 ImpCastExprToType(LHS, RHSTy);
3208 return RHSTy;
3209 }
3210 // And the same for struct objc_object* / id
3211 if (LHSTy->isObjCIdType() &&
3212 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3213 ImpCastExprToType(RHS, LHSTy);
3214 return LHSTy;
3215 }
3216 if (RHSTy->isObjCIdType() &&
3217 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3218 ImpCastExprToType(LHS, RHSTy);
3219 return RHSTy;
3220 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003221 // Handle block pointer types.
3222 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3223 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3224 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3225 QualType destType = Context.getPointerType(Context.VoidTy);
3226 ImpCastExprToType(LHS, destType);
3227 ImpCastExprToType(RHS, destType);
3228 return destType;
3229 }
3230 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3231 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3232 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003233 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003234 // We have 2 block pointer types.
3235 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3236 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003237 return LHSTy;
3238 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003239 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003240 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3241 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003242
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003243 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3244 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003245 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3246 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3247 // In this situation, we assume void* type. No especially good
3248 // reason, but this is what gcc does, and we do have to pick
3249 // to get a consistent AST.
3250 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3251 ImpCastExprToType(LHS, incompatTy);
3252 ImpCastExprToType(RHS, incompatTy);
3253 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003254 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003255 // The block pointer types are compatible.
3256 ImpCastExprToType(LHS, LHSTy);
3257 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003258 return LHSTy;
3259 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003260 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003261 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003262
3263 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3264 // Two identical object pointer types are always compatible.
3265 return LHSTy;
3266 }
Steve Naroff329ec222009-07-10 23:34:53 +00003267 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3268 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003269 QualType compositeType = LHSTy;
3270
3271 // If both operands are interfaces and either operand can be
3272 // assigned to the other, use that type as the composite
3273 // type. This allows
3274 // xxx ? (A*) a : (B*) b
3275 // where B is a subclass of A.
3276 //
3277 // Additionally, as for assignment, if either type is 'id'
3278 // allow silent coercion. Finally, if the types are
3279 // incompatible then make sure to use 'id' as the composite
3280 // type so the result is acceptable for sending messages to.
3281
3282 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3283 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003284 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003285 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003286 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003287 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003288 } else if ((LHSTy->isObjCQualifiedIdType() ||
3289 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003290 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003291 // Need to handle "id<xx>" explicitly.
3292 // GCC allows qualified id and any Objective-C type to devolve to
3293 // id. Currently localizing to here until clear this should be
3294 // part of ObjCQualifiedIdTypesAreCompatible.
3295 compositeType = Context.getObjCIdType();
3296 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003297 compositeType = Context.getObjCIdType();
3298 } else {
3299 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3300 << LHSTy << RHSTy
3301 << LHS->getSourceRange() << RHS->getSourceRange();
3302 QualType incompatTy = Context.getObjCIdType();
3303 ImpCastExprToType(LHS, incompatTy);
3304 ImpCastExprToType(RHS, incompatTy);
3305 return incompatTy;
3306 }
3307 // The object pointer types are compatible.
3308 ImpCastExprToType(LHS, compositeType);
3309 ImpCastExprToType(RHS, compositeType);
3310 return compositeType;
3311 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003312 // Check Objective-C object pointer types and 'void *'
3313 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003314 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003315 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3316 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3317 QualType destType = Context.getPointerType(destPointee);
3318 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3319 ImpCastExprToType(RHS, destType); // promote to void*
3320 return destType;
3321 }
3322 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3323 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003324 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003325 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3326 QualType destType = Context.getPointerType(destPointee);
3327 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3328 ImpCastExprToType(LHS, destType); // promote to void*
3329 return destType;
3330 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003331 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3332 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3333 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003334 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3335 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003336
3337 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3338 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3339 // Figure out necessary qualifiers (C99 6.5.15p6)
3340 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3341 QualType destType = Context.getPointerType(destPointee);
3342 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3343 ImpCastExprToType(RHS, destType); // promote to void*
3344 return destType;
3345 }
3346 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3347 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3348 QualType destType = Context.getPointerType(destPointee);
3349 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3350 ImpCastExprToType(RHS, destType); // promote to void*
3351 return destType;
3352 }
3353
3354 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3355 // Two identical pointer types are always compatible.
3356 return LHSTy;
3357 }
3358 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3359 rhptee.getUnqualifiedType())) {
3360 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3361 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3362 // In this situation, we assume void* type. No especially good
3363 // reason, but this is what gcc does, and we do have to pick
3364 // to get a consistent AST.
3365 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3366 ImpCastExprToType(LHS, incompatTy);
3367 ImpCastExprToType(RHS, incompatTy);
3368 return incompatTy;
3369 }
3370 // The pointer types are compatible.
3371 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3372 // differently qualified versions of compatible types, the result type is
3373 // a pointer to an appropriately qualified version of the *composite*
3374 // type.
3375 // FIXME: Need to calculate the composite type.
3376 // FIXME: Need to add qualifiers
3377 ImpCastExprToType(LHS, LHSTy);
3378 ImpCastExprToType(RHS, LHSTy);
3379 return LHSTy;
3380 }
3381
3382 // GCC compatibility: soften pointer/integer mismatch.
3383 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3384 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3385 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3386 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3387 return RHSTy;
3388 }
3389 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3390 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3391 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3392 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3393 return LHSTy;
3394 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003395
Chris Lattner992ae932008-01-06 22:42:25 +00003396 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003397 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3398 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003399 return QualType();
3400}
3401
Steve Naroff87d58b42007-09-16 03:34:24 +00003402/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003403/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003404Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3405 SourceLocation ColonLoc,
3406 ExprArg Cond, ExprArg LHS,
3407 ExprArg RHS) {
3408 Expr *CondExpr = (Expr *) Cond.get();
3409 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003410
3411 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3412 // was the condition.
3413 bool isLHSNull = LHSExpr == 0;
3414 if (isLHSNull)
3415 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003416
3417 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003418 RHSExpr, QuestionLoc);
3419 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003420 return ExprError();
3421
3422 Cond.release();
3423 LHS.release();
3424 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003425 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003426 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003427 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003428}
3429
Chris Lattner4b009652007-07-25 00:24:17 +00003430// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003431// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003432// routine is it effectively iqnores the qualifiers on the top level pointee.
3433// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3434// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003435Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003436Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3437 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003438
David Chisnall44663db2009-08-17 16:35:33 +00003439 if ((lhsType->isObjCClassType() &&
3440 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3441 (rhsType->isObjCClassType() &&
3442 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3443 return Compatible;
3444 }
3445
Chris Lattner4b009652007-07-25 00:24:17 +00003446 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003447 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3448 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003449
Chris Lattner4b009652007-07-25 00:24:17 +00003450 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003451 lhptee = Context.getCanonicalType(lhptee);
3452 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003453
Chris Lattner005ed752008-01-04 18:04:52 +00003454 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003455
3456 // C99 6.5.16.1p1: This following citation is common to constraints
3457 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3458 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003459 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003460 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003461 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003462
Mike Stump9afab102009-02-19 03:04:26 +00003463 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3464 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003465 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003466 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003467 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003468 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003469
Chris Lattner4ca3d772008-01-03 22:56:36 +00003470 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003471 assert(rhptee->isFunctionType());
3472 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003473 }
Mike Stump9afab102009-02-19 03:04:26 +00003474
Chris Lattner4ca3d772008-01-03 22:56:36 +00003475 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003476 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003477 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003478
3479 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003480 assert(lhptee->isFunctionType());
3481 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003482 }
Mike Stump9afab102009-02-19 03:04:26 +00003483 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003484 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003485 lhptee = lhptee.getUnqualifiedType();
3486 rhptee = rhptee.getUnqualifiedType();
3487 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3488 // Check if the pointee types are compatible ignoring the sign.
3489 // We explicitly check for char so that we catch "char" vs
3490 // "unsigned char" on systems where "char" is unsigned.
3491 if (lhptee->isCharType()) {
3492 lhptee = Context.UnsignedCharTy;
3493 } else if (lhptee->isSignedIntegerType()) {
3494 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3495 }
3496 if (rhptee->isCharType()) {
3497 rhptee = Context.UnsignedCharTy;
3498 } else if (rhptee->isSignedIntegerType()) {
3499 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3500 }
3501 if (lhptee == rhptee) {
3502 // Types are compatible ignoring the sign. Qualifier incompatibility
3503 // takes priority over sign incompatibility because the sign
3504 // warning can be disabled.
3505 if (ConvTy != Compatible)
3506 return ConvTy;
3507 return IncompatiblePointerSign;
3508 }
3509 // General pointer incompatibility takes priority over qualifiers.
3510 return IncompatiblePointer;
3511 }
Chris Lattner005ed752008-01-04 18:04:52 +00003512 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003513}
3514
Steve Naroff3454b6c2008-09-04 15:10:53 +00003515/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3516/// block pointer types are compatible or whether a block and normal pointer
3517/// are compatible. It is more restrict than comparing two function pointer
3518// types.
Mike Stump9afab102009-02-19 03:04:26 +00003519Sema::AssignConvertType
3520Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003521 QualType rhsType) {
3522 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003523
Steve Naroff3454b6c2008-09-04 15:10:53 +00003524 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003525 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3526 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003527
Steve Naroff3454b6c2008-09-04 15:10:53 +00003528 // make sure we operate on the canonical type
3529 lhptee = Context.getCanonicalType(lhptee);
3530 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003531
Steve Naroff3454b6c2008-09-04 15:10:53 +00003532 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003533
Steve Naroff3454b6c2008-09-04 15:10:53 +00003534 // For blocks we enforce that qualifiers are identical.
3535 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3536 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003537
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003538 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003539 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003540 return ConvTy;
3541}
3542
Mike Stump9afab102009-02-19 03:04:26 +00003543/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3544/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003545/// pointers. Here are some objectionable examples that GCC considers warnings:
3546///
3547/// int a, *pint;
3548/// short *pshort;
3549/// struct foo *pfoo;
3550///
3551/// pint = pshort; // warning: assignment from incompatible pointer type
3552/// a = pint; // warning: assignment makes integer from pointer without a cast
3553/// pint = a; // warning: assignment makes pointer from integer without a cast
3554/// pint = pfoo; // warning: assignment from incompatible pointer type
3555///
3556/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003557/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003558///
Chris Lattner005ed752008-01-04 18:04:52 +00003559Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003560Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003561 // Get canonical types. We're not formatting these types, just comparing
3562 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003563 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3564 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003565
3566 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003567 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003568
David Chisnall44663db2009-08-17 16:35:33 +00003569 if ((lhsType->isObjCClassType() &&
3570 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3571 (rhsType->isObjCClassType() &&
3572 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3573 return Compatible;
3574 }
3575
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003576 // If the left-hand side is a reference type, then we are in a
3577 // (rare!) case where we've allowed the use of references in C,
3578 // e.g., as a parameter type in a built-in function. In this case,
3579 // just make sure that the type referenced is compatible with the
3580 // right-hand side type. The caller is responsible for adjusting
3581 // lhsType so that the resulting expression does not have reference
3582 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003583 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003584 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003585 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003586 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003587 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003588 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3589 // to the same ExtVector type.
3590 if (lhsType->isExtVectorType()) {
3591 if (rhsType->isExtVectorType())
3592 return lhsType == rhsType ? Compatible : Incompatible;
3593 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3594 return Compatible;
3595 }
3596
Nate Begemanc5f0f652008-07-14 18:02:46 +00003597 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003598 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003599 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003600 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003601 if (getLangOptions().LaxVectorConversions &&
3602 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003603 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003604 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003605 }
3606 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003607 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003608
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003609 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003610 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003611
Chris Lattner390564e2008-04-07 06:49:41 +00003612 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003613 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003614 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003615
Chris Lattner390564e2008-04-07 06:49:41 +00003616 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003617 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003618
Steve Naroff8194a542009-07-20 17:56:53 +00003619 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003620 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003621 if (lhsType->isVoidPointerType()) // an exception to the rule.
3622 return Compatible;
3623 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003624 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003625 if (rhsType->getAs<BlockPointerType>()) {
3626 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003627 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003628
3629 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003630 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003631 return Compatible;
3632 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003633 return Incompatible;
3634 }
3635
3636 if (isa<BlockPointerType>(lhsType)) {
3637 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003638 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003639
Steve Naroffa982c712008-09-29 18:10:17 +00003640 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003641 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003642 return Compatible;
3643
Steve Naroff3454b6c2008-09-04 15:10:53 +00003644 if (rhsType->isBlockPointerType())
3645 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003646
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003647 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003648 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003649 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003650 }
Chris Lattner1853da22008-01-04 23:18:45 +00003651 return Incompatible;
3652 }
3653
Steve Naroff329ec222009-07-10 23:34:53 +00003654 if (isa<ObjCObjectPointerType>(lhsType)) {
3655 if (rhsType->isIntegerType())
3656 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003657
3658 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003659 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003660 if (rhsType->isVoidPointerType()) // an exception to the rule.
3661 return Compatible;
3662 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003663 }
3664 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003665 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3666 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003667 if (Context.typesAreCompatible(lhsType, rhsType))
3668 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003669 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3670 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003671 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003672 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003673 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003674 if (RHSPT->getPointeeType()->isVoidType())
3675 return Compatible;
3676 }
3677 // Treat block pointers as objects.
3678 if (rhsType->isBlockPointerType())
3679 return Compatible;
3680 return Incompatible;
3681 }
Chris Lattner390564e2008-04-07 06:49:41 +00003682 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003683 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003684 if (lhsType == Context.BoolTy)
3685 return Compatible;
3686
3687 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003688 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003689
Mike Stump9afab102009-02-19 03:04:26 +00003690 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003691 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003692
3693 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003694 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003695 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003696 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003697 }
Steve Naroff329ec222009-07-10 23:34:53 +00003698 if (isa<ObjCObjectPointerType>(rhsType)) {
3699 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3700 if (lhsType == Context.BoolTy)
3701 return Compatible;
3702
3703 if (lhsType->isIntegerType())
3704 return PointerToInt;
3705
Steve Naroff8194a542009-07-20 17:56:53 +00003706 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003707 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003708 if (lhsType->isVoidPointerType()) // an exception to the rule.
3709 return Compatible;
3710 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003711 }
3712 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003713 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003714 return Compatible;
3715 return Incompatible;
3716 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003717
Chris Lattner1853da22008-01-04 23:18:45 +00003718 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003719 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003720 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003721 }
3722 return Incompatible;
3723}
3724
Douglas Gregor144b06c2009-04-29 22:16:16 +00003725/// \brief Constructs a transparent union from an expression that is
3726/// used to initialize the transparent union.
3727static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3728 QualType UnionType, FieldDecl *Field) {
3729 // Build an initializer list that designates the appropriate member
3730 // of the transparent union.
3731 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3732 &E, 1,
3733 SourceLocation());
3734 Initializer->setType(UnionType);
3735 Initializer->setInitializedFieldInUnion(Field);
3736
3737 // Build a compound literal constructing a value of the transparent
3738 // union type from this initializer list.
3739 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3740 false);
3741}
3742
3743Sema::AssignConvertType
3744Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3745 QualType FromType = rExpr->getType();
3746
3747 // If the ArgType is a Union type, we want to handle a potential
3748 // transparent_union GCC extension.
3749 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003750 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003751 return Incompatible;
3752
3753 // The field to initialize within the transparent union.
3754 RecordDecl *UD = UT->getDecl();
3755 FieldDecl *InitField = 0;
3756 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003757 for (RecordDecl::field_iterator it = UD->field_begin(),
3758 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003759 it != itend; ++it) {
3760 if (it->getType()->isPointerType()) {
3761 // If the transparent union contains a pointer type, we allow:
3762 // 1) void pointer
3763 // 2) null pointer constant
3764 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003765 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003766 ImpCastExprToType(rExpr, it->getType());
3767 InitField = *it;
3768 break;
3769 }
3770
3771 if (rExpr->isNullPointerConstant(Context)) {
3772 ImpCastExprToType(rExpr, it->getType());
3773 InitField = *it;
3774 break;
3775 }
3776 }
3777
3778 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3779 == Compatible) {
3780 InitField = *it;
3781 break;
3782 }
3783 }
3784
3785 if (!InitField)
3786 return Incompatible;
3787
3788 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3789 return Compatible;
3790}
3791
Chris Lattner005ed752008-01-04 18:04:52 +00003792Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003793Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003794 if (getLangOptions().CPlusPlus) {
3795 if (!lhsType->isRecordType()) {
3796 // C++ 5.17p3: If the left operand is not of class type, the
3797 // expression is implicitly converted (C++ 4) to the
3798 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003799 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3800 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003801 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003802 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003803 }
3804
3805 // FIXME: Currently, we fall through and treat C++ classes like C
3806 // structures.
3807 }
3808
Steve Naroffcdee22d2007-11-27 17:58:44 +00003809 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3810 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003811 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003812 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003813 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003814 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003815 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003816 return Compatible;
3817 }
Mike Stump9afab102009-02-19 03:04:26 +00003818
Chris Lattner5f505bf2007-10-16 02:55:40 +00003819 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003820 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003821 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003822 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003823 //
Mike Stump9afab102009-02-19 03:04:26 +00003824 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003825 if (!lhsType->isReferenceType())
3826 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003827
Chris Lattner005ed752008-01-04 18:04:52 +00003828 Sema::AssignConvertType result =
3829 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003830
Steve Naroff0f32f432007-08-24 22:33:52 +00003831 // C99 6.5.16.1p2: The value of the right operand is converted to the
3832 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003833 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3834 // so that we can use references in built-in functions even in C.
3835 // The getNonReferenceType() call makes sure that the resulting expression
3836 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003837 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003838 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003839 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003840}
3841
Chris Lattner1eafdea2008-11-18 01:30:42 +00003842QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003843 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003844 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003845 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003846 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003847}
3848
Mike Stump9afab102009-02-19 03:04:26 +00003849inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003850 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003851 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003852 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003853 QualType lhsType =
3854 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3855 QualType rhsType =
3856 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003857
Nate Begemanc5f0f652008-07-14 18:02:46 +00003858 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003859 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003860 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003861
Nate Begemanc5f0f652008-07-14 18:02:46 +00003862 // Handle the case of a vector & extvector type of the same size and element
3863 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003864 if (getLangOptions().LaxVectorConversions) {
3865 // FIXME: Should we warn here?
3866 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003867 if (const VectorType *RV = rhsType->getAsVectorType())
3868 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003869 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003870 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003871 }
3872 }
3873 }
Mike Stump9afab102009-02-19 03:04:26 +00003874
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003875 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3876 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3877 bool swapped = false;
3878 if (rhsType->isExtVectorType()) {
3879 swapped = true;
3880 std::swap(rex, lex);
3881 std::swap(rhsType, lhsType);
3882 }
3883
Nate Begemanf1695892009-06-28 19:12:57 +00003884 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003885 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3886 QualType EltTy = LV->getElementType();
3887 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3888 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003889 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003890 if (swapped) std::swap(rex, lex);
3891 return lhsType;
3892 }
3893 }
3894 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3895 rhsType->isRealFloatingType()) {
3896 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003897 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003898 if (swapped) std::swap(rex, lex);
3899 return lhsType;
3900 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003901 }
3902 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003903
Nate Begemanf1695892009-06-28 19:12:57 +00003904 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003905 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003906 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003907 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003908 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003909}
3910
Chris Lattner4b009652007-07-25 00:24:17 +00003911inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003912 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003913{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003914 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003915 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003916
Steve Naroff8f708362007-08-24 19:07:16 +00003917 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003918
Chris Lattner4b009652007-07-25 00:24:17 +00003919 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003920 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003921 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003922}
3923
3924inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003925 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003926{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003927 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3928 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3929 return CheckVectorOperands(Loc, lex, rex);
3930 return InvalidOperands(Loc, lex, rex);
3931 }
Chris Lattner4b009652007-07-25 00:24:17 +00003932
Steve Naroff8f708362007-08-24 19:07:16 +00003933 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003934
Chris Lattner4b009652007-07-25 00:24:17 +00003935 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003936 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003937 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003938}
3939
3940inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003941 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003942{
Eli Friedman3cd92882009-03-28 01:22:36 +00003943 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3944 QualType compType = CheckVectorOperands(Loc, lex, rex);
3945 if (CompLHSTy) *CompLHSTy = compType;
3946 return compType;
3947 }
Chris Lattner4b009652007-07-25 00:24:17 +00003948
Eli Friedman3cd92882009-03-28 01:22:36 +00003949 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003950
Chris Lattner4b009652007-07-25 00:24:17 +00003951 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003952 if (lex->getType()->isArithmeticType() &&
3953 rex->getType()->isArithmeticType()) {
3954 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003955 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003956 }
Chris Lattner4b009652007-07-25 00:24:17 +00003957
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003958 // Put any potential pointer into PExp
3959 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00003960 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003961 std::swap(PExp, IExp);
3962
Steve Naroff79ae19a2009-07-14 18:25:06 +00003963 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003964
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003965 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00003966 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00003967
Chris Lattner184f92d2009-04-24 23:50:08 +00003968 // Check for arithmetic on pointers to incomplete types.
3969 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003970 if (getLangOptions().CPlusPlus) {
3971 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003972 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003973 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003974 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003975
3976 // GNU extension: arithmetic on pointer to void
3977 Diag(Loc, diag::ext_gnu_void_ptr)
3978 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003979 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003980 if (getLangOptions().CPlusPlus) {
3981 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3982 << lex->getType() << lex->getSourceRange();
3983 return QualType();
3984 }
3985
3986 // GNU extension: arithmetic on pointer to function
3987 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3988 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00003989 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00003990 // Check if we require a complete type.
3991 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00003992 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00003993 PExp->getType()->isObjCObjectPointerType()) &&
3994 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00003995 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
3996 << PExp->getSourceRange()
3997 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00003998 return QualType();
3999 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004000 // Diagnose bad cases where we step over interface counts.
4001 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4002 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4003 << PointeeTy << PExp->getSourceRange();
4004 return QualType();
4005 }
4006
Eli Friedman3cd92882009-03-28 01:22:36 +00004007 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004008 QualType LHSTy = Context.isPromotableBitField(lex);
4009 if (LHSTy.isNull()) {
4010 LHSTy = lex->getType();
4011 if (LHSTy->isPromotableIntegerType())
4012 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004013 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004014 *CompLHSTy = LHSTy;
4015 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004016 return PExp->getType();
4017 }
4018 }
4019
Chris Lattner1eafdea2008-11-18 01:30:42 +00004020 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004021}
4022
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004023// C99 6.5.6
4024QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004025 SourceLocation Loc, QualType* CompLHSTy) {
4026 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4027 QualType compType = CheckVectorOperands(Loc, lex, rex);
4028 if (CompLHSTy) *CompLHSTy = compType;
4029 return compType;
4030 }
Mike Stump9afab102009-02-19 03:04:26 +00004031
Eli Friedman3cd92882009-03-28 01:22:36 +00004032 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004033
Chris Lattnerf6da2912007-12-09 21:53:25 +00004034 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004035
Chris Lattnerf6da2912007-12-09 21:53:25 +00004036 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004037 if (lex->getType()->isArithmeticType()
4038 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004039 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004040 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004041 }
Steve Naroff329ec222009-07-10 23:34:53 +00004042
Chris Lattnerf6da2912007-12-09 21:53:25 +00004043 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004044 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004045 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004046
Douglas Gregor05e28f62009-03-24 19:52:54 +00004047 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004048
Douglas Gregor05e28f62009-03-24 19:52:54 +00004049 bool ComplainAboutVoid = false;
4050 Expr *ComplainAboutFunc = 0;
4051 if (lpointee->isVoidType()) {
4052 if (getLangOptions().CPlusPlus) {
4053 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4054 << lex->getSourceRange() << rex->getSourceRange();
4055 return QualType();
4056 }
4057
4058 // GNU C extension: arithmetic on pointer to void
4059 ComplainAboutVoid = true;
4060 } else if (lpointee->isFunctionType()) {
4061 if (getLangOptions().CPlusPlus) {
4062 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004063 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004064 return QualType();
4065 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004066
4067 // GNU C extension: arithmetic on pointer to function
4068 ComplainAboutFunc = lex;
4069 } else if (!lpointee->isDependentType() &&
4070 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004071 PDiag(diag::err_typecheck_sub_ptr_object)
4072 << lex->getSourceRange()
4073 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004074 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004075
Chris Lattner184f92d2009-04-24 23:50:08 +00004076 // Diagnose bad cases where we step over interface counts.
4077 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4078 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4079 << lpointee << lex->getSourceRange();
4080 return QualType();
4081 }
4082
Chris Lattnerf6da2912007-12-09 21:53:25 +00004083 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004084 if (rex->getType()->isIntegerType()) {
4085 if (ComplainAboutVoid)
4086 Diag(Loc, diag::ext_gnu_void_ptr)
4087 << lex->getSourceRange() << rex->getSourceRange();
4088 if (ComplainAboutFunc)
4089 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4090 << ComplainAboutFunc->getType()
4091 << ComplainAboutFunc->getSourceRange();
4092
Eli Friedman3cd92882009-03-28 01:22:36 +00004093 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004094 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004095 }
Mike Stump9afab102009-02-19 03:04:26 +00004096
Chris Lattnerf6da2912007-12-09 21:53:25 +00004097 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004098 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004099 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004100
Douglas Gregor05e28f62009-03-24 19:52:54 +00004101 // RHS must be a completely-type object type.
4102 // Handle the GNU void* extension.
4103 if (rpointee->isVoidType()) {
4104 if (getLangOptions().CPlusPlus) {
4105 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4106 << lex->getSourceRange() << rex->getSourceRange();
4107 return QualType();
4108 }
Mike Stump9afab102009-02-19 03:04:26 +00004109
Douglas Gregor05e28f62009-03-24 19:52:54 +00004110 ComplainAboutVoid = true;
4111 } else if (rpointee->isFunctionType()) {
4112 if (getLangOptions().CPlusPlus) {
4113 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004114 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004115 return QualType();
4116 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004117
4118 // GNU extension: arithmetic on pointer to function
4119 if (!ComplainAboutFunc)
4120 ComplainAboutFunc = rex;
4121 } else if (!rpointee->isDependentType() &&
4122 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004123 PDiag(diag::err_typecheck_sub_ptr_object)
4124 << rex->getSourceRange()
4125 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004126 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004127
Eli Friedman143ddc92009-05-16 13:54:38 +00004128 if (getLangOptions().CPlusPlus) {
4129 // Pointee types must be the same: C++ [expr.add]
4130 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4131 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4132 << lex->getType() << rex->getType()
4133 << lex->getSourceRange() << rex->getSourceRange();
4134 return QualType();
4135 }
4136 } else {
4137 // Pointee types must be compatible C99 6.5.6p3
4138 if (!Context.typesAreCompatible(
4139 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4140 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4141 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4142 << lex->getType() << rex->getType()
4143 << lex->getSourceRange() << rex->getSourceRange();
4144 return QualType();
4145 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004146 }
Mike Stump9afab102009-02-19 03:04:26 +00004147
Douglas Gregor05e28f62009-03-24 19:52:54 +00004148 if (ComplainAboutVoid)
4149 Diag(Loc, diag::ext_gnu_void_ptr)
4150 << lex->getSourceRange() << rex->getSourceRange();
4151 if (ComplainAboutFunc)
4152 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4153 << ComplainAboutFunc->getType()
4154 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004155
4156 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004157 return Context.getPointerDiffType();
4158 }
4159 }
Mike Stump9afab102009-02-19 03:04:26 +00004160
Chris Lattner1eafdea2008-11-18 01:30:42 +00004161 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004162}
4163
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004164// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004165QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004166 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004167 // C99 6.5.7p2: Each of the operands shall have integer type.
4168 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004169 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004170
Chris Lattner2c8bff72007-12-12 05:47:28 +00004171 // Shifts don't perform usual arithmetic conversions, they just do integer
4172 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004173 QualType LHSTy = Context.isPromotableBitField(lex);
4174 if (LHSTy.isNull()) {
4175 LHSTy = lex->getType();
4176 if (LHSTy->isPromotableIntegerType())
4177 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004178 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004179 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004180 ImpCastExprToType(lex, LHSTy);
4181
Chris Lattner2c8bff72007-12-12 05:47:28 +00004182 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004183
Ryan Flynnf109fff2009-08-07 16:20:20 +00004184 // Sanity-check shift operands
4185 llvm::APSInt Right;
4186 // Check right/shifter operand
4187 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004188 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004189 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4190 else {
4191 llvm::APInt LeftBits(Right.getBitWidth(),
4192 Context.getTypeSize(lex->getType()));
4193 if (Right.uge(LeftBits))
4194 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4195 }
4196 }
4197
Chris Lattner2c8bff72007-12-12 05:47:28 +00004198 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004199 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004200}
4201
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004202// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004203QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004204 unsigned OpaqueOpc, bool isRelational) {
4205 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4206
Nate Begemanc5f0f652008-07-14 18:02:46 +00004207 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004208 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004209
Chris Lattner254f3bc2007-08-26 01:18:55 +00004210 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004211 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4212 UsualArithmeticConversions(lex, rex);
4213 else {
4214 UsualUnaryConversions(lex);
4215 UsualUnaryConversions(rex);
4216 }
Chris Lattner4b009652007-07-25 00:24:17 +00004217 QualType lType = lex->getType();
4218 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004219
Mike Stumpea3d74e2009-05-07 18:43:07 +00004220 if (!lType->isFloatingType()
4221 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004222 // For non-floating point types, check for self-comparisons of the form
4223 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4224 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004225 // NOTE: Don't warn about comparisons of enum constants. These can arise
4226 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004227 Expr *LHSStripped = lex->IgnoreParens();
4228 Expr *RHSStripped = rex->IgnoreParens();
4229 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4230 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004231 if (DRL->getDecl() == DRR->getDecl() &&
4232 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004233 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004234
4235 if (isa<CastExpr>(LHSStripped))
4236 LHSStripped = LHSStripped->IgnoreParenCasts();
4237 if (isa<CastExpr>(RHSStripped))
4238 RHSStripped = RHSStripped->IgnoreParenCasts();
4239
4240 // Warn about comparisons against a string constant (unless the other
4241 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004242 Expr *literalString = 0;
4243 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004244 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004245 !RHSStripped->isNullPointerConstant(Context)) {
4246 literalString = lex;
4247 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004248 } else if ((isa<StringLiteral>(RHSStripped) ||
4249 isa<ObjCEncodeExpr>(RHSStripped)) &&
4250 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004251 literalString = rex;
4252 literalStringStripped = RHSStripped;
4253 }
4254
4255 if (literalString) {
4256 std::string resultComparison;
4257 switch (Opc) {
4258 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4259 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4260 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4261 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4262 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4263 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4264 default: assert(false && "Invalid comparison operator");
4265 }
4266 Diag(Loc, diag::warn_stringcompare)
4267 << isa<ObjCEncodeExpr>(literalStringStripped)
4268 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004269 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4270 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4271 "strcmp(")
4272 << CodeModificationHint::CreateInsertion(
4273 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004274 resultComparison);
4275 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004276 }
Mike Stump9afab102009-02-19 03:04:26 +00004277
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004278 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004279 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004280
Chris Lattner254f3bc2007-08-26 01:18:55 +00004281 if (isRelational) {
4282 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004283 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004284 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004285 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004286 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004287 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004288 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004289 }
Mike Stump9afab102009-02-19 03:04:26 +00004290
Chris Lattner254f3bc2007-08-26 01:18:55 +00004291 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004292 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004293 }
Mike Stump9afab102009-02-19 03:04:26 +00004294
Chris Lattner22be8422007-08-26 01:10:14 +00004295 bool LHSIsNull = lex->isNullPointerConstant(Context);
4296 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004297
Chris Lattner254f3bc2007-08-26 01:18:55 +00004298 // All of the following pointer related warnings are GCC extensions, except
4299 // when handling null pointer constants. One day, we can consider making them
4300 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004301 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004302 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004303 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004304 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004305 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004306
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004307 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004308 if (LCanPointeeTy == RCanPointeeTy)
4309 return ResultTy;
4310
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004311 // C++ [expr.rel]p2:
4312 // [...] Pointer conversions (4.10) and qualification
4313 // conversions (4.4) are performed on pointer operands (or on
4314 // a pointer operand and a null pointer constant) to bring
4315 // them to their composite pointer type. [...]
4316 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004317 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004318 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004319 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004320 if (T.isNull()) {
4321 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4322 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4323 return QualType();
4324 }
4325
4326 ImpCastExprToType(lex, T);
4327 ImpCastExprToType(rex, T);
4328 return ResultTy;
4329 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004330 // C99 6.5.9p2 and C99 6.5.8p2
4331 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4332 RCanPointeeTy.getUnqualifiedType())) {
4333 // Valid unless a relational comparison of function pointers
4334 if (isRelational && LCanPointeeTy->isFunctionType()) {
4335 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4336 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4337 }
4338 } else if (!isRelational &&
4339 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4340 // Valid unless comparison between non-null pointer and function pointer
4341 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4342 && !LHSIsNull && !RHSIsNull) {
4343 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4344 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4345 }
4346 } else {
4347 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004348 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004349 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004350 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004351 if (LCanPointeeTy != RCanPointeeTy)
4352 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004353 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004354 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004355
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004356 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004357 // Comparison of pointers with null pointer constants and equality
4358 // comparisons of member pointers to null pointer constants.
4359 if (RHSIsNull &&
4360 (lType->isPointerType() ||
4361 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004362 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004363 return ResultTy;
4364 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004365 if (LHSIsNull &&
4366 (rType->isPointerType() ||
4367 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004368 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004369 return ResultTy;
4370 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004371
4372 // Comparison of member pointers.
4373 if (!isRelational &&
4374 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4375 // C++ [expr.eq]p2:
4376 // In addition, pointers to members can be compared, or a pointer to
4377 // member and a null pointer constant. Pointer to member conversions
4378 // (4.11) and qualification conversions (4.4) are performed to bring
4379 // them to a common type. If one operand is a null pointer constant,
4380 // the common type is the type of the other operand. Otherwise, the
4381 // common type is a pointer to member type similar (4.4) to the type
4382 // of one of the operands, with a cv-qualification signature (4.4)
4383 // that is the union of the cv-qualification signatures of the operand
4384 // types.
4385 QualType T = FindCompositePointerType(lex, rex);
4386 if (T.isNull()) {
4387 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4388 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4389 return QualType();
4390 }
4391
4392 ImpCastExprToType(lex, T);
4393 ImpCastExprToType(rex, T);
4394 return ResultTy;
4395 }
4396
4397 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004398 if (lType->isNullPtrType() && rType->isNullPtrType())
4399 return ResultTy;
4400 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004401
Steve Naroff3454b6c2008-09-04 15:10:53 +00004402 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004403 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004404 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4405 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004406
Steve Naroff3454b6c2008-09-04 15:10:53 +00004407 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004408 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004409 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004410 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004411 }
4412 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004413 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004414 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004415 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004416 if (!isRelational
4417 && ((lType->isBlockPointerType() && rType->isPointerType())
4418 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004419 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004420 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004421 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004422 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004423 ->getPointeeType()->isVoidType())))
4424 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4425 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004426 }
4427 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004428 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004429 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004430
Steve Naroff329ec222009-07-10 23:34:53 +00004431 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004432 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004433 const PointerType *LPT = lType->getAs<PointerType>();
4434 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004435 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004436 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004437 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004438 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004439
Steve Naroff030fcda2008-11-17 19:49:16 +00004440 if (!LPtrToVoid && !RPtrToVoid &&
4441 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004442 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004443 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004444 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004445 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004446 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004447 }
Steve Naroff329ec222009-07-10 23:34:53 +00004448 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004449 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004450 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4451 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004452 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004453 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004454 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004455 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004456 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004457 unsigned DiagID = 0;
4458 if (RHSIsNull) {
4459 if (isRelational)
4460 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4461 } else if (isRelational)
4462 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4463 else
4464 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4465
4466 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004467 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004468 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004469 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004470 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004471 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004472 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004473 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004474 unsigned DiagID = 0;
4475 if (LHSIsNull) {
4476 if (isRelational)
4477 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4478 } else if (isRelational)
4479 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4480 else
4481 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004482
Chris Lattner124569f2009-08-23 00:03:44 +00004483 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004484 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004485 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004486 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004487 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004488 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004489 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004490 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004491 if (!isRelational && RHSIsNull
4492 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004493 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004494 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004495 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004496 if (!isRelational && LHSIsNull
4497 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004498 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004499 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004500 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004501 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004502}
4503
Nate Begemanc5f0f652008-07-14 18:02:46 +00004504/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004505/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004506/// like a scalar comparison, a vector comparison produces a vector of integer
4507/// types.
4508QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004509 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004510 bool isRelational) {
4511 // Check to make sure we're operating on vectors of the same type and width,
4512 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004513 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004514 if (vType.isNull())
4515 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004516
Nate Begemanc5f0f652008-07-14 18:02:46 +00004517 QualType lType = lex->getType();
4518 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004519
Nate Begemanc5f0f652008-07-14 18:02:46 +00004520 // For non-floating point types, check for self-comparisons of the form
4521 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4522 // often indicate logic errors in the program.
4523 if (!lType->isFloatingType()) {
4524 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4525 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4526 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004527 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004528 }
Mike Stump9afab102009-02-19 03:04:26 +00004529
Nate Begemanc5f0f652008-07-14 18:02:46 +00004530 // Check for comparisons of floating point operands using != and ==.
4531 if (!isRelational && lType->isFloatingType()) {
4532 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004533 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004534 }
Mike Stump9afab102009-02-19 03:04:26 +00004535
Nate Begemanc5f0f652008-07-14 18:02:46 +00004536 // Return the type for the comparison, which is the same as vector type for
4537 // integer vectors, or an integer type of identical size and number of
4538 // elements for floating point vectors.
4539 if (lType->isIntegerType())
4540 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004541
Nate Begemanc5f0f652008-07-14 18:02:46 +00004542 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004543 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004544 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004545 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004546 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004547 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4548
Mike Stump9afab102009-02-19 03:04:26 +00004549 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004550 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004551 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4552}
4553
Chris Lattner4b009652007-07-25 00:24:17 +00004554inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004555 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004556{
4557 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004558 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004559
Steve Naroff8f708362007-08-24 19:07:16 +00004560 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004561
Chris Lattner4b009652007-07-25 00:24:17 +00004562 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004563 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004564 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004565}
4566
4567inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004568 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004569{
4570 UsualUnaryConversions(lex);
4571 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004572
Eli Friedmanbea3f842008-05-13 20:16:47 +00004573 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004574 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004575 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004576}
4577
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004578/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4579/// is a read-only property; return true if so. A readonly property expression
4580/// depends on various declarations and thus must be treated specially.
4581///
Mike Stump9afab102009-02-19 03:04:26 +00004582static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004583{
4584 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4585 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4586 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4587 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004588 if (const ObjCObjectPointerType *OPT =
4589 BaseType->getAsObjCInterfacePointerType())
4590 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4591 if (S.isPropertyReadonly(PDecl, IFace))
4592 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004593 }
4594 }
4595 return false;
4596}
4597
Chris Lattner4c2642c2008-11-18 01:22:49 +00004598/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4599/// emit an error and return true. If so, return false.
4600static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004601 SourceLocation OrigLoc = Loc;
4602 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4603 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004604 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4605 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004606 if (IsLV == Expr::MLV_Valid)
4607 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004608
Chris Lattner4c2642c2008-11-18 01:22:49 +00004609 unsigned Diag = 0;
4610 bool NeedType = false;
4611 switch (IsLV) { // C99 6.5.16p2
4612 default: assert(0 && "Unknown result from isModifiableLvalue!");
4613 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004614 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004615 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4616 NeedType = true;
4617 break;
Mike Stump9afab102009-02-19 03:04:26 +00004618 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004619 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4620 NeedType = true;
4621 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004622 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004623 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4624 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004625 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004626 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4627 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004628 case Expr::MLV_IncompleteType:
4629 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004630 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00004631 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4632 << E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004633 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004634 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4635 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004636 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004637 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4638 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004639 case Expr::MLV_ReadonlyProperty:
4640 Diag = diag::error_readonly_property_assignment;
4641 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004642 case Expr::MLV_NoSetterProperty:
4643 Diag = diag::error_nosetter_property_assignment;
4644 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004645 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004646
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004647 SourceRange Assign;
4648 if (Loc != OrigLoc)
4649 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004650 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004651 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004652 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004653 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004654 return true;
4655}
4656
4657
4658
4659// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004660QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4661 SourceLocation Loc,
4662 QualType CompoundType) {
4663 // Verify that LHS is a modifiable lvalue, and emit error if not.
4664 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004665 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004666
4667 QualType LHSType = LHS->getType();
4668 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004669
Chris Lattner005ed752008-01-04 18:04:52 +00004670 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004671 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004672 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004673 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004674 // Special case of NSObject attributes on c-style pointer types.
4675 if (ConvTy == IncompatiblePointer &&
4676 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004677 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004678 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004679 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004680 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004681
Chris Lattner34c85082008-08-21 18:04:13 +00004682 // If the RHS is a unary plus or minus, check to see if they = and + are
4683 // right next to each other. If so, the user may have typo'd "x =+ 4"
4684 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004685 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004686 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4687 RHSCheck = ICE->getSubExpr();
4688 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4689 if ((UO->getOpcode() == UnaryOperator::Plus ||
4690 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004691 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004692 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004693 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4694 // And there is a space or other character before the subexpr of the
4695 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004696 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4697 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004698 Diag(Loc, diag::warn_not_compound_assign)
4699 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4700 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004701 }
Chris Lattner34c85082008-08-21 18:04:13 +00004702 }
4703 } else {
4704 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004705 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004706 }
Chris Lattner005ed752008-01-04 18:04:52 +00004707
Chris Lattner1eafdea2008-11-18 01:30:42 +00004708 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4709 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004710 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004711
Chris Lattner4b009652007-07-25 00:24:17 +00004712 // C99 6.5.16p3: The type of an assignment expression is the type of the
4713 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004714 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004715 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4716 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004717 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004718 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004719 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004720}
4721
Chris Lattner1eafdea2008-11-18 01:30:42 +00004722// C99 6.5.17
4723QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004724 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004725 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004726
4727 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4728 // incomplete in C++).
4729
Chris Lattner1eafdea2008-11-18 01:30:42 +00004730 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004731}
4732
4733/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4734/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004735QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4736 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004737 if (Op->isTypeDependent())
4738 return Context.DependentTy;
4739
Chris Lattnere65182c2008-11-21 07:05:48 +00004740 QualType ResType = Op->getType();
4741 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004742
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004743 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4744 // Decrement of bool is not allowed.
4745 if (!isInc) {
4746 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4747 return QualType();
4748 }
4749 // Increment of bool sets it to true, but is deprecated.
4750 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4751 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004752 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004753 } else if (ResType->isAnyPointerType()) {
4754 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004755
Chris Lattnere65182c2008-11-21 07:05:48 +00004756 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004757 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004758 if (getLangOptions().CPlusPlus) {
4759 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4760 << Op->getSourceRange();
4761 return QualType();
4762 }
4763
4764 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004765 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004766 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004767 if (getLangOptions().CPlusPlus) {
4768 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4769 << Op->getType() << Op->getSourceRange();
4770 return QualType();
4771 }
4772
4773 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004774 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004775 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004776 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4777 << Op->getSourceRange()
4778 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004779 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004780 // Diagnose bad cases where we step over interface counts.
4781 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4782 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4783 << PointeeTy << Op->getSourceRange();
4784 return QualType();
4785 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004786 } else if (ResType->isComplexType()) {
4787 // C99 does not support ++/-- on complex types, we allow as an extension.
4788 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004789 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004790 } else {
4791 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004792 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004793 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004794 }
Mike Stump9afab102009-02-19 03:04:26 +00004795 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004796 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004797 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004798 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004799 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004800}
4801
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004802/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004803/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004804/// where the declaration is needed for type checking. We only need to
4805/// handle cases when the expression references a function designator
4806/// or is an lvalue. Here are some examples:
4807/// - &(x) => x
4808/// - &*****f => f for f a function designator.
4809/// - &s.xx => s
4810/// - &s.zz[1].yy -> s, if zz is an array
4811/// - *(x + 1) -> x, if x is an array
4812/// - &"123"[2] -> 0
4813/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004814static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004815 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004816 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004817 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004818 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004819 case Stmt::MemberExprClass:
Douglas Gregore399ad42009-08-26 22:36:53 +00004820 case Stmt::CXXQualifiedMemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004821 // If this is an arrow operator, the address is an offset from
4822 // the base's value, so the object the base refers to is
4823 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004824 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004825 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004826 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004827 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004828 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004829 // FIXME: This code shouldn't be necessary! We should catch the implicit
4830 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004831 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4832 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4833 if (ICE->getSubExpr()->getType()->isArrayType())
4834 return getPrimaryDecl(ICE->getSubExpr());
4835 }
4836 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004837 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004838 case Stmt::UnaryOperatorClass: {
4839 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004840
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004841 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004842 case UnaryOperator::Real:
4843 case UnaryOperator::Imag:
4844 case UnaryOperator::Extension:
4845 return getPrimaryDecl(UO->getSubExpr());
4846 default:
4847 return 0;
4848 }
4849 }
Chris Lattner4b009652007-07-25 00:24:17 +00004850 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004851 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004852 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004853 // If the result of an implicit cast is an l-value, we care about
4854 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004855 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004856 default:
4857 return 0;
4858 }
4859}
4860
4861/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004862/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004863/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004864/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004865/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004866/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004867/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004868QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004869 // Make sure to ignore parentheses in subsequent checks
4870 op = op->IgnoreParens();
4871
Douglas Gregore6be68a2008-12-17 22:52:20 +00004872 if (op->isTypeDependent())
4873 return Context.DependentTy;
4874
Steve Naroff9c6c3592008-01-13 17:10:08 +00004875 if (getLangOptions().C99) {
4876 // Implement C99-only parts of addressof rules.
4877 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4878 if (uOp->getOpcode() == UnaryOperator::Deref)
4879 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4880 // (assuming the deref expression is valid).
4881 return uOp->getSubExpr()->getType();
4882 }
4883 // Technically, there should be a check for array subscript
4884 // expressions here, but the result of one is always an lvalue anyway.
4885 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004886 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004887 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004888
Eli Friedman14ab4c42009-05-16 23:27:50 +00004889 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4890 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004891 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004892 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004893 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004894 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4895 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004896 return QualType();
4897 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004898 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004899 // The operand cannot be a bit-field
4900 Diag(OpLoc, diag::err_typecheck_address_of)
4901 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004902 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004903 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4904 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004905 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004906 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004907 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004908 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004909 } else if (isa<ObjCPropertyRefExpr>(op)) {
4910 // cannot take address of a property expression.
4911 Diag(OpLoc, diag::err_typecheck_address_of)
4912 << "property expression" << op->getSourceRange();
4913 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004914 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004915 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004916 // with the register storage-class specifier.
4917 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4918 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004919 Diag(OpLoc, diag::err_typecheck_address_of)
4920 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004921 return QualType();
4922 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004923 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4924 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004925 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004926 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004927 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004928 // Could be a pointer to member, though, if there is an explicit
4929 // scope qualifier for the class.
4930 if (isa<QualifiedDeclRefExpr>(op)) {
4931 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004932 if (Ctx && Ctx->isRecord()) {
4933 if (FD->getType()->isReferenceType()) {
4934 Diag(OpLoc,
4935 diag::err_cannot_form_pointer_to_member_of_reference_type)
4936 << FD->getDeclName() << FD->getType();
4937 return QualType();
4938 }
4939
Sebastian Redl0c9da212009-02-03 20:19:35 +00004940 return Context.getMemberPointerType(op->getType(),
4941 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004942 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004943 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004944 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004945 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004946 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004947 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4948 return Context.getMemberPointerType(op->getType(),
4949 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4950 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004951 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004952 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004953
Eli Friedman14ab4c42009-05-16 23:27:50 +00004954 if (lval == Expr::LV_IncompleteVoidType) {
4955 // Taking the address of a void variable is technically illegal, but we
4956 // allow it in cases which are otherwise valid.
4957 // Example: "extern void x; void* y = &x;".
4958 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4959 }
4960
Chris Lattner4b009652007-07-25 00:24:17 +00004961 // If the operand has type "type", the result has type "pointer to type".
4962 return Context.getPointerType(op->getType());
4963}
4964
Chris Lattnerda5c0872008-11-23 09:13:29 +00004965QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004966 if (Op->isTypeDependent())
4967 return Context.DependentTy;
4968
Chris Lattnerda5c0872008-11-23 09:13:29 +00004969 UsualUnaryConversions(Op);
4970 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004971
Chris Lattnerda5c0872008-11-23 09:13:29 +00004972 // Note that per both C89 and C99, this is always legal, even if ptype is an
4973 // incomplete type or void. It would be possible to warn about dereferencing
4974 // a void pointer, but it's completely well-defined, and such a warning is
4975 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004976 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004977 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004978
Steve Naroff329ec222009-07-10 23:34:53 +00004979 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4980 return OPT->getPointeeType();
4981
Chris Lattner77d52da2008-11-20 06:06:08 +00004982 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004983 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004984 return QualType();
4985}
4986
4987static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4988 tok::TokenKind Kind) {
4989 BinaryOperator::Opcode Opc;
4990 switch (Kind) {
4991 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004992 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4993 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004994 case tok::star: Opc = BinaryOperator::Mul; break;
4995 case tok::slash: Opc = BinaryOperator::Div; break;
4996 case tok::percent: Opc = BinaryOperator::Rem; break;
4997 case tok::plus: Opc = BinaryOperator::Add; break;
4998 case tok::minus: Opc = BinaryOperator::Sub; break;
4999 case tok::lessless: Opc = BinaryOperator::Shl; break;
5000 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5001 case tok::lessequal: Opc = BinaryOperator::LE; break;
5002 case tok::less: Opc = BinaryOperator::LT; break;
5003 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5004 case tok::greater: Opc = BinaryOperator::GT; break;
5005 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5006 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5007 case tok::amp: Opc = BinaryOperator::And; break;
5008 case tok::caret: Opc = BinaryOperator::Xor; break;
5009 case tok::pipe: Opc = BinaryOperator::Or; break;
5010 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5011 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5012 case tok::equal: Opc = BinaryOperator::Assign; break;
5013 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5014 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5015 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5016 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5017 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5018 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5019 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5020 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5021 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5022 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5023 case tok::comma: Opc = BinaryOperator::Comma; break;
5024 }
5025 return Opc;
5026}
5027
5028static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5029 tok::TokenKind Kind) {
5030 UnaryOperator::Opcode Opc;
5031 switch (Kind) {
5032 default: assert(0 && "Unknown unary op!");
5033 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5034 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5035 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5036 case tok::star: Opc = UnaryOperator::Deref; break;
5037 case tok::plus: Opc = UnaryOperator::Plus; break;
5038 case tok::minus: Opc = UnaryOperator::Minus; break;
5039 case tok::tilde: Opc = UnaryOperator::Not; break;
5040 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005041 case tok::kw___real: Opc = UnaryOperator::Real; break;
5042 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5043 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5044 }
5045 return Opc;
5046}
5047
Douglas Gregord7f915e2008-11-06 23:29:22 +00005048/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5049/// operator @p Opc at location @c TokLoc. This routine only supports
5050/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005051Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5052 unsigned Op,
5053 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005054 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005055 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005056 // The following two variables are used for compound assignment operators
5057 QualType CompLHSTy; // Type of LHS after promotions for computation
5058 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005059
5060 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005061 case BinaryOperator::Assign:
5062 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5063 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005064 case BinaryOperator::PtrMemD:
5065 case BinaryOperator::PtrMemI:
5066 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5067 Opc == BinaryOperator::PtrMemI);
5068 break;
5069 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005070 case BinaryOperator::Div:
5071 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5072 break;
5073 case BinaryOperator::Rem:
5074 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5075 break;
5076 case BinaryOperator::Add:
5077 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5078 break;
5079 case BinaryOperator::Sub:
5080 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5081 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005082 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005083 case BinaryOperator::Shr:
5084 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5085 break;
5086 case BinaryOperator::LE:
5087 case BinaryOperator::LT:
5088 case BinaryOperator::GE:
5089 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005090 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005091 break;
5092 case BinaryOperator::EQ:
5093 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005094 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005095 break;
5096 case BinaryOperator::And:
5097 case BinaryOperator::Xor:
5098 case BinaryOperator::Or:
5099 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5100 break;
5101 case BinaryOperator::LAnd:
5102 case BinaryOperator::LOr:
5103 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5104 break;
5105 case BinaryOperator::MulAssign:
5106 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005107 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5108 CompLHSTy = CompResultTy;
5109 if (!CompResultTy.isNull())
5110 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005111 break;
5112 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005113 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5114 CompLHSTy = CompResultTy;
5115 if (!CompResultTy.isNull())
5116 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005117 break;
5118 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005119 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5120 if (!CompResultTy.isNull())
5121 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005122 break;
5123 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005124 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5125 if (!CompResultTy.isNull())
5126 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005127 break;
5128 case BinaryOperator::ShlAssign:
5129 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005130 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5131 CompLHSTy = CompResultTy;
5132 if (!CompResultTy.isNull())
5133 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005134 break;
5135 case BinaryOperator::AndAssign:
5136 case BinaryOperator::XorAssign:
5137 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005138 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5139 CompLHSTy = CompResultTy;
5140 if (!CompResultTy.isNull())
5141 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005142 break;
5143 case BinaryOperator::Comma:
5144 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5145 break;
5146 }
5147 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005148 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005149 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005150 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5151 else
5152 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005153 CompLHSTy, CompResultTy,
5154 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005155}
5156
Chris Lattner4b009652007-07-25 00:24:17 +00005157// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005158Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5159 tok::TokenKind Kind,
5160 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005161 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005162 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005163
Steve Naroff87d58b42007-09-16 03:34:24 +00005164 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5165 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005166
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005167 if (getLangOptions().CPlusPlus &&
5168 (lhs->getType()->isOverloadableType() ||
5169 rhs->getType()->isOverloadableType())) {
5170 // Find all of the overloaded operators visible from this
5171 // point. We perform both an operator-name lookup from the local
5172 // scope and an argument-dependent lookup based on the types of
5173 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005174 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005175 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5176 if (OverOp != OO_None) {
5177 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5178 Functions);
5179 Expr *Args[2] = { lhs, rhs };
5180 DeclarationName OpName
5181 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5182 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005183 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005184
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005185 // Build the (potentially-overloaded, potentially-dependent)
5186 // binary operation.
5187 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005188 }
5189
Douglas Gregord7f915e2008-11-06 23:29:22 +00005190 // Build a built-in binary operation.
5191 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005192}
5193
Douglas Gregorc78182d2009-03-13 23:49:33 +00005194Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5195 unsigned OpcIn,
5196 ExprArg InputArg) {
5197 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005198
Mike Stumpe127ae32009-05-16 07:39:55 +00005199 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005200 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005201 QualType resultType;
5202 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005203 case UnaryOperator::OffsetOf:
5204 assert(false && "Invalid unary operator");
5205 break;
5206
Chris Lattner4b009652007-07-25 00:24:17 +00005207 case UnaryOperator::PreInc:
5208 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005209 case UnaryOperator::PostInc:
5210 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005211 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005212 Opc == UnaryOperator::PreInc ||
5213 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005214 break;
Mike Stump9afab102009-02-19 03:04:26 +00005215 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005216 resultType = CheckAddressOfOperand(Input, OpLoc);
5217 break;
Mike Stump9afab102009-02-19 03:04:26 +00005218 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005219 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005220 resultType = CheckIndirectionOperand(Input, OpLoc);
5221 break;
5222 case UnaryOperator::Plus:
5223 case UnaryOperator::Minus:
5224 UsualUnaryConversions(Input);
5225 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005226 if (resultType->isDependentType())
5227 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005228 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5229 break;
5230 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5231 resultType->isEnumeralType())
5232 break;
5233 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5234 Opc == UnaryOperator::Plus &&
5235 resultType->isPointerType())
5236 break;
5237
Sebastian Redl8b769972009-01-19 00:08:26 +00005238 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5239 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005240 case UnaryOperator::Not: // bitwise complement
5241 UsualUnaryConversions(Input);
5242 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005243 if (resultType->isDependentType())
5244 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005245 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5246 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5247 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005248 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005249 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005250 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005251 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5252 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005253 break;
5254 case UnaryOperator::LNot: // logical negation
5255 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5256 DefaultFunctionArrayConversion(Input);
5257 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005258 if (resultType->isDependentType())
5259 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005260 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005261 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5262 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005263 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005264 // In C++, it's bool. C++ 5.3.1p8
5265 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005266 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005267 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005268 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005269 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005270 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005271 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005272 resultType = Input->getType();
5273 break;
5274 }
5275 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005276 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005277
5278 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005279 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005280}
5281
Douglas Gregorc78182d2009-03-13 23:49:33 +00005282// Unary Operators. 'Tok' is the token for the operator.
5283Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5284 tok::TokenKind Op, ExprArg input) {
5285 Expr *Input = (Expr*)input.get();
5286 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5287
5288 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5289 // Find all of the overloaded operators visible from this
5290 // point. We perform both an operator-name lookup from the local
5291 // scope and an argument-dependent lookup based on the types of
5292 // the arguments.
5293 FunctionSet Functions;
5294 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5295 if (OverOp != OO_None) {
5296 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5297 Functions);
5298 DeclarationName OpName
5299 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5300 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5301 }
5302
5303 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5304 }
5305
5306 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5307}
5308
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005309/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005310Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5311 SourceLocation LabLoc,
5312 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005313 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005314 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005315
Daniel Dunbar879788d2008-08-04 16:51:22 +00005316 // If we haven't seen this label yet, create a forward reference. It
5317 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005318 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005319 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005320
Chris Lattner4b009652007-07-25 00:24:17 +00005321 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005322 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5323 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005324}
5325
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005326Sema::OwningExprResult
5327Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5328 SourceLocation RPLoc) { // "({..})"
5329 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005330 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5331 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5332
Eli Friedmanbc941e12009-01-24 23:09:00 +00005333 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005334 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005335 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005336
Chris Lattner4b009652007-07-25 00:24:17 +00005337 // FIXME: there are a variety of strange constraints to enforce here, for
5338 // example, it is not possible to goto into a stmt expression apparently.
5339 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005340
Chris Lattner4b009652007-07-25 00:24:17 +00005341 // If there are sub stmts in the compound stmt, take the type of the last one
5342 // as the type of the stmtexpr.
5343 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005344
Chris Lattner200964f2008-07-26 19:51:01 +00005345 if (!Compound->body_empty()) {
5346 Stmt *LastStmt = Compound->body_back();
5347 // If LastStmt is a label, skip down through into the body.
5348 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5349 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005350
Chris Lattner200964f2008-07-26 19:51:01 +00005351 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005352 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005353 }
Mike Stump9afab102009-02-19 03:04:26 +00005354
Eli Friedman2b128322009-03-23 00:24:07 +00005355 // FIXME: Check that expression type is complete/non-abstract; statement
5356 // expressions are not lvalues.
5357
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005358 substmt.release();
5359 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005360}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005361
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005362Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5363 SourceLocation BuiltinLoc,
5364 SourceLocation TypeLoc,
5365 TypeTy *argty,
5366 OffsetOfComponent *CompPtr,
5367 unsigned NumComponents,
5368 SourceLocation RPLoc) {
5369 // FIXME: This function leaks all expressions in the offset components on
5370 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005371 // FIXME: Preserve type source info.
5372 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005373 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005374
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005375 bool Dependent = ArgTy->isDependentType();
5376
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005377 // We must have at least one component that refers to the type, and the first
5378 // one is known to be a field designator. Verify that the ArgTy represents
5379 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005380 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005381 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005382
Eli Friedman2b128322009-03-23 00:24:07 +00005383 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5384 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005385
Eli Friedman342d9432009-02-27 06:44:11 +00005386 // Otherwise, create a null pointer as the base, and iteratively process
5387 // the offsetof designators.
5388 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5389 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005390 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005391 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005392
Chris Lattnerb37522e2007-08-31 21:49:13 +00005393 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5394 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005395 // FIXME: This diagnostic isn't actually visible because the location is in
5396 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005397 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005398 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5399 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005400
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005401 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005402 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005403
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005404 // FIXME: Dependent case loses a lot of information here. And probably
5405 // leaks like a sieve.
5406 for (unsigned i = 0; i != NumComponents; ++i) {
5407 const OffsetOfComponent &OC = CompPtr[i];
5408 if (OC.isBrackets) {
5409 // Offset of an array sub-field. TODO: Should we allow vector elements?
5410 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5411 if (!AT) {
5412 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005413 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5414 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005415 }
5416
5417 // FIXME: C++: Verify that operator[] isn't overloaded.
5418
Eli Friedman342d9432009-02-27 06:44:11 +00005419 // Promote the array so it looks more like a normal array subscript
5420 // expression.
5421 DefaultFunctionArrayConversion(Res);
5422
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005423 // C99 6.5.2.1p1
5424 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005425 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005426 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005427 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005428 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005429 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005430
5431 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5432 OC.LocEnd);
5433 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005434 }
Mike Stump9afab102009-02-19 03:04:26 +00005435
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005436 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005437 if (!RC) {
5438 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005439 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5440 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005441 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005442
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005443 // Get the decl corresponding to this.
5444 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005445 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005446 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005447 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5448 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5449 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005450 DidWarnAboutNonPOD = true;
5451 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005452 }
5453
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005454 FieldDecl *MemberDecl
5455 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5456 LookupMemberName)
5457 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005458 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005459 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005460 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5461 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005462
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005463 // FIXME: C++: Verify that MemberDecl isn't a static field.
5464 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005465 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005466 Res = BuildAnonymousStructUnionMemberReference(
5467 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005468 } else {
5469 // MemberDecl->getType() doesn't get the right qualifiers, but it
5470 // doesn't matter here.
5471 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5472 MemberDecl->getType().getNonReferenceType());
5473 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005474 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005475 }
Mike Stump9afab102009-02-19 03:04:26 +00005476
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005477 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5478 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005479}
5480
5481
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005482Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5483 TypeTy *arg1,TypeTy *arg2,
5484 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005485 // FIXME: Preserve type source info.
5486 QualType argT1 = GetTypeFromParser(arg1);
5487 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005488
Steve Naroff63bad2d2007-08-01 22:05:33 +00005489 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005490
Douglas Gregore6211502009-05-19 22:28:02 +00005491 if (getLangOptions().CPlusPlus) {
5492 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5493 << SourceRange(BuiltinLoc, RPLoc);
5494 return ExprError();
5495 }
5496
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005497 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5498 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005499}
5500
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005501Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5502 ExprArg cond,
5503 ExprArg expr1, ExprArg expr2,
5504 SourceLocation RPLoc) {
5505 Expr *CondExpr = static_cast<Expr*>(cond.get());
5506 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5507 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005508
Steve Naroff93c53012007-08-03 21:21:27 +00005509 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5510
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005511 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005512 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005513 resType = Context.DependentTy;
5514 } else {
5515 // The conditional expression is required to be a constant expression.
5516 llvm::APSInt condEval(32);
5517 SourceLocation ExpLoc;
5518 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005519 return ExprError(Diag(ExpLoc,
5520 diag::err_typecheck_choose_expr_requires_constant)
5521 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005522
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005523 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5524 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5525 }
5526
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005527 cond.release(); expr1.release(); expr2.release();
5528 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5529 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005530}
5531
Steve Naroff52a81c02008-09-03 18:15:37 +00005532//===----------------------------------------------------------------------===//
5533// Clang Extensions.
5534//===----------------------------------------------------------------------===//
5535
5536/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005537void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005538 // Analyze block parameters.
5539 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005540
Steve Naroff52a81c02008-09-03 18:15:37 +00005541 // Add BSI to CurBlock.
5542 BSI->PrevBlockInfo = CurBlock;
5543 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005544
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005545 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005546 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005547 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005548 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005549 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5550 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005551
Steve Naroff52059382008-10-10 01:28:17 +00005552 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005553 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005554}
5555
Mike Stumpc1fddff2009-02-04 22:31:32 +00005556void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005557 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005558
5559 if (ParamInfo.getNumTypeObjects() == 0
5560 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005561 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005562 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5563
Mike Stump458287d2009-04-28 01:10:27 +00005564 if (T->isArrayType()) {
5565 Diag(ParamInfo.getSourceRange().getBegin(),
5566 diag::err_block_returns_array);
5567 return;
5568 }
5569
Mike Stumpc1fddff2009-02-04 22:31:32 +00005570 // The parameter list is optional, if there was none, assume ().
5571 if (!T->isFunctionType())
5572 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5573
5574 CurBlock->hasPrototype = true;
5575 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005576 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005577 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005578 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005579 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005580 // FIXME: remove the attribute.
5581 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005582 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5583
5584 // Do not allow returning a objc interface by-value.
5585 if (RetTy->isObjCInterfaceType()) {
5586 Diag(ParamInfo.getSourceRange().getBegin(),
5587 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5588 return;
5589 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005590 return;
5591 }
5592
Steve Naroff52a81c02008-09-03 18:15:37 +00005593 // Analyze arguments to block.
5594 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5595 "Not a function declarator!");
5596 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005597
Steve Naroff52059382008-10-10 01:28:17 +00005598 CurBlock->hasPrototype = FTI.hasPrototype;
5599 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005600
Steve Naroff52a81c02008-09-03 18:15:37 +00005601 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5602 // no arguments, not a function that takes a single void argument.
5603 if (FTI.hasPrototype &&
5604 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005605 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5606 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005607 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005608 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005609 } else if (FTI.hasPrototype) {
5610 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005611 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005612 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005613 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005614 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005615 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005616 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005617 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005618 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5619 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5620 // If this has an identifier, add it to the scope stack.
5621 if ((*AI)->getIdentifier())
5622 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005623
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005624 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005625 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005626 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005627 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005628 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005629 // FIXME: remove the attribute.
5630 }
5631
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005632 // Analyze the return type.
5633 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5634 QualType RetTy = T->getAsFunctionType()->getResultType();
5635
5636 // Do not allow returning a objc interface by-value.
5637 if (RetTy->isObjCInterfaceType()) {
5638 Diag(ParamInfo.getSourceRange().getBegin(),
5639 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5640 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005641 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005642}
5643
5644/// ActOnBlockError - If there is an error parsing a block, this callback
5645/// is invoked to pop the information about the block from the action impl.
5646void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5647 // Ensure that CurBlock is deleted.
5648 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005649
Chris Lattnere7765e12009-04-19 05:28:12 +00005650 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5651
Steve Naroff52a81c02008-09-03 18:15:37 +00005652 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005653 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005654 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005655 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005656}
5657
5658/// ActOnBlockStmtExpr - This is called when the body of a block statement
5659/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005660Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5661 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005662 // If blocks are disabled, emit an error.
5663 if (!LangOpts.Blocks)
5664 Diag(CaretLoc, diag::err_blocks_disable);
5665
Steve Naroff52a81c02008-09-03 18:15:37 +00005666 // Ensure that CurBlock is deleted.
5667 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005668
Steve Naroff52059382008-10-10 01:28:17 +00005669 PopDeclContext();
5670
Steve Naroff52a81c02008-09-03 18:15:37 +00005671 // Pop off CurBlock, handle nested blocks.
5672 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005673
Steve Naroff52a81c02008-09-03 18:15:37 +00005674 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005675 if (!BSI->ReturnType.isNull())
5676 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005677
Steve Naroff52a81c02008-09-03 18:15:37 +00005678 llvm::SmallVector<QualType, 8> ArgTypes;
5679 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5680 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005681
Mike Stump8e288f42009-07-28 22:04:01 +00005682 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005683 QualType BlockTy;
5684 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005685 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5686 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005687 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005688 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005689 BSI->isVariadic, 0, false, false, 0, 0,
5690 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005691
Eli Friedman2b128322009-03-23 00:24:07 +00005692 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005693 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005694 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005695
Chris Lattnere7765e12009-04-19 05:28:12 +00005696 // If needed, diagnose invalid gotos and switches in the block.
5697 if (CurFunctionNeedsScopeChecking)
5698 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5699 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5700
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005701 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005702 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005703 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5704 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005705}
5706
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005707Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5708 ExprArg expr, TypeTy *type,
5709 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005710 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005711 Expr *E = static_cast<Expr*>(expr.get());
5712 Expr *OrigExpr = E;
5713
Anders Carlsson36760332007-10-15 20:28:48 +00005714 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005715
5716 // Get the va_list type
5717 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005718 if (VaListType->isArrayType()) {
5719 // Deal with implicit array decay; for example, on x86-64,
5720 // va_list is an array, but it's supposed to decay to
5721 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005722 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005723 // Make sure the input expression also decays appropriately.
5724 UsualUnaryConversions(E);
5725 } else {
5726 // Otherwise, the va_list argument must be an l-value because
5727 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005728 if (!E->isTypeDependent() &&
5729 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005730 return ExprError();
5731 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005732
Douglas Gregor25990972009-05-19 23:10:31 +00005733 if (!E->isTypeDependent() &&
5734 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005735 return ExprError(Diag(E->getLocStart(),
5736 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005737 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005738 }
Mike Stump9afab102009-02-19 03:04:26 +00005739
Eli Friedman2b128322009-03-23 00:24:07 +00005740 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005741 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005742
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005743 expr.release();
5744 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5745 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005746}
5747
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005748Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005749 // The type of __null will be int or long, depending on the size of
5750 // pointers on the target.
5751 QualType Ty;
5752 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5753 Ty = Context.IntTy;
5754 else
5755 Ty = Context.LongTy;
5756
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005757 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005758}
5759
Chris Lattner005ed752008-01-04 18:04:52 +00005760bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5761 SourceLocation Loc,
5762 QualType DstType, QualType SrcType,
5763 Expr *SrcExpr, const char *Flavor) {
5764 // Decode the result (notice that AST's are still created for extensions).
5765 bool isInvalid = false;
5766 unsigned DiagKind;
5767 switch (ConvTy) {
5768 default: assert(0 && "Unknown conversion type");
5769 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005770 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005771 DiagKind = diag::ext_typecheck_convert_pointer_int;
5772 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005773 case IntToPointer:
5774 DiagKind = diag::ext_typecheck_convert_int_pointer;
5775 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005776 case IncompatiblePointer:
5777 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5778 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005779 case IncompatiblePointerSign:
5780 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5781 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005782 case FunctionVoidPointer:
5783 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5784 break;
5785 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005786 // If the qualifiers lost were because we were applying the
5787 // (deprecated) C++ conversion from a string literal to a char*
5788 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5789 // Ideally, this check would be performed in
5790 // CheckPointerTypesForAssignment. However, that would require a
5791 // bit of refactoring (so that the second argument is an
5792 // expression, rather than a type), which should be done as part
5793 // of a larger effort to fix CheckPointerTypesForAssignment for
5794 // C++ semantics.
5795 if (getLangOptions().CPlusPlus &&
5796 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5797 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005798 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5799 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005800 case IntToBlockPointer:
5801 DiagKind = diag::err_int_to_block_pointer;
5802 break;
5803 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005804 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005805 break;
Steve Naroff19608432008-10-14 22:18:38 +00005806 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005807 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005808 // it can give a more specific diagnostic.
5809 DiagKind = diag::warn_incompatible_qualified_id;
5810 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005811 case IncompatibleVectors:
5812 DiagKind = diag::warn_incompatible_vectors;
5813 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005814 case Incompatible:
5815 DiagKind = diag::err_typecheck_convert_incompatible;
5816 isInvalid = true;
5817 break;
5818 }
Mike Stump9afab102009-02-19 03:04:26 +00005819
Chris Lattner271d4c22008-11-24 05:29:24 +00005820 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5821 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005822 return isInvalid;
5823}
Anders Carlssond5201b92008-11-30 19:50:32 +00005824
Chris Lattnereec8ae22009-04-25 21:59:05 +00005825bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005826 llvm::APSInt ICEResult;
5827 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5828 if (Result)
5829 *Result = ICEResult;
5830 return false;
5831 }
5832
Anders Carlssond5201b92008-11-30 19:50:32 +00005833 Expr::EvalResult EvalResult;
5834
Mike Stump9afab102009-02-19 03:04:26 +00005835 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005836 EvalResult.HasSideEffects) {
5837 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5838
5839 if (EvalResult.Diag) {
5840 // We only show the note if it's not the usual "invalid subexpression"
5841 // or if it's actually in a subexpression.
5842 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5843 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5844 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5845 }
Mike Stump9afab102009-02-19 03:04:26 +00005846
Anders Carlssond5201b92008-11-30 19:50:32 +00005847 return true;
5848 }
5849
Eli Friedmance329412009-04-25 22:26:58 +00005850 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5851 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005852
Eli Friedmance329412009-04-25 22:26:58 +00005853 if (EvalResult.Diag &&
5854 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5855 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005856
Anders Carlssond5201b92008-11-30 19:50:32 +00005857 if (Result)
5858 *Result = EvalResult.Val.getInt();
5859 return false;
5860}
Douglas Gregor98189262009-06-19 23:52:42 +00005861
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005862Sema::ExpressionEvaluationContext
5863Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5864 // Introduce a new set of potentially referenced declarations to the stack.
5865 if (NewContext == PotentiallyPotentiallyEvaluated)
5866 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5867
5868 std::swap(ExprEvalContext, NewContext);
5869 return NewContext;
5870}
5871
5872void
5873Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5874 ExpressionEvaluationContext NewContext) {
5875 ExprEvalContext = NewContext;
5876
5877 if (OldContext == PotentiallyPotentiallyEvaluated) {
5878 // Mark any remaining declarations in the current position of the stack
5879 // as "referenced". If they were not meant to be referenced, semantic
5880 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5881 PotentiallyReferencedDecls RemainingDecls;
5882 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5883 PotentiallyReferencedDeclStack.pop_back();
5884
5885 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5886 IEnd = RemainingDecls.end();
5887 I != IEnd; ++I)
5888 MarkDeclarationReferenced(I->first, I->second);
5889 }
5890}
Douglas Gregor98189262009-06-19 23:52:42 +00005891
5892/// \brief Note that the given declaration was referenced in the source code.
5893///
5894/// This routine should be invoke whenever a given declaration is referenced
5895/// in the source code, and where that reference occurred. If this declaration
5896/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5897/// C99 6.9p3), then the declaration will be marked as used.
5898///
5899/// \param Loc the location where the declaration was referenced.
5900///
5901/// \param D the declaration that has been referenced by the source code.
5902void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5903 assert(D && "No declaration?");
5904
Douglas Gregorcad27f62009-06-22 23:06:13 +00005905 if (D->isUsed())
5906 return;
5907
Douglas Gregor98189262009-06-19 23:52:42 +00005908 // Mark a parameter declaration "used", regardless of whether we're in a
5909 // template or not.
5910 if (isa<ParmVarDecl>(D))
5911 D->setUsed(true);
5912
5913 // Do not mark anything as "used" within a dependent context; wait for
5914 // an instantiation.
5915 if (CurContext->isDependentContext())
5916 return;
5917
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005918 switch (ExprEvalContext) {
5919 case Unevaluated:
5920 // We are in an expression that is not potentially evaluated; do nothing.
5921 return;
5922
5923 case PotentiallyEvaluated:
5924 // We are in a potentially-evaluated expression, so this declaration is
5925 // "used"; handle this below.
5926 break;
5927
5928 case PotentiallyPotentiallyEvaluated:
5929 // We are in an expression that may be potentially evaluated; queue this
5930 // declaration reference until we know whether the expression is
5931 // potentially evaluated.
5932 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5933 return;
5934 }
5935
Douglas Gregor98189262009-06-19 23:52:42 +00005936 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005937 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005938 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005939 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5940 if (!Constructor->isUsed())
5941 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005942 } else if (Constructor->isImplicit() &&
5943 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005944 if (!Constructor->isUsed())
5945 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5946 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005947 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5948 if (Destructor->isImplicit() && !Destructor->isUsed())
5949 DefineImplicitDestructor(Loc, Destructor);
5950
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005951 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5952 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5953 MethodDecl->getOverloadedOperator() == OO_Equal) {
5954 if (!MethodDecl->isUsed())
5955 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5956 }
5957 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00005958 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005959 // Implicit instantiation of function templates and member functions of
5960 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00005961 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005962 // FIXME: distinguish between implicit instantiations of function
5963 // templates and explicit specializations (the latter don't get
5964 // instantiated, naturally).
5965 if (Function->getInstantiatedFromMemberFunction() ||
5966 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00005967 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00005968 }
5969
5970
Douglas Gregor98189262009-06-19 23:52:42 +00005971 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00005972 Function->setUsed(true);
5973 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00005974 }
Douglas Gregor98189262009-06-19 23:52:42 +00005975
5976 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00005977 // Implicit instantiation of static data members of class templates.
5978 // FIXME: distinguish between implicit instantiations (which we need to
5979 // actually instantiate) and explicit specializations.
5980 if (Var->isStaticDataMember() &&
5981 Var->getInstantiatedFromStaticDataMember())
5982 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
5983
Douglas Gregor98189262009-06-19 23:52:42 +00005984 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00005985
Douglas Gregor98189262009-06-19 23:52:42 +00005986 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00005987 return;
5988}
Douglas Gregor98189262009-06-19 23:52:42 +00005989}
5990