blob: df94f20af7dfa19e12c58bfb8c53109b99a78e9a [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.
Anders Carlsson4355a392009-08-30 00:54:35 +0000792 if (SS && !SS->isEmpty()) {
793 DiagnoseMissingMember(Loc, Name,
794 (NestedNameSpecifier *)SS->getScopeRep(),
795 SS->getRange());
796 return ExprError();
797 } else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000798 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000799 return ExprError(Diag(Loc, diag::err_undeclared_use)
800 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000801 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000802 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000803 }
804 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000805
806 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
807 // Warn about constructs like:
808 // if (void *X = foo()) { ... } else { X }.
809 // In the else block, the pointer is always false.
810
811 // FIXME: In a template instantiation, we don't have scope
812 // information to check this property.
813 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
814 Scope *CheckS = S;
815 while (CheckS) {
816 if (CheckS->isWithinElse() &&
817 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
818 if (Var->getType()->isBooleanType())
819 ExprError(Diag(Loc, diag::warn_value_always_false)
820 << Var->getDeclName());
821 else
822 ExprError(Diag(Loc, diag::warn_value_always_zero)
823 << Var->getDeclName());
824 break;
825 }
826
827 // Move up one more control parent to check again.
828 CheckS = CheckS->getControlParent();
829 if (CheckS)
830 CheckS = CheckS->getParent();
831 }
832 }
833 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
834 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
835 // C99 DR 316 says that, if a function type comes from a
836 // function definition (without a prototype), that type is only
837 // used for checking compatibility. Therefore, when referencing
838 // the function, we pretend that we don't have the full function
839 // type.
840 if (DiagnoseUseOfDecl(Func, Loc))
841 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000842
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000843 QualType T = Func->getType();
844 QualType NoProtoType = T;
845 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
846 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
847 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
848 }
849 }
850
851 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
852}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000853/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000854bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000855Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
856 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
857 if (CXXRecordDecl *RD =
858 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
859 QualType DestType =
860 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000861 if (DestType->isDependentType() || From->getType()->isDependentType())
862 return false;
863 QualType FromRecordType = From->getType();
864 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000865 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000866 DestType = Context.getPointerType(DestType);
867 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000868 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000869 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
870 CheckDerivedToBaseConversion(FromRecordType,
871 DestRecordType,
872 From->getSourceRange().getBegin(),
873 From->getSourceRange()))
874 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000875 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
876 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000877 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000878 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000879}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000880
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000881/// \brief Build a MemberExpr AST node.
Douglas Gregore399ad42009-08-26 22:36:53 +0000882static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
883 const CXXScopeSpec *SS, NamedDecl *Member,
884 SourceLocation Loc, QualType Ty) {
885 if (SS && SS->isSet())
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000886 return MemberExpr::Create(C, Base, isArrow,
887 (NestedNameSpecifier *)SS->getScopeRep(),
888 SS->getRange(), Member, Loc, Ty);
Douglas Gregore399ad42009-08-26 22:36:53 +0000889
890 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
891}
892
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000893/// \brief Complete semantic analysis for a reference to the given declaration.
894Sema::OwningExprResult
895Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
896 bool HasTrailingLParen,
897 const CXXScopeSpec *SS,
898 bool isAddressOfOperand) {
899 assert(D && "Cannot refer to a NULL declaration");
900 DeclarationName Name = D->getDeclName();
901
Sebastian Redl0c9da212009-02-03 20:19:35 +0000902 // If this is an expression of the form &Class::member, don't build an
903 // implicit member ref, because we want a pointer to the member in general,
904 // not any specific instance's member.
905 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000906 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000907 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000908 QualType DType;
909 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
910 DType = FD->getType().getNonReferenceType();
911 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
912 DType = Method->getType();
913 } else if (isa<OverloadedFunctionDecl>(D)) {
914 DType = Context.OverloadTy;
915 }
916 // Could be an inner type. That's diagnosed below, so ignore it here.
917 if (!DType.isNull()) {
918 // The pointer is type- and value-dependent if it points into something
919 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000920 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000921 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000922 }
923 }
924 }
925
Douglas Gregor723d3332009-01-07 00:43:41 +0000926 // We may have found a field within an anonymous union or struct
927 // (C++ [class.union]).
928 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
929 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
930 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000931
Douglas Gregor3257fb52008-12-22 05:46:06 +0000932 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
933 if (!MD->isStatic()) {
934 // C++ [class.mfct.nonstatic]p2:
935 // [...] if name lookup (3.4.1) resolves the name in the
936 // id-expression to a nonstatic nontype member of class X or of
937 // a base class of X, the id-expression is transformed into a
938 // class member access expression (5.2.5) using (*this) (9.3.2)
939 // as the postfix-expression to the left of the '.' operator.
940 DeclContext *Ctx = 0;
941 QualType MemberType;
942 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
943 Ctx = FD->getDeclContext();
944 MemberType = FD->getType();
945
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000946 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000947 MemberType = RefType->getPointeeType();
948 else if (!FD->isMutable()) {
949 unsigned combinedQualifiers
950 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
951 MemberType = MemberType.getQualifiedType(combinedQualifiers);
952 }
953 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
954 if (!Method->isStatic()) {
955 Ctx = Method->getParent();
956 MemberType = Method->getType();
957 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000958 } else if (FunctionTemplateDecl *FunTmpl
959 = dyn_cast<FunctionTemplateDecl>(D)) {
960 if (CXXMethodDecl *Method
961 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
962 if (!Method->isStatic()) {
963 Ctx = Method->getParent();
964 MemberType = Context.OverloadTy;
965 }
966 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000967 } else if (OverloadedFunctionDecl *Ovl
968 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000969 // FIXME: We need an abstraction for iterating over one or more function
970 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000971 for (OverloadedFunctionDecl::function_iterator
972 Func = Ovl->function_begin(),
973 FuncEnd = Ovl->function_end();
974 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000975 CXXMethodDecl *DMethod = 0;
976 if (FunctionTemplateDecl *FunTmpl
977 = dyn_cast<FunctionTemplateDecl>(*Func))
978 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
979 else
980 DMethod = dyn_cast<CXXMethodDecl>(*Func);
981
982 if (DMethod && !DMethod->isStatic()) {
983 Ctx = DMethod->getDeclContext();
984 MemberType = Context.OverloadTy;
985 break;
986 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000987 }
988 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000989
990 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000991 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
992 QualType ThisType = Context.getTagDeclType(MD->getParent());
993 if ((Context.getCanonicalType(CtxType)
994 == Context.getCanonicalType(ThisType)) ||
995 IsDerivedFrom(ThisType, CtxType)) {
996 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000997 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000998 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +0000999 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001000 if (PerformObjectMemberConversion(This, D))
1001 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001002 if (DiagnoseUseOfDecl(D, Loc))
1003 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00001004 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1005 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001006 }
1007 }
1008 }
1009 }
1010
Douglas Gregor8acb7272008-12-11 16:49:14 +00001011 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001012 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1013 if (MD->isStatic())
1014 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001015 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1016 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001017 }
1018
Douglas Gregor3257fb52008-12-22 05:46:06 +00001019 // Any other ways we could have found the field in a well-formed
1020 // program would have been turned into implicit member expressions
1021 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001022 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1023 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001024 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001025
Chris Lattner4b009652007-07-25 00:24:17 +00001026 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001027 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001028 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001029 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001030 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001031 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001032
Steve Naroffd6163f32008-09-05 22:11:13 +00001033 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001034 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001035 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1036 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001037 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001038 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1039 false, false, SS);
Anders Carlsson89908542009-08-29 01:06:32 +00001040 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
1041 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1042 /*TypeDependent=*/true,
1043 /*ValueDependent=*/true, SS);
1044
Steve Naroffd6163f32008-09-05 22:11:13 +00001045 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001046
Douglas Gregoraa57e862009-02-18 21:56:37 +00001047 // Check whether this declaration can be used. Note that we suppress
1048 // this check when we're going to perform argument-dependent lookup
1049 // on this function name, because this might not be the function
1050 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001051 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1052 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001053 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1054 return ExprError();
1055
Steve Naroffd6163f32008-09-05 22:11:13 +00001056 // Only create DeclRefExpr's for valid Decl's.
1057 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001058 return ExprError();
1059
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001060 // If the identifier reference is inside a block, and it refers to a value
1061 // that is outside the block, create a BlockDeclRefExpr instead of a
1062 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1063 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001064 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001065 // We do not do this for things like enum constants, global variables, etc,
1066 // as they do not get snapshotted.
1067 //
1068 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001069 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001070 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001071 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001072 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001073 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001074 // This is to record that a 'const' was actually synthesize and added.
1075 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001076 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001077
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001078 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001079 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1080 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001081 }
1082 // If this reference is not in a block or if the referenced variable is
1083 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001084
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001085 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001086 bool ValueDependent = false;
1087 if (getLangOptions().CPlusPlus) {
1088 // C++ [temp.dep.expr]p3:
1089 // An id-expression is type-dependent if it contains:
1090 // - an identifier that was declared with a dependent type,
1091 if (VD->getType()->isDependentType())
1092 TypeDependent = true;
1093 // - FIXME: a template-id that is dependent,
1094 // - a conversion-function-id that specifies a dependent type,
1095 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1096 Name.getCXXNameType()->isDependentType())
1097 TypeDependent = true;
1098 // - a nested-name-specifier that contains a class-name that
1099 // names a dependent type.
1100 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001101 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001102 DC; DC = DC->getParent()) {
1103 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001104 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001105 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1106 if (Context.getTypeDeclType(Record)->isDependentType()) {
1107 TypeDependent = true;
1108 break;
1109 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001110 }
1111 }
1112 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001113
Douglas Gregora5d84612008-12-10 20:57:37 +00001114 // C++ [temp.dep.constexpr]p2:
1115 //
1116 // An identifier is value-dependent if it is:
1117 // - a name declared with a dependent type,
1118 if (TypeDependent)
1119 ValueDependent = true;
1120 // - the name of a non-type template parameter,
1121 else if (isa<NonTypeTemplateParmDecl>(VD))
1122 ValueDependent = true;
1123 // - a constant with integral or enumeration type and is
1124 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001125 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1126 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1127 Dcl->getInit()) {
1128 ValueDependent = Dcl->getInit()->isValueDependent();
1129 }
1130 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001131 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001132
Anders Carlsson4571d812009-06-24 00:10:43 +00001133 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1134 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001135}
1136
Sebastian Redlcd883f72009-01-18 18:53:16 +00001137Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1138 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001139 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001140
Chris Lattner4b009652007-07-25 00:24:17 +00001141 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001142 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001143 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1144 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1145 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001146 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001147
Chris Lattner7e637512008-01-12 08:14:25 +00001148 // Pre-defined identifiers are of type char[x], where x is the length of the
1149 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001150 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001151 if (FunctionDecl *FD = getCurFunctionDecl())
1152 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001153 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1154 Length = MD->getSynthesizedMethodSize();
1155 else {
1156 Diag(Loc, diag::ext_predef_outside_function);
1157 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1158 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1159 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001160
1161
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001162 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001163 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001164 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001165 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001166}
1167
Sebastian Redlcd883f72009-01-18 18:53:16 +00001168Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001169 llvm::SmallString<16> CharBuffer;
1170 CharBuffer.resize(Tok.getLength());
1171 const char *ThisTokBegin = &CharBuffer[0];
1172 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001173
Chris Lattner4b009652007-07-25 00:24:17 +00001174 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1175 Tok.getLocation(), PP);
1176 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001177 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001178
1179 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1180
Sebastian Redl75324932009-01-20 22:23:13 +00001181 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1182 Literal.isWide(),
1183 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001184}
1185
Sebastian Redlcd883f72009-01-18 18:53:16 +00001186Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1187 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001188 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1189 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001190 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001191 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001192 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001193 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001194 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001195
Chris Lattner4b009652007-07-25 00:24:17 +00001196 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001197 // Add padding so that NumericLiteralParser can overread by one character.
1198 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001199 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001200
Chris Lattner4b009652007-07-25 00:24:17 +00001201 // Get the spelling of the token, which eliminates trigraphs, etc.
1202 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001203
Chris Lattner4b009652007-07-25 00:24:17 +00001204 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1205 Tok.getLocation(), PP);
1206 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001207 return ExprError();
1208
Chris Lattner1de66eb2007-08-26 03:42:43 +00001209 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001210
Chris Lattner1de66eb2007-08-26 03:42:43 +00001211 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001212 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001213 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001214 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001215 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001216 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001217 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001218 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001219
1220 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1221
Ted Kremenekddedbe22007-11-29 00:56:49 +00001222 // isExact will be set by GetFloatValue().
1223 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001224 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1225 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001226
Chris Lattner1de66eb2007-08-26 03:42:43 +00001227 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001228 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001229 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001230 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001231
Neil Booth7421e9c2007-08-29 22:00:19 +00001232 // long long is a C99 feature.
1233 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001234 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001235 Diag(Tok.getLocation(), diag::ext_longlong);
1236
Chris Lattner4b009652007-07-25 00:24:17 +00001237 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001238 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001239
Chris Lattner4b009652007-07-25 00:24:17 +00001240 if (Literal.GetIntegerValue(ResultVal)) {
1241 // If this value didn't fit into uintmax_t, warn and force to ull.
1242 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001243 Ty = Context.UnsignedLongLongTy;
1244 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001245 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001246 } else {
1247 // If this value fits into a ULL, try to figure out what else it fits into
1248 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001249
Chris Lattner4b009652007-07-25 00:24:17 +00001250 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1251 // be an unsigned int.
1252 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1253
1254 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001255 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001256 if (!Literal.isLong && !Literal.isLongLong) {
1257 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001258 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001259
Chris Lattner4b009652007-07-25 00:24:17 +00001260 // Does it fit in a unsigned int?
1261 if (ResultVal.isIntN(IntSize)) {
1262 // Does it fit in a signed int?
1263 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001264 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001265 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001266 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001267 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001268 }
Chris Lattner4b009652007-07-25 00:24:17 +00001269 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001270
Chris Lattner4b009652007-07-25 00:24:17 +00001271 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001272 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001273 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001274
Chris Lattner4b009652007-07-25 00:24:17 +00001275 // Does it fit in a unsigned long?
1276 if (ResultVal.isIntN(LongSize)) {
1277 // Does it fit in a signed long?
1278 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001279 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001280 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001281 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001282 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001283 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001284 }
1285
Chris Lattner4b009652007-07-25 00:24:17 +00001286 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001287 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001288 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001289
Chris Lattner4b009652007-07-25 00:24:17 +00001290 // Does it fit in a unsigned long long?
1291 if (ResultVal.isIntN(LongLongSize)) {
1292 // Does it fit in a signed long long?
1293 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001294 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001295 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001296 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001297 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001298 }
1299 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001300
Chris Lattner4b009652007-07-25 00:24:17 +00001301 // If we still couldn't decide a type, we probably have something that
1302 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001303 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001304 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001305 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001306 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001307 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001308
Chris Lattnere4068872008-05-09 05:59:00 +00001309 if (ResultVal.getBitWidth() != Width)
1310 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001311 }
Sebastian Redl75324932009-01-20 22:23:13 +00001312 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001313 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001314
Chris Lattner1de66eb2007-08-26 03:42:43 +00001315 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1316 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001317 Res = new (Context) ImaginaryLiteral(Res,
1318 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001319
1320 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001321}
1322
Sebastian Redlcd883f72009-01-18 18:53:16 +00001323Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1324 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001325 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001326 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001327 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001328}
1329
1330/// The UsualUnaryConversions() function is *not* called by this routine.
1331/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001332bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001333 SourceLocation OpLoc,
1334 const SourceRange &ExprRange,
1335 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001336 if (exprType->isDependentType())
1337 return false;
1338
Chris Lattner4b009652007-07-25 00:24:17 +00001339 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001340 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001341 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001342 if (isSizeof)
1343 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1344 return false;
1345 }
1346
Chris Lattner95933c12009-04-24 00:30:45 +00001347 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001348 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001349 Diag(OpLoc, diag::ext_sizeof_void_type)
1350 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001351 return false;
1352 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001353
Chris Lattner95933c12009-04-24 00:30:45 +00001354 if (RequireCompleteType(OpLoc, exprType,
1355 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssona21e7872009-08-26 23:45:07 +00001356 PDiag(diag::err_alignof_incomplete_type)
1357 << ExprRange))
Chris Lattner95933c12009-04-24 00:30:45 +00001358 return true;
1359
1360 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001361 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001362 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001363 << exprType << isSizeof << ExprRange;
1364 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001365 }
1366
Chris Lattner95933c12009-04-24 00:30:45 +00001367 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001368}
1369
Chris Lattner8d9f7962009-01-24 20:17:12 +00001370bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1371 const SourceRange &ExprRange) {
1372 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001373
Chris Lattner8d9f7962009-01-24 20:17:12 +00001374 // alignof decl is always ok.
1375 if (isa<DeclRefExpr>(E))
1376 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001377
1378 // Cannot know anything else if the expression is dependent.
1379 if (E->isTypeDependent())
1380 return false;
1381
Douglas Gregor531434b2009-05-02 02:18:30 +00001382 if (E->getBitField()) {
1383 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1384 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001385 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001386
1387 // Alignment of a field access is always okay, so long as it isn't a
1388 // bit-field.
1389 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001390 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001391 return false;
1392
Chris Lattner8d9f7962009-01-24 20:17:12 +00001393 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1394}
1395
Douglas Gregor396f1142009-03-13 21:01:28 +00001396/// \brief Build a sizeof or alignof expression given a type operand.
1397Action::OwningExprResult
1398Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1399 bool isSizeOf, SourceRange R) {
1400 if (T.isNull())
1401 return ExprError();
1402
1403 if (!T->isDependentType() &&
1404 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1405 return ExprError();
1406
1407 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1408 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1409 Context.getSizeType(), OpLoc,
1410 R.getEnd()));
1411}
1412
1413/// \brief Build a sizeof or alignof expression given an expression
1414/// operand.
1415Action::OwningExprResult
1416Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1417 bool isSizeOf, SourceRange R) {
1418 // Verify that the operand is valid.
1419 bool isInvalid = false;
1420 if (E->isTypeDependent()) {
1421 // Delay type-checking for type-dependent expressions.
1422 } else if (!isSizeOf) {
1423 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001424 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001425 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1426 isInvalid = true;
1427 } else {
1428 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1429 }
1430
1431 if (isInvalid)
1432 return ExprError();
1433
1434 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1435 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1436 Context.getSizeType(), OpLoc,
1437 R.getEnd()));
1438}
1439
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001440/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1441/// the same for @c alignof and @c __alignof
1442/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001443Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001444Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1445 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001446 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001447 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001448
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001449 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001450 // FIXME: Preserve type source info.
1451 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001452 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1453 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001454
Douglas Gregor396f1142009-03-13 21:01:28 +00001455 // Get the end location.
1456 Expr *ArgEx = (Expr *)TyOrEx;
1457 Action::OwningExprResult Result
1458 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1459
1460 if (Result.isInvalid())
1461 DeleteExpr(ArgEx);
1462
1463 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001464}
1465
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001466QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001467 if (V->isTypeDependent())
1468 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001469
Chris Lattnera16e42d2007-08-26 05:39:26 +00001470 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001471 if (const ComplexType *CT = V->getType()->getAsComplexType())
1472 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001473
1474 // Otherwise they pass through real integer and floating point types here.
1475 if (V->getType()->isArithmeticType())
1476 return V->getType();
1477
1478 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001479 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1480 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001481 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001482}
1483
1484
Chris Lattner4b009652007-07-25 00:24:17 +00001485
Sebastian Redl8b769972009-01-19 00:08:26 +00001486Action::OwningExprResult
1487Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1488 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001489 // Since this might be a postfix expression, get rid of ParenListExprs.
1490 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001491 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001492
Chris Lattner4b009652007-07-25 00:24:17 +00001493 UnaryOperator::Opcode Opc;
1494 switch (Kind) {
1495 default: assert(0 && "Unknown unary op!");
1496 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1497 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1498 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001499
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001500 if (getLangOptions().CPlusPlus &&
1501 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1502 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001503 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001504 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1505
1506 // C++ [over.inc]p1:
1507 //
1508 // [...] If the function is a member function with one
1509 // parameter (which shall be of type int) or a non-member
1510 // function with two parameters (the second of which shall be
1511 // of type int), it defines the postfix increment operator ++
1512 // for objects of that type. When the postfix increment is
1513 // called as a result of using the ++ operator, the int
1514 // argument will have value zero.
1515 Expr *Args[2] = {
1516 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001517 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1518 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001519 };
1520
1521 // Build the candidate set for overloading
1522 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001523 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001524
1525 // Perform overload resolution.
1526 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001527 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001528 case OR_Success: {
1529 // We found a built-in operator or an overloaded operator.
1530 FunctionDecl *FnDecl = Best->Function;
1531
1532 if (FnDecl) {
1533 // We matched an overloaded operator. Build a call to that
1534 // operator.
1535
1536 // Convert the arguments.
1537 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1538 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001539 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001540 } else {
1541 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001542 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001543 FnDecl->getParamDecl(0)->getType(),
1544 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001545 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001546 }
1547
1548 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001549 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001550 = FnDecl->getType()->getAsFunctionType()->getResultType();
1551 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001552
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001553 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001554 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001555 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001556 UsualUnaryConversions(FnExpr);
1557
Sebastian Redl8b769972009-01-19 00:08:26 +00001558 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001559 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001560 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1561 Args, 2, ResultTy,
1562 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001563 } else {
1564 // We matched a built-in operator. Convert the arguments, then
1565 // break out so that we will build the appropriate built-in
1566 // operator node.
1567 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1568 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001569 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001570
1571 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001572 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001573 }
1574
1575 case OR_No_Viable_Function:
1576 // No viable function; fall through to handling this as a
1577 // built-in operator, which will produce an error message for us.
1578 break;
1579
1580 case OR_Ambiguous:
1581 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1582 << UnaryOperator::getOpcodeStr(Opc)
1583 << Arg->getSourceRange();
1584 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001585 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001586
1587 case OR_Deleted:
1588 Diag(OpLoc, diag::err_ovl_deleted_oper)
1589 << Best->Function->isDeleted()
1590 << UnaryOperator::getOpcodeStr(Opc)
1591 << Arg->getSourceRange();
1592 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1593 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001594 }
1595
1596 // Either we found no viable overloaded operator or we matched a
1597 // built-in operator. In either case, fall through to trying to
1598 // build a built-in operation.
1599 }
1600
Eli Friedman94d30952009-07-22 23:24:42 +00001601 Input.release();
1602 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001603 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001604}
1605
Sebastian Redl8b769972009-01-19 00:08:26 +00001606Action::OwningExprResult
1607Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1608 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001609 // Since this might be a postfix expression, get rid of ParenListExprs.
1610 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1611
Sebastian Redl8b769972009-01-19 00:08:26 +00001612 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1613 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001614
Douglas Gregor80723c52008-11-19 17:17:41 +00001615 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001616 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1617 Base.release();
1618 Idx.release();
1619 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1620 Context.DependentTy, RLoc));
1621 }
1622
1623 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001624 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001625 LHSExp->getType()->isEnumeralType() ||
1626 RHSExp->getType()->isRecordType() ||
1627 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001628 // Add the appropriate overloaded operators (C++ [over.match.oper])
1629 // to the candidate set.
1630 OverloadCandidateSet CandidateSet;
1631 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001632 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1633 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001634
Douglas Gregor80723c52008-11-19 17:17:41 +00001635 // Perform overload resolution.
1636 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001637 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001638 case OR_Success: {
1639 // We found a built-in operator or an overloaded operator.
1640 FunctionDecl *FnDecl = Best->Function;
1641
1642 if (FnDecl) {
1643 // We matched an overloaded operator. Build a call to that
1644 // operator.
1645
1646 // Convert the arguments.
1647 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1648 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1649 PerformCopyInitialization(RHSExp,
1650 FnDecl->getParamDecl(0)->getType(),
1651 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001652 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001653 } else {
1654 // Convert the arguments.
1655 if (PerformCopyInitialization(LHSExp,
1656 FnDecl->getParamDecl(0)->getType(),
1657 "passing") ||
1658 PerformCopyInitialization(RHSExp,
1659 FnDecl->getParamDecl(1)->getType(),
1660 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001661 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001662 }
1663
1664 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001665 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001666 = FnDecl->getType()->getAsFunctionType()->getResultType();
1667 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001668
Douglas Gregor80723c52008-11-19 17:17:41 +00001669 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001670 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1671 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001672 UsualUnaryConversions(FnExpr);
1673
Sebastian Redl8b769972009-01-19 00:08:26 +00001674 Base.release();
1675 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001676 Args[0] = LHSExp;
1677 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001678 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1679 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001680 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001681 } else {
1682 // We matched a built-in operator. Convert the arguments, then
1683 // break out so that we will build the appropriate built-in
1684 // operator node.
1685 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1686 "passing") ||
1687 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1688 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001689 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001690
1691 break;
1692 }
1693 }
1694
1695 case OR_No_Viable_Function:
1696 // No viable function; fall through to handling this as a
1697 // built-in operator, which will produce an error message for us.
1698 break;
1699
1700 case OR_Ambiguous:
1701 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1702 << "[]"
1703 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1704 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001705 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001706
1707 case OR_Deleted:
1708 Diag(LLoc, diag::err_ovl_deleted_oper)
1709 << Best->Function->isDeleted()
1710 << "[]"
1711 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1712 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1713 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001714 }
1715
1716 // Either we found no viable overloaded operator or we matched a
1717 // built-in operator. In either case, fall through to trying to
1718 // build a built-in operation.
1719 }
1720
Chris Lattner4b009652007-07-25 00:24:17 +00001721 // Perform default conversions.
1722 DefaultFunctionArrayConversion(LHSExp);
1723 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001724
Chris Lattner4b009652007-07-25 00:24:17 +00001725 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1726
1727 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001728 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001729 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001730 // and index from the expression types.
1731 Expr *BaseExpr, *IndexExpr;
1732 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001733 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1734 BaseExpr = LHSExp;
1735 IndexExpr = RHSExp;
1736 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001737 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001738 BaseExpr = LHSExp;
1739 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001740 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001741 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001742 // Handle the uncommon case of "123[Ptr]".
1743 BaseExpr = RHSExp;
1744 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001745 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001746 } else if (const ObjCObjectPointerType *PTy =
1747 LHSTy->getAsObjCObjectPointerType()) {
1748 BaseExpr = LHSExp;
1749 IndexExpr = RHSExp;
1750 ResultType = PTy->getPointeeType();
1751 } else if (const ObjCObjectPointerType *PTy =
1752 RHSTy->getAsObjCObjectPointerType()) {
1753 // Handle the uncommon case of "123[Ptr]".
1754 BaseExpr = RHSExp;
1755 IndexExpr = LHSExp;
1756 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001757 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1758 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001759 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001760
Chris Lattner4b009652007-07-25 00:24:17 +00001761 // FIXME: need to deal with const...
1762 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001763 } else if (LHSTy->isArrayType()) {
1764 // If we see an array that wasn't promoted by
1765 // DefaultFunctionArrayConversion, it must be an array that
1766 // wasn't promoted because of the C90 rule that doesn't
1767 // allow promoting non-lvalue arrays. Warn, then
1768 // force the promotion here.
1769 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1770 LHSExp->getSourceRange();
1771 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1772 LHSTy = LHSExp->getType();
1773
1774 BaseExpr = LHSExp;
1775 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001776 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001777 } else if (RHSTy->isArrayType()) {
1778 // Same as previous, except for 123[f().a] case
1779 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1780 RHSExp->getSourceRange();
1781 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1782 RHSTy = RHSExp->getType();
1783
1784 BaseExpr = RHSExp;
1785 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001786 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001787 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001788 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1789 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001790 }
Chris Lattner4b009652007-07-25 00:24:17 +00001791 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001792 if (!(IndexExpr->getType()->isIntegerType() &&
1793 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001794 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1795 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001796
Douglas Gregor05e28f62009-03-24 19:52:54 +00001797 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1798 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1799 // type. Note that Functions are not objects, and that (in C99 parlance)
1800 // incomplete types are not object types.
1801 if (ResultType->isFunctionType()) {
1802 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1803 << ResultType << BaseExpr->getSourceRange();
1804 return ExprError();
1805 }
Chris Lattner95933c12009-04-24 00:30:45 +00001806
Douglas Gregor05e28f62009-03-24 19:52:54 +00001807 if (!ResultType->isDependentType() &&
Anders Carlssona21e7872009-08-26 23:45:07 +00001808 RequireCompleteType(LLoc, ResultType,
1809 PDiag(diag::err_subscript_incomplete_type)
1810 << BaseExpr->getSourceRange()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00001811 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001812
1813 // Diagnose bad cases where we step over interface counts.
1814 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1815 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1816 << ResultType << BaseExpr->getSourceRange();
1817 return ExprError();
1818 }
1819
Sebastian Redl8b769972009-01-19 00:08:26 +00001820 Base.release();
1821 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001822 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001823 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001824}
1825
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001826QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001827CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001828 const IdentifierInfo *CompName,
1829 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001830 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001831
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001832 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001833 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001834
Mike Stump9afab102009-02-19 03:04:26 +00001835 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001836 // special names that indicate a subset of exactly half the elements are
1837 // to be selected.
1838 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001839
Nate Begeman1486b502009-01-18 01:47:54 +00001840 // This flag determines whether or not CompName has an 's' char prefix,
1841 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001842 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001843
1844 // Check that we've found one of the special components, or that the component
1845 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001846 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001847 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1848 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001849 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001850 do
1851 compStr++;
1852 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001853 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001854 do
1855 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001856 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001857 }
Nate Begeman1486b502009-01-18 01:47:54 +00001858
Mike Stump9afab102009-02-19 03:04:26 +00001859 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001860 // We didn't get to the end of the string. This means the component names
1861 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001862 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1863 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001864 return QualType();
1865 }
Mike Stump9afab102009-02-19 03:04:26 +00001866
Nate Begeman1486b502009-01-18 01:47:54 +00001867 // Ensure no component accessor exceeds the width of the vector type it
1868 // operates on.
1869 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001870 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001871
1872 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001873 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001874
1875 while (*compStr) {
1876 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1877 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1878 << baseType << SourceRange(CompLoc);
1879 return QualType();
1880 }
1881 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001882 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001883
Nate Begeman1486b502009-01-18 01:47:54 +00001884 // If this is a halving swizzle, verify that the base type has an even
1885 // number of elements.
1886 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001887 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001888 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001889 return QualType();
1890 }
Mike Stump9afab102009-02-19 03:04:26 +00001891
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001892 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001893 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001894 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001895 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001896 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001897 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001898 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001899 if (HexSwizzle)
1900 CompSize--;
1901
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001902 if (CompSize == 1)
1903 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001904
Nate Begemanaf6ed502008-04-18 23:10:10 +00001905 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001906 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001907 // diagostics look bad. We want extended vector types to appear built-in.
1908 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1909 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1910 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001911 }
1912 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001913}
1914
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001915static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001916 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001917 const Selector &Sel,
1918 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001919
Anders Carlsson9935ab92009-08-26 18:25:21 +00001920 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001921 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001922 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001923 return OMD;
1924
1925 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1926 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001927 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1928 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001929 return D;
1930 }
1931 return 0;
1932}
1933
Steve Naroffc75c1a82009-06-17 22:40:22 +00001934static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001935 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001936 const Selector &Sel,
1937 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001938 // Check protocols on qualified interfaces.
1939 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001940 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001941 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001942 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001943 GDecl = PD;
1944 break;
1945 }
1946 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001947 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001948 GDecl = OMD;
1949 break;
1950 }
1951 }
1952 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001953 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001954 E = QIdTy->qual_end(); I != E; ++I) {
1955 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001956 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001957 if (GDecl)
1958 return GDecl;
1959 }
1960 }
1961 return GDecl;
1962}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001963
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001964/// FindMethodInNestedImplementations - Look up a method in current and
1965/// all base class implementations.
1966///
1967ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1968 const ObjCInterfaceDecl *IFace,
1969 const Selector &Sel) {
1970 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001971 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001972 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001973
1974 if (!Method && IFace->getSuperClass())
1975 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1976 return Method;
1977}
Douglas Gregore399ad42009-08-26 22:36:53 +00001978
Anders Carlsson9935ab92009-08-26 18:25:21 +00001979Action::OwningExprResult
1980Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001981 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001982 DeclarationName MemberName,
Douglas Gregorda61ad22009-08-06 03:17:00 +00001983 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001984 if (SS && SS->isInvalid())
1985 return ExprError();
1986
Nate Begemane85f43d2009-08-10 23:49:36 +00001987 // Since this might be a postfix expression, get rid of ParenListExprs.
1988 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1989
Anders Carlssonc154a722009-05-01 19:30:39 +00001990 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001991 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00001992
Steve Naroff137e11d2007-12-16 21:42:28 +00001993 // Perform default conversions.
1994 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001995
Steve Naroff2cb66382007-07-26 03:11:44 +00001996 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00001997 // If this is an Objective-C pseudo-builtin and a definition is provided then
1998 // use that.
1999 if (BaseType->isObjCIdType()) {
2000 // We have an 'id' type. Rather than fall through, we check if this
2001 // is a reference to 'isa'.
2002 if (BaseType != Context.ObjCIdRedefinitionType) {
2003 BaseType = Context.ObjCIdRedefinitionType;
2004 ImpCastExprToType(BaseExpr, BaseType);
2005 }
2006 } else if (BaseType->isObjCClassType() &&
Douglas Gregorcfa0a632009-08-31 21:16:32 +00002007 BaseType != Context.ObjCClassRedefinitionType) {
David Chisnall44663db2009-08-17 16:35:33 +00002008 BaseType = Context.ObjCClassRedefinitionType;
2009 ImpCastExprToType(BaseExpr, BaseType);
2010 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002011 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002012
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002013 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2014 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002015 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002016 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002017 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2018 BaseExpr, true,
2019 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002020 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002021 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002022 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002023 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002024 else if (BaseType->isObjCObjectPointerType())
2025 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002026 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002027 return ExprError(Diag(MemberLoc,
2028 diag::err_typecheck_member_reference_arrow)
2029 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002030 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002031 if (BaseType->isDependentType()) {
2032 // Require that the base type isn't a pointer type
2033 // (so we'll report an error for)
2034 // T* t;
2035 // t.f;
2036 //
2037 // In Obj-C++, however, the above expression is valid, since it could be
2038 // accessing the 'f' property if T is an Obj-C interface. The extra check
2039 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002040 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002041
2042 if (!PT || (getLangOptions().ObjC1 &&
2043 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002044 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2045 BaseExpr, false,
2046 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002047 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002048 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002049 }
Chris Lattner4b009652007-07-25 00:24:17 +00002050 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002051
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002052 // Handle field access to simple records. This also handles access to fields
2053 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002054 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002055 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002056 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002057 PDiag(diag::err_typecheck_incomplete_tag)
2058 << BaseExpr->getSourceRange()))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002059 return ExprError();
2060
Douglas Gregorda61ad22009-08-06 03:17:00 +00002061 DeclContext *DC = RDecl;
2062 if (SS && SS->isSet()) {
2063 // If the member name was a qualified-id, look into the
2064 // nested-name-specifier.
2065 DC = computeDeclContext(*SS, false);
2066
2067 // FIXME: If DC is not computable, we should build a
2068 // CXXUnresolvedMemberExpr.
2069 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2070 }
2071
Steve Naroff2cb66382007-07-26 03:11:44 +00002072 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002073 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002074 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002075
Douglas Gregor12431cb2009-08-06 05:28:30 +00002076 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002077 QualType BaseTypeCanon
2078 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2079 QualType MemberTypeCanon
2080 = Context.getCanonicalType(
2081 Context.getTypeDeclType(
2082 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2083
2084 if (BaseTypeCanon != MemberTypeCanon &&
2085 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2086 return ExprError(Diag(SS->getBeginLoc(),
2087 diag::err_not_direct_base_or_virtual)
2088 << MemberTypeCanon << BaseTypeCanon);
2089 }
2090
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002091 if (!Result)
Anders Carlsson4355a392009-08-30 00:54:35 +00002092 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002093 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002094 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002095 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2096 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002097 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002098 }
2099
2100 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002101
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002102 // If the decl being referenced had an error, return an error for this
2103 // sub-expr without emitting another error, in order to avoid cascading
2104 // error cases.
2105 if (MemberDecl->isInvalidDecl())
2106 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002107
Douglas Gregoraa57e862009-02-18 21:56:37 +00002108 // Check the use of this field
2109 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2110 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002111
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002112 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002113 // We may have found a field within an anonymous union or struct
2114 // (C++ [class.union]).
2115 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002116 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002117 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002118
Douglas Gregor82d44772008-12-20 23:49:58 +00002119 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002120 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002121 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002122 MemberType = Ref->getPointeeType();
2123 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002124 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002125 unsigned combinedQualifiers =
2126 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002127 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002128 combinedQualifiers &= ~QualType::Const;
2129 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002130 if (BaseAddrSpace != MemberType.getAddressSpace())
2131 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002132 }
Eli Friedman76b49832008-02-06 22:48:16 +00002133
Douglas Gregorcad27f62009-06-22 23:06:13 +00002134 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002135 if (PerformObjectMemberConversion(BaseExpr, FD))
2136 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002137 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2138 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002139 }
2140
Douglas Gregorcad27f62009-06-22 23:06:13 +00002141 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2142 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002143 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2144 Var, MemberLoc,
2145 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002146 }
2147 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2148 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002149 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2150 MemberFn, MemberLoc,
2151 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002152 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002153 if (FunctionTemplateDecl *FunTmpl
2154 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2155 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002156 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2157 FunTmpl, MemberLoc,
2158 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002159 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002160 if (OverloadedFunctionDecl *Ovl
2161 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregore399ad42009-08-26 22:36:53 +00002162 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2163 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002164 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2165 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002166 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2167 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002168 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002169 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002170 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002171 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002172
Douglas Gregor82d44772008-12-20 23:49:58 +00002173 // We found a declaration kind that we didn't expect. This is a
2174 // generic error message that tells the user that she can't refer
2175 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002176 return ExprError(Diag(MemberLoc,
2177 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002178 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002179 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002180
Steve Naroff329ec222009-07-10 23:34:53 +00002181 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002182 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002183 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002184 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2185 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002186 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2187 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2188 ObjCMethodDecl *Getter;
2189 // FIXME: need to also look locally in the implementation.
2190 if ((Getter = IFace->lookupClassMethod(Sel))) {
2191 // Check the use of this method.
2192 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2193 return ExprError();
2194 }
2195 // If we found a getter then this may be a valid dot-reference, we
2196 // will look for the matching setter, in case it is needed.
2197 Selector SetterSel =
2198 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002199 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002200 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2201 if (!Setter) {
2202 // If this reference is in an @implementation, also check for 'private'
2203 // methods.
2204 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2205 }
2206 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002207 if (!Setter)
2208 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002209
2210 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2211 return ExprError();
2212
2213 if (Getter || Setter) {
2214 QualType PType;
2215
2216 if (Getter)
2217 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002218 else
2219 // Get the expression type from Setter's incoming parameter.
2220 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002221 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002222 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002223 Setter, MemberLoc, BaseExpr));
2224 }
2225 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002226 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002227 }
2228 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002229 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2230 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002231 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2232 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2233 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2234 const ObjCInterfaceType *IFaceT =
2235 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002236 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002237 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2238
Steve Naroff4e743962009-07-16 00:25:06 +00002239 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2240 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002241 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002242
2243 if (IV) {
2244 // If the decl being referenced had an error, return an error for this
2245 // sub-expr without emitting another error, in order to avoid cascading
2246 // error cases.
2247 if (IV->isInvalidDecl())
2248 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002249
Steve Naroff4e743962009-07-16 00:25:06 +00002250 // Check whether we can reference this field.
2251 if (DiagnoseUseOfDecl(IV, MemberLoc))
2252 return ExprError();
2253 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2254 IV->getAccessControl() != ObjCIvarDecl::Package) {
2255 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2256 if (ObjCMethodDecl *MD = getCurMethodDecl())
2257 ClassOfMethodDecl = MD->getClassInterface();
2258 else if (ObjCImpDecl && getCurFunctionDecl()) {
2259 // Case of a c-function declared inside an objc implementation.
2260 // FIXME: For a c-style function nested inside an objc implementation
2261 // class, there is no implementation context available, so we pass
2262 // down the context as argument to this routine. Ideally, this context
2263 // need be passed down in the AST node and somehow calculated from the
2264 // AST for a function decl.
2265 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2266 if (ObjCImplementationDecl *IMPD =
2267 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2268 ClassOfMethodDecl = IMPD->getClassInterface();
2269 else if (ObjCCategoryImplDecl* CatImplClass =
2270 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2271 ClassOfMethodDecl = CatImplClass->getClassInterface();
2272 }
2273
2274 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2275 if (ClassDeclared != IDecl ||
2276 ClassOfMethodDecl != ClassDeclared)
2277 Diag(MemberLoc, diag::error_private_ivar_access)
2278 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002279 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2280 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002281 Diag(MemberLoc, diag::error_protected_ivar_access)
2282 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002283 }
Steve Naroff4e743962009-07-16 00:25:06 +00002284
2285 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2286 MemberLoc, BaseExpr,
2287 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002288 }
Steve Naroff4e743962009-07-16 00:25:06 +00002289 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002290 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002291 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002292 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002293 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002294 // Handle properties on 'id' and qualified "id".
2295 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2296 BaseType->isObjCQualifiedIdType())) {
2297 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002298 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002299
Steve Naroff329ec222009-07-10 23:34:53 +00002300 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002301 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002302 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2303 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2304 // Check the use of this declaration
2305 if (DiagnoseUseOfDecl(PD, MemberLoc))
2306 return ExprError();
2307
2308 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2309 MemberLoc, BaseExpr));
2310 }
2311 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2312 // Check the use of this method.
2313 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2314 return ExprError();
2315
2316 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2317 OMD->getResultType(),
2318 OMD, OpLoc, MemberLoc,
2319 NULL, 0));
2320 }
2321 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002322
Steve Naroff329ec222009-07-10 23:34:53 +00002323 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002324 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002325 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002326 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2327 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002328 const ObjCObjectPointerType *OPT;
2329 if (OpKind == tok::period &&
2330 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2331 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2332 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002333 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002334
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002335 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002336 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002337 // Check whether we can reference this property.
2338 if (DiagnoseUseOfDecl(PD, MemberLoc))
2339 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002340 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002341 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002342 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002343 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2344 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002345 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002346 MemberLoc, BaseExpr));
2347 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002348 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002349 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2350 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002351 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002352 // Check whether we can reference this property.
2353 if (DiagnoseUseOfDecl(PD, MemberLoc))
2354 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002355
Steve Naroff774e4152009-01-21 00:14:39 +00002356 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002357 MemberLoc, BaseExpr));
2358 }
Steve Naroff329ec222009-07-10 23:34:53 +00002359 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2360 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002361 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002362 // Check whether we can reference this property.
2363 if (DiagnoseUseOfDecl(PD, MemberLoc))
2364 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002365
Steve Naroff329ec222009-07-10 23:34:53 +00002366 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2367 MemberLoc, BaseExpr));
2368 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002369 // If that failed, look for an "implicit" property by seeing if the nullary
2370 // selector is implemented.
2371
2372 // FIXME: The logic for looking up nullary and unary selectors should be
2373 // shared with the code in ActOnInstanceMessage.
2374
Anders Carlsson9935ab92009-08-26 18:25:21 +00002375 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002376 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002377
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002378 // If this reference is in an @implementation, check for 'private' methods.
2379 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002380 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002381
Steve Naroff04151f32008-10-22 19:16:27 +00002382 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002383 if (!Getter)
2384 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002385 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002386 // Check if we can reference this property.
2387 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2388 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002389 }
2390 // If we found a getter then this may be a valid dot-reference, we
2391 // will look for the matching setter, in case it is needed.
2392 Selector SetterSel =
2393 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002394 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002395 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002396 if (!Setter) {
2397 // If this reference is in an @implementation, also check for 'private'
2398 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002399 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002400 }
2401 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002402 if (!Setter)
2403 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002404
Steve Naroffdede0c92009-03-11 13:48:17 +00002405 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2406 return ExprError();
2407
2408 if (Getter || Setter) {
2409 QualType PType;
2410
2411 if (Getter)
2412 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002413 else
2414 // Get the expression type from Setter's incoming parameter.
2415 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002416 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002417 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002418 Setter, MemberLoc, BaseExpr));
2419 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002420 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002421 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002422 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002423
Steve Naroff29d293b2009-07-24 17:54:45 +00002424 // Handle the following exceptional case (*Obj).isa.
2425 if (OpKind == tok::period &&
2426 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002427 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002428 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2429 Context.getObjCIdType()));
2430
Chris Lattnera57cf472008-07-21 04:28:12 +00002431 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002432 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002433 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002434 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2435 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002436 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002437 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002438 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002439 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002440
Douglas Gregor762da552009-03-27 06:00:30 +00002441 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2442 << BaseType << BaseExpr->getSourceRange();
2443
2444 // If the user is trying to apply -> or . to a function or function
2445 // pointer, it's probably because they forgot parentheses to call
2446 // the function. Suggest the addition of those parentheses.
2447 if (BaseType == Context.OverloadTy ||
2448 BaseType->isFunctionType() ||
2449 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002450 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002451 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2452 Diag(Loc, diag::note_member_reference_needs_call)
2453 << CodeModificationHint::CreateInsertion(Loc, "()");
2454 }
2455
2456 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002457}
2458
Anders Carlsson9935ab92009-08-26 18:25:21 +00002459Action::OwningExprResult
2460Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2461 tok::TokenKind OpKind, SourceLocation MemberLoc,
2462 IdentifierInfo &Member,
2463 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2464 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2465 DeclarationName(&Member), ObjCImpDecl, SS);
2466}
2467
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002468Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2469 FunctionDecl *FD,
2470 ParmVarDecl *Param) {
2471 if (Param->hasUnparsedDefaultArg()) {
2472 Diag (CallLoc,
2473 diag::err_use_of_default_argument_to_function_declared_later) <<
2474 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2475 Diag(UnparsedDefaultArgLocs[Param],
2476 diag::note_default_argument_declared_here);
2477 } else {
2478 if (Param->hasUninstantiatedDefaultArg()) {
2479 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2480
2481 // Instantiate the expression.
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002482 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002483
2484 // FIXME: We should really make a new InstantiatingTemplate ctor
2485 // that has a better message - right now we're just piggy-backing
2486 // off the "default template argument" error message.
2487 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002488 ArgList.getInnermost().getFlatArgumentList(),
2489 ArgList.getInnermost().flat_size());
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002490
John McCall0ba26ee2009-08-25 22:02:44 +00002491 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002492 if (Result.isInvalid())
2493 return ExprError();
2494
2495 if (SetParamDefaultArgument(Param, move(Result),
2496 /*FIXME:EqualLoc*/
2497 UninstExpr->getSourceRange().getBegin()))
2498 return ExprError();
2499 }
2500
2501 Expr *DefaultExpr = Param->getDefaultArg();
2502
2503 // If the default expression creates temporaries, we need to
2504 // push them to the current stack of expression temporaries so they'll
2505 // be properly destroyed.
2506 if (CXXExprWithTemporaries *E
2507 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2508 assert(!E->shouldDestroyTemporaries() &&
2509 "Can't destroy temporaries in a default argument expr!");
2510 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2511 ExprTemporaries.push_back(E->getTemporary(I));
2512 }
2513 }
2514
2515 // We already type-checked the argument, so we know it works.
2516 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2517}
2518
Douglas Gregor3257fb52008-12-22 05:46:06 +00002519/// ConvertArgumentsForCall - Converts the arguments specified in
2520/// Args/NumArgs to the parameter types of the function FDecl with
2521/// function prototype Proto. Call is the call expression itself, and
2522/// Fn is the function expression. For a C++ member function, this
2523/// routine does not attempt to convert the object argument. Returns
2524/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002525bool
2526Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002527 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002528 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002529 Expr **Args, unsigned NumArgs,
2530 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002531 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002532 // assignment, to the types of the corresponding parameter, ...
2533 unsigned NumArgsInProto = Proto->getNumArgs();
2534 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002535 bool Invalid = false;
2536
Douglas Gregor3257fb52008-12-22 05:46:06 +00002537 // If too few arguments are available (and we don't have default
2538 // arguments for the remaining parameters), don't make the call.
2539 if (NumArgs < NumArgsInProto) {
2540 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2541 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2542 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2543 // Use default arguments for missing arguments
2544 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002545 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002546 }
2547
2548 // If too many are passed and not variadic, error on the extras and drop
2549 // them.
2550 if (NumArgs > NumArgsInProto) {
2551 if (!Proto->isVariadic()) {
2552 Diag(Args[NumArgsInProto]->getLocStart(),
2553 diag::err_typecheck_call_too_many_args)
2554 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2555 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2556 Args[NumArgs-1]->getLocEnd());
2557 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002558 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002559 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002560 }
2561 NumArgsToCheck = NumArgsInProto;
2562 }
Mike Stump9afab102009-02-19 03:04:26 +00002563
Douglas Gregor3257fb52008-12-22 05:46:06 +00002564 // Continue to check argument types (even if we have too few/many args).
2565 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2566 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002567
Douglas Gregor3257fb52008-12-22 05:46:06 +00002568 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002569 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002570 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002571
Eli Friedman83dec9e2009-03-22 22:00:50 +00002572 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2573 ProtoArgType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002574 PDiag(diag::err_call_incomplete_argument)
2575 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002576 return true;
2577
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002578 // Pass the argument.
2579 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2580 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002581 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002582 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002583
2584 OwningExprResult ArgExpr =
2585 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2586 FDecl, Param);
2587 if (ArgExpr.isInvalid())
2588 return true;
2589
2590 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002591 }
2592
Douglas Gregor3257fb52008-12-22 05:46:06 +00002593 Call->setArg(i, Arg);
2594 }
Mike Stump9afab102009-02-19 03:04:26 +00002595
Douglas Gregor3257fb52008-12-22 05:46:06 +00002596 // If this is a variadic call, handle args passed through "...".
2597 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002598 VariadicCallType CallType = VariadicFunction;
2599 if (Fn->getType()->isBlockPointerType())
2600 CallType = VariadicBlock; // Block
2601 else if (isa<MemberExpr>(Fn))
2602 CallType = VariadicMethod;
2603
Douglas Gregor3257fb52008-12-22 05:46:06 +00002604 // Promote the arguments (C99 6.5.2.2p7).
2605 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2606 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002607 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002608 Call->setArg(i, Arg);
2609 }
2610 }
2611
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002612 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002613}
2614
Steve Naroff87d58b42007-09-16 03:34:24 +00002615/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002616/// This provides the location of the left/right parens and a list of comma
2617/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002618Action::OwningExprResult
2619Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2620 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002621 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002622 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002623
2624 // Since this might be a postfix expression, get rid of ParenListExprs.
2625 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2626
Anders Carlssonc154a722009-05-01 19:30:39 +00002627 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002628 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002629 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002630 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002631 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002632 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002633
Douglas Gregor3257fb52008-12-22 05:46:06 +00002634 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002635 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002636 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002637 // FIXME: Will need to cache the results of name lookup (including ADL) in
2638 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002639 bool Dependent = false;
2640 if (Fn->isTypeDependent())
2641 Dependent = true;
2642 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2643 Dependent = true;
2644
2645 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002646 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002647 Context.DependentTy, RParenLoc));
2648
2649 // Determine whether this is a call to an object (C++ [over.call.object]).
2650 if (Fn->getType()->isRecordType())
2651 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2652 CommaLocs, RParenLoc));
2653
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002654 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002655 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2656 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2657 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2658 isa<CXXMethodDecl>(MemDecl) ||
2659 (isa<FunctionTemplateDecl>(MemDecl) &&
2660 isa<CXXMethodDecl>(
2661 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002662 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2663 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002664 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002665 }
2666
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002667 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002668 // Also, in C++, keep track of whether we should perform argument-dependent
2669 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002670 Expr *FnExpr = Fn;
2671 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002672 bool HasExplicitTemplateArgs = 0;
2673 const TemplateArgument *ExplicitTemplateArgs = 0;
2674 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002675 while (true) {
2676 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2677 FnExpr = IcExpr->getSubExpr();
2678 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002679 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002680 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002681 ADL = false;
2682 FnExpr = PExpr->getSubExpr();
2683 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002684 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002685 == UnaryOperator::AddrOf) {
2686 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002687 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002688 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2689 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002690 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002691 break;
Mike Stump9afab102009-02-19 03:04:26 +00002692 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002693 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2694 UnqualifiedName = DepName->getName();
2695 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002696 } else if (TemplateIdRefExpr *TemplateIdRef
2697 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2698 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002699 if (!NDecl)
2700 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002701 HasExplicitTemplateArgs = true;
2702 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2703 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2704
2705 // C++ [temp.arg.explicit]p6:
2706 // [Note: For simple function names, argument dependent lookup (3.4.2)
2707 // applies even when the function name is not visible within the
2708 // scope of the call. This is because the call still has the syntactic
2709 // form of a function call (3.4.1). But when a function template with
2710 // explicit template arguments is used, the call does not have the
2711 // correct syntactic form unless there is a function template with
2712 // that name visible at the point of the call. If no such name is
2713 // visible, the call is not syntactically well-formed and
2714 // argument-dependent lookup does not apply. If some such name is
2715 // visible, argument dependent lookup applies and additional function
2716 // templates may be found in other namespaces.
2717 //
2718 // The summary of this paragraph is that, if we get to this point and the
2719 // template-id was not a qualified name, then argument-dependent lookup
2720 // is still possible.
2721 if (TemplateIdRef->getQualifier())
2722 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002723 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002724 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002725 // Any kind of name that does not refer to a declaration (or
2726 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2727 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002728 break;
2729 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002730 }
Mike Stump9afab102009-02-19 03:04:26 +00002731
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002732 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002733 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002734 if (NDecl) {
2735 FDecl = dyn_cast<FunctionDecl>(NDecl);
2736 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002737 FDecl = FunctionTemplate->getTemplatedDecl();
2738 else
Douglas Gregor28857752009-06-30 22:34:41 +00002739 FDecl = dyn_cast<FunctionDecl>(NDecl);
2740 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002741 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002742
Douglas Gregorb60eb752009-06-25 22:08:12 +00002743 if (Ovl || FunctionTemplate ||
2744 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002745 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002746 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002747 ADL = false;
2748
Douglas Gregorfcb19192009-02-11 23:02:49 +00002749 // We don't perform ADL in C.
2750 if (!getLangOptions().CPlusPlus)
2751 ADL = false;
2752
Douglas Gregorb60eb752009-06-25 22:08:12 +00002753 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002754 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2755 HasExplicitTemplateArgs,
2756 ExplicitTemplateArgs,
2757 NumExplicitTemplateArgs,
2758 LParenLoc, Args, NumArgs, CommaLocs,
2759 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002760 if (!FDecl)
2761 return ExprError();
2762
2763 // Update Fn to refer to the actual function selected.
2764 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002765 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002766 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002767 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2768 QDRExpr->getLocation(),
2769 false, false,
2770 QDRExpr->getQualifierRange(),
2771 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002772 else
Mike Stump9afab102009-02-19 03:04:26 +00002773 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002774 Fn->getSourceRange().getBegin());
2775 Fn->Destroy(Context);
2776 Fn = NewFn;
2777 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002778 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002779
2780 // Promote the function operand.
2781 UsualUnaryConversions(Fn);
2782
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002783 // Make the call expr early, before semantic checks. This guarantees cleanup
2784 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002785 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2786 Args, NumArgs,
2787 Context.BoolTy,
2788 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002789
Steve Naroffd6163f32008-09-05 22:11:13 +00002790 const FunctionType *FuncT;
2791 if (!Fn->getType()->isBlockPointerType()) {
2792 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2793 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002794 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002795 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002796 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2797 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002798 FuncT = PT->getPointeeType()->getAsFunctionType();
2799 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002800 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002801 getAsFunctionType();
2802 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002803 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002804 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2805 << Fn->getType() << Fn->getSourceRange());
2806
Eli Friedman83dec9e2009-03-22 22:00:50 +00002807 // Check for a valid return type
2808 if (!FuncT->getResultType()->isVoidType() &&
2809 RequireCompleteType(Fn->getSourceRange().getBegin(),
2810 FuncT->getResultType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002811 PDiag(diag::err_call_incomplete_return)
2812 << TheCall->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002813 return ExprError();
2814
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002815 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002816 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002817
Douglas Gregor4fa58902009-02-26 23:50:07 +00002818 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002819 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002820 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002821 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002822 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002823 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002824
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002825 if (FDecl) {
2826 // Check if we have too few/too many template arguments, based
2827 // on our knowledge of the function definition.
2828 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002829 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002830 const FunctionProtoType *Proto =
2831 Def->getType()->getAsFunctionProtoType();
2832 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2833 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2834 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2835 }
2836 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002837 }
2838
Steve Naroffdb65e052007-08-28 23:30:39 +00002839 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002840 for (unsigned i = 0; i != NumArgs; i++) {
2841 Expr *Arg = Args[i];
2842 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002843 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2844 Arg->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002845 PDiag(diag::err_call_incomplete_argument)
2846 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002847 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002848 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002849 }
Chris Lattner4b009652007-07-25 00:24:17 +00002850 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002851
Douglas Gregor3257fb52008-12-22 05:46:06 +00002852 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2853 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002854 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2855 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002856
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002857 // Check for sentinels
2858 if (NDecl)
2859 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002860
Chris Lattner2e64c072007-08-10 20:18:51 +00002861 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002862 if (FDecl) {
2863 if (CheckFunctionCall(FDecl, TheCall.get()))
2864 return ExprError();
2865
2866 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2867 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2868 } else if (NDecl) {
2869 if (CheckBlockCall(NDecl, TheCall.get()))
2870 return ExprError();
2871 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002872
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002873 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002874}
2875
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002876Action::OwningExprResult
2877Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2878 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002879 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002880 //FIXME: Preserve type source info.
2881 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002882 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002883 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002884 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002885
Eli Friedman8c2173d2008-05-20 05:22:08 +00002886 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002887 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002888 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2889 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002890 } else if (!literalType->isDependentType() &&
2891 RequireCompleteType(LParenLoc, literalType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002892 PDiag(diag::err_typecheck_decl_incomplete_type)
2893 << SourceRange(LParenLoc,
2894 literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002895 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002896
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002897 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002898 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002899 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002900
Chris Lattnere5cb5862008-12-04 23:50:19 +00002901 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002902 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002903 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002904 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002905 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002906 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002907 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002908 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002909}
2910
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002911Action::OwningExprResult
2912Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002913 SourceLocation RBraceLoc) {
2914 unsigned NumInit = initlist.size();
2915 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002916
Steve Naroff0acc9c92007-09-15 18:49:24 +00002917 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002918 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002919
Mike Stump9afab102009-02-19 03:04:26 +00002920 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002921 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002922 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002923 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002924}
2925
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002926/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002927bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002928 CastExpr::CastKind& Kind,
2929 CXXMethodDecl *& ConversionDecl,
2930 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002931 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002932 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2933 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002934
Eli Friedman01e0f652009-08-15 19:02:19 +00002935 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002936
2937 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2938 // type needs to be scalar.
2939 if (castType->isVoidType()) {
2940 // Cast to void allows any expr type.
2941 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002942 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2943 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2944 (castType->isStructureType() || castType->isUnionType())) {
2945 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002946 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002947 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2948 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002949 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002950 } else if (castType->isUnionType()) {
2951 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002952 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002953 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002954 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002955 Field != FieldEnd; ++Field) {
2956 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2957 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2958 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2959 << castExpr->getSourceRange();
2960 break;
2961 }
2962 }
2963 if (Field == FieldEnd)
2964 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2965 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002966 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002967 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002968 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002969 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002970 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002971 }
Mike Stump9afab102009-02-19 03:04:26 +00002972 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002973 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002974 return Diag(castExpr->getLocStart(),
2975 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002976 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00002977 } else if (castType->isExtVectorType()) {
2978 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002979 return true;
2980 } else if (castType->isVectorType()) {
2981 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2982 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00002983 } else if (castExpr->getType()->isVectorType()) {
2984 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2985 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002986 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002987 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002988 } else if (!castType->isArithmeticType()) {
2989 QualType castExprType = castExpr->getType();
2990 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2991 return Diag(castExpr->getLocStart(),
2992 diag::err_cast_pointer_from_non_pointer_int)
2993 << castExprType << castExpr->getSourceRange();
2994 } else if (!castExpr->getType()->isArithmeticType()) {
2995 if (!castType->isIntegralType() && castType->isArithmeticType())
2996 return Diag(castExpr->getLocStart(),
2997 diag::err_cast_pointer_to_non_pointer_int)
2998 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002999 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003000 if (isa<ObjCSelectorExpr>(castExpr))
3001 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003002 return false;
3003}
3004
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003005bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003006 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003007
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003008 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003009 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003010 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003011 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003012 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003013 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003014 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003015 } else
3016 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003017 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003018 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003019
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003020 return false;
3021}
3022
Nate Begemanbd42e022009-06-26 00:50:28 +00003023bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3024 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3025
Nate Begeman9e063702009-06-27 22:05:55 +00003026 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3027 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003028 if (SrcTy->isVectorType()) {
3029 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3030 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3031 << DestTy << SrcTy << R;
3032 return false;
3033 }
3034
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003035 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003036 // conversion will take place first from scalar to elt type, and then
3037 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003038 if (SrcTy->isPointerType())
3039 return Diag(R.getBegin(),
3040 diag::err_invalid_conversion_between_vector_and_scalar)
3041 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003042 return false;
3043}
3044
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003045Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003046Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003047 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003048 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3049
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003050 assert((Ty != 0) && (Op.get() != 0) &&
3051 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003052
Nate Begemane85f43d2009-08-10 23:49:36 +00003053 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003054 //FIXME: Preserve type source info.
3055 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003056
3057 // If the Expr being casted is a ParenListExpr, handle it specially.
3058 if (isa<ParenListExpr>(castExpr))
3059 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003060 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003061 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003062 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003063 return ExprError();
Fariborz Jahanianec172132009-08-29 19:15:16 +00003064 if (ConversionDecl) {
3065 // encounterred a c-style cast requiring a conversion function.
3066 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) {
3067 castExpr =
3068 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(),
3069 castType, LParenLoc,
3070 CastExpr::CK_UserDefinedConversion,
3071 castExpr, CD,
3072 RParenLoc);
3073 Kind = CastExpr::CK_UserDefinedConversion;
3074 }
3075 // FIXME. AST for when dealing with conversion functions (FunctionDecl).
3076 }
Nate Begemane85f43d2009-08-10 23:49:36 +00003077
3078 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003079 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003080 Kind, castExpr, castType,
3081 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003082}
3083
Nate Begemane85f43d2009-08-10 23:49:36 +00003084/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3085/// of comma binary operators.
3086Action::OwningExprResult
3087Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3088 Expr *expr = EA.takeAs<Expr>();
3089 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3090 if (!E)
3091 return Owned(expr);
3092
3093 OwningExprResult Result(*this, E->getExpr(0));
3094
3095 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3096 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3097 Owned(E->getExpr(i)));
3098
3099 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3100}
3101
3102Action::OwningExprResult
3103Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3104 SourceLocation RParenLoc, ExprArg Op,
3105 QualType Ty) {
3106 ParenListExpr *PE = (ParenListExpr *)Op.get();
3107
3108 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3109 // then handle it as such.
3110 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3111 if (PE->getNumExprs() == 0) {
3112 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3113 return ExprError();
3114 }
3115
3116 llvm::SmallVector<Expr *, 8> initExprs;
3117 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3118 initExprs.push_back(PE->getExpr(i));
3119
3120 // FIXME: This means that pretty-printing the final AST will produce curly
3121 // braces instead of the original commas.
3122 Op.release();
3123 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3124 initExprs.size(), RParenLoc);
3125 E->setType(Ty);
3126 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3127 Owned(E));
3128 } else {
3129 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3130 // sequence of BinOp comma operators.
3131 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3132 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3133 }
3134}
3135
3136Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3137 SourceLocation R,
3138 MultiExprArg Val) {
3139 unsigned nexprs = Val.size();
3140 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3141 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3142 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3143 return Owned(expr);
3144}
3145
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003146/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3147/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003148/// C99 6.5.15
3149QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3150 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003151 // C++ is sufficiently different to merit its own checker.
3152 if (getLangOptions().CPlusPlus)
3153 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3154
Chris Lattnere2897262009-02-18 04:28:32 +00003155 UsualUnaryConversions(Cond);
3156 UsualUnaryConversions(LHS);
3157 UsualUnaryConversions(RHS);
3158 QualType CondTy = Cond->getType();
3159 QualType LHSTy = LHS->getType();
3160 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003161
3162 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003163 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3164 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3165 << CondTy;
3166 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003167 }
Mike Stump9afab102009-02-19 03:04:26 +00003168
Chris Lattner992ae932008-01-06 22:42:25 +00003169 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003170 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3171 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003172
Chris Lattner992ae932008-01-06 22:42:25 +00003173 // If both operands have arithmetic type, do the usual arithmetic conversions
3174 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003175 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3176 UsualArithmeticConversions(LHS, RHS);
3177 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003178 }
Mike Stump9afab102009-02-19 03:04:26 +00003179
Chris Lattner992ae932008-01-06 22:42:25 +00003180 // If both operands are the same structure or union type, the result is that
3181 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003182 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3183 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003184 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003185 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003186 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003187 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003188 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003189 }
Mike Stump9afab102009-02-19 03:04:26 +00003190
Chris Lattner992ae932008-01-06 22:42:25 +00003191 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003192 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003193 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3194 if (!LHSTy->isVoidType())
3195 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3196 << RHS->getSourceRange();
3197 if (!RHSTy->isVoidType())
3198 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3199 << LHS->getSourceRange();
3200 ImpCastExprToType(LHS, Context.VoidTy);
3201 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003202 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003203 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003204 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3205 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003206 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003207 RHS->isNullPointerConstant(Context)) {
3208 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3209 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003210 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003211 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003212 LHS->isNullPointerConstant(Context)) {
3213 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3214 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003215 }
David Chisnall44663db2009-08-17 16:35:33 +00003216 // Handle things like Class and struct objc_class*. Here we case the result
3217 // to the pseudo-builtin, because that will be implicitly cast back to the
3218 // redefinition type if an attempt is made to access its fields.
3219 if (LHSTy->isObjCClassType() &&
3220 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3221 ImpCastExprToType(RHS, LHSTy);
3222 return LHSTy;
3223 }
3224 if (RHSTy->isObjCClassType() &&
3225 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3226 ImpCastExprToType(LHS, RHSTy);
3227 return RHSTy;
3228 }
3229 // And the same for struct objc_object* / id
3230 if (LHSTy->isObjCIdType() &&
3231 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3232 ImpCastExprToType(RHS, LHSTy);
3233 return LHSTy;
3234 }
3235 if (RHSTy->isObjCIdType() &&
3236 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3237 ImpCastExprToType(LHS, RHSTy);
3238 return RHSTy;
3239 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003240 // Handle block pointer types.
3241 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3242 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3243 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3244 QualType destType = Context.getPointerType(Context.VoidTy);
3245 ImpCastExprToType(LHS, destType);
3246 ImpCastExprToType(RHS, destType);
3247 return destType;
3248 }
3249 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3250 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3251 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003252 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003253 // We have 2 block pointer types.
3254 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3255 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003256 return LHSTy;
3257 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003258 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003259 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3260 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003261
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003262 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3263 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003264 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3265 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3266 // In this situation, we assume void* type. No especially good
3267 // reason, but this is what gcc does, and we do have to pick
3268 // to get a consistent AST.
3269 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3270 ImpCastExprToType(LHS, incompatTy);
3271 ImpCastExprToType(RHS, incompatTy);
3272 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003273 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003274 // The block pointer types are compatible.
3275 ImpCastExprToType(LHS, LHSTy);
3276 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003277 return LHSTy;
3278 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003279 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003280 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003281
3282 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3283 // Two identical object pointer types are always compatible.
3284 return LHSTy;
3285 }
Steve Naroff329ec222009-07-10 23:34:53 +00003286 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3287 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003288 QualType compositeType = LHSTy;
3289
3290 // If both operands are interfaces and either operand can be
3291 // assigned to the other, use that type as the composite
3292 // type. This allows
3293 // xxx ? (A*) a : (B*) b
3294 // where B is a subclass of A.
3295 //
3296 // Additionally, as for assignment, if either type is 'id'
3297 // allow silent coercion. Finally, if the types are
3298 // incompatible then make sure to use 'id' as the composite
3299 // type so the result is acceptable for sending messages to.
3300
3301 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3302 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003303 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003304 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003305 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003306 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003307 } else if ((LHSTy->isObjCQualifiedIdType() ||
3308 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003309 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003310 // Need to handle "id<xx>" explicitly.
3311 // GCC allows qualified id and any Objective-C type to devolve to
3312 // id. Currently localizing to here until clear this should be
3313 // part of ObjCQualifiedIdTypesAreCompatible.
3314 compositeType = Context.getObjCIdType();
3315 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003316 compositeType = Context.getObjCIdType();
3317 } else {
3318 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3319 << LHSTy << RHSTy
3320 << LHS->getSourceRange() << RHS->getSourceRange();
3321 QualType incompatTy = Context.getObjCIdType();
3322 ImpCastExprToType(LHS, incompatTy);
3323 ImpCastExprToType(RHS, incompatTy);
3324 return incompatTy;
3325 }
3326 // The object pointer types are compatible.
3327 ImpCastExprToType(LHS, compositeType);
3328 ImpCastExprToType(RHS, compositeType);
3329 return compositeType;
3330 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003331 // Check Objective-C object pointer types and 'void *'
3332 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003333 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003334 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3335 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3336 QualType destType = Context.getPointerType(destPointee);
3337 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3338 ImpCastExprToType(RHS, destType); // promote to void*
3339 return destType;
3340 }
3341 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3342 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003343 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003344 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3345 QualType destType = Context.getPointerType(destPointee);
3346 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3347 ImpCastExprToType(LHS, destType); // promote to void*
3348 return destType;
3349 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003350 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3351 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3352 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003353 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3354 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003355
3356 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3357 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3358 // Figure out necessary qualifiers (C99 6.5.15p6)
3359 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3360 QualType destType = Context.getPointerType(destPointee);
3361 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3362 ImpCastExprToType(RHS, destType); // promote to void*
3363 return destType;
3364 }
3365 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3366 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3367 QualType destType = Context.getPointerType(destPointee);
3368 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3369 ImpCastExprToType(RHS, destType); // promote to void*
3370 return destType;
3371 }
3372
3373 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3374 // Two identical pointer types are always compatible.
3375 return LHSTy;
3376 }
3377 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3378 rhptee.getUnqualifiedType())) {
3379 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3380 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3381 // In this situation, we assume void* type. No especially good
3382 // reason, but this is what gcc does, and we do have to pick
3383 // to get a consistent AST.
3384 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3385 ImpCastExprToType(LHS, incompatTy);
3386 ImpCastExprToType(RHS, incompatTy);
3387 return incompatTy;
3388 }
3389 // The pointer types are compatible.
3390 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3391 // differently qualified versions of compatible types, the result type is
3392 // a pointer to an appropriately qualified version of the *composite*
3393 // type.
3394 // FIXME: Need to calculate the composite type.
3395 // FIXME: Need to add qualifiers
3396 ImpCastExprToType(LHS, LHSTy);
3397 ImpCastExprToType(RHS, LHSTy);
3398 return LHSTy;
3399 }
3400
3401 // GCC compatibility: soften pointer/integer mismatch.
3402 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3403 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3404 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3405 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3406 return RHSTy;
3407 }
3408 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3409 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3410 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3411 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3412 return LHSTy;
3413 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003414
Chris Lattner992ae932008-01-06 22:42:25 +00003415 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003416 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3417 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003418 return QualType();
3419}
3420
Steve Naroff87d58b42007-09-16 03:34:24 +00003421/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003422/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003423Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3424 SourceLocation ColonLoc,
3425 ExprArg Cond, ExprArg LHS,
3426 ExprArg RHS) {
3427 Expr *CondExpr = (Expr *) Cond.get();
3428 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003429
3430 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3431 // was the condition.
3432 bool isLHSNull = LHSExpr == 0;
3433 if (isLHSNull)
3434 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003435
3436 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003437 RHSExpr, QuestionLoc);
3438 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003439 return ExprError();
3440
3441 Cond.release();
3442 LHS.release();
3443 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003444 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003445 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003446 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003447}
3448
Chris Lattner4b009652007-07-25 00:24:17 +00003449// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003450// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003451// routine is it effectively iqnores the qualifiers on the top level pointee.
3452// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3453// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003454Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003455Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3456 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003457
David Chisnall44663db2009-08-17 16:35:33 +00003458 if ((lhsType->isObjCClassType() &&
3459 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3460 (rhsType->isObjCClassType() &&
3461 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3462 return Compatible;
3463 }
3464
Chris Lattner4b009652007-07-25 00:24:17 +00003465 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003466 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3467 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003468
Chris Lattner4b009652007-07-25 00:24:17 +00003469 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003470 lhptee = Context.getCanonicalType(lhptee);
3471 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003472
Chris Lattner005ed752008-01-04 18:04:52 +00003473 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003474
3475 // C99 6.5.16.1p1: This following citation is common to constraints
3476 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3477 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003478 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003479 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003480 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003481
Mike Stump9afab102009-02-19 03:04:26 +00003482 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3483 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003484 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003485 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003486 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003487 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003488
Chris Lattner4ca3d772008-01-03 22:56:36 +00003489 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003490 assert(rhptee->isFunctionType());
3491 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003492 }
Mike Stump9afab102009-02-19 03:04:26 +00003493
Chris Lattner4ca3d772008-01-03 22:56:36 +00003494 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003495 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003496 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003497
3498 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003499 assert(lhptee->isFunctionType());
3500 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003501 }
Mike Stump9afab102009-02-19 03:04:26 +00003502 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003503 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003504 lhptee = lhptee.getUnqualifiedType();
3505 rhptee = rhptee.getUnqualifiedType();
3506 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3507 // Check if the pointee types are compatible ignoring the sign.
3508 // We explicitly check for char so that we catch "char" vs
3509 // "unsigned char" on systems where "char" is unsigned.
3510 if (lhptee->isCharType()) {
3511 lhptee = Context.UnsignedCharTy;
3512 } else if (lhptee->isSignedIntegerType()) {
3513 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3514 }
3515 if (rhptee->isCharType()) {
3516 rhptee = Context.UnsignedCharTy;
3517 } else if (rhptee->isSignedIntegerType()) {
3518 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3519 }
3520 if (lhptee == rhptee) {
3521 // Types are compatible ignoring the sign. Qualifier incompatibility
3522 // takes priority over sign incompatibility because the sign
3523 // warning can be disabled.
3524 if (ConvTy != Compatible)
3525 return ConvTy;
3526 return IncompatiblePointerSign;
3527 }
3528 // General pointer incompatibility takes priority over qualifiers.
3529 return IncompatiblePointer;
3530 }
Chris Lattner005ed752008-01-04 18:04:52 +00003531 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003532}
3533
Steve Naroff3454b6c2008-09-04 15:10:53 +00003534/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3535/// block pointer types are compatible or whether a block and normal pointer
3536/// are compatible. It is more restrict than comparing two function pointer
3537// types.
Mike Stump9afab102009-02-19 03:04:26 +00003538Sema::AssignConvertType
3539Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003540 QualType rhsType) {
3541 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003542
Steve Naroff3454b6c2008-09-04 15:10:53 +00003543 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003544 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3545 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003546
Steve Naroff3454b6c2008-09-04 15:10:53 +00003547 // make sure we operate on the canonical type
3548 lhptee = Context.getCanonicalType(lhptee);
3549 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003550
Steve Naroff3454b6c2008-09-04 15:10:53 +00003551 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003552
Steve Naroff3454b6c2008-09-04 15:10:53 +00003553 // For blocks we enforce that qualifiers are identical.
3554 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3555 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003556
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003557 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003558 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003559 return ConvTy;
3560}
3561
Mike Stump9afab102009-02-19 03:04:26 +00003562/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3563/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003564/// pointers. Here are some objectionable examples that GCC considers warnings:
3565///
3566/// int a, *pint;
3567/// short *pshort;
3568/// struct foo *pfoo;
3569///
3570/// pint = pshort; // warning: assignment from incompatible pointer type
3571/// a = pint; // warning: assignment makes integer from pointer without a cast
3572/// pint = a; // warning: assignment makes pointer from integer without a cast
3573/// pint = pfoo; // warning: assignment from incompatible pointer type
3574///
3575/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003576/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003577///
Chris Lattner005ed752008-01-04 18:04:52 +00003578Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003579Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003580 // Get canonical types. We're not formatting these types, just comparing
3581 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003582 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3583 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003584
3585 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003586 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003587
David Chisnall44663db2009-08-17 16:35:33 +00003588 if ((lhsType->isObjCClassType() &&
3589 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3590 (rhsType->isObjCClassType() &&
3591 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3592 return Compatible;
3593 }
3594
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003595 // If the left-hand side is a reference type, then we are in a
3596 // (rare!) case where we've allowed the use of references in C,
3597 // e.g., as a parameter type in a built-in function. In this case,
3598 // just make sure that the type referenced is compatible with the
3599 // right-hand side type. The caller is responsible for adjusting
3600 // lhsType so that the resulting expression does not have reference
3601 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003602 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003603 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003604 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003605 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003606 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003607 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3608 // to the same ExtVector type.
3609 if (lhsType->isExtVectorType()) {
3610 if (rhsType->isExtVectorType())
3611 return lhsType == rhsType ? Compatible : Incompatible;
3612 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3613 return Compatible;
3614 }
3615
Nate Begemanc5f0f652008-07-14 18:02:46 +00003616 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003617 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003618 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003619 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003620 if (getLangOptions().LaxVectorConversions &&
3621 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003622 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003623 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003624 }
3625 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003626 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003627
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003628 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003629 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003630
Chris Lattner390564e2008-04-07 06:49:41 +00003631 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003632 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003633 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003634
Chris Lattner390564e2008-04-07 06:49:41 +00003635 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003636 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003637
Steve Naroff8194a542009-07-20 17:56:53 +00003638 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003639 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003640 if (lhsType->isVoidPointerType()) // an exception to the rule.
3641 return Compatible;
3642 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003643 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003644 if (rhsType->getAs<BlockPointerType>()) {
3645 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003646 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003647
3648 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003649 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003650 return Compatible;
3651 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003652 return Incompatible;
3653 }
3654
3655 if (isa<BlockPointerType>(lhsType)) {
3656 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003657 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003658
Steve Naroffa982c712008-09-29 18:10:17 +00003659 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003660 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003661 return Compatible;
3662
Steve Naroff3454b6c2008-09-04 15:10:53 +00003663 if (rhsType->isBlockPointerType())
3664 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003665
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003666 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003667 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003668 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003669 }
Chris Lattner1853da22008-01-04 23:18:45 +00003670 return Incompatible;
3671 }
3672
Steve Naroff329ec222009-07-10 23:34:53 +00003673 if (isa<ObjCObjectPointerType>(lhsType)) {
3674 if (rhsType->isIntegerType())
3675 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003676
3677 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003678 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003679 if (rhsType->isVoidPointerType()) // an exception to the rule.
3680 return Compatible;
3681 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003682 }
3683 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003684 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3685 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003686 if (Context.typesAreCompatible(lhsType, rhsType))
3687 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003688 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3689 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003690 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003691 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003692 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003693 if (RHSPT->getPointeeType()->isVoidType())
3694 return Compatible;
3695 }
3696 // Treat block pointers as objects.
3697 if (rhsType->isBlockPointerType())
3698 return Compatible;
3699 return Incompatible;
3700 }
Chris Lattner390564e2008-04-07 06:49:41 +00003701 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003702 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003703 if (lhsType == Context.BoolTy)
3704 return Compatible;
3705
3706 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003707 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003708
Mike Stump9afab102009-02-19 03:04:26 +00003709 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003710 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003711
3712 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003713 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003714 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003715 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003716 }
Steve Naroff329ec222009-07-10 23:34:53 +00003717 if (isa<ObjCObjectPointerType>(rhsType)) {
3718 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3719 if (lhsType == Context.BoolTy)
3720 return Compatible;
3721
3722 if (lhsType->isIntegerType())
3723 return PointerToInt;
3724
Steve Naroff8194a542009-07-20 17:56:53 +00003725 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003726 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003727 if (lhsType->isVoidPointerType()) // an exception to the rule.
3728 return Compatible;
3729 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003730 }
3731 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003732 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003733 return Compatible;
3734 return Incompatible;
3735 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003736
Chris Lattner1853da22008-01-04 23:18:45 +00003737 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003738 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003739 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003740 }
3741 return Incompatible;
3742}
3743
Douglas Gregor144b06c2009-04-29 22:16:16 +00003744/// \brief Constructs a transparent union from an expression that is
3745/// used to initialize the transparent union.
3746static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3747 QualType UnionType, FieldDecl *Field) {
3748 // Build an initializer list that designates the appropriate member
3749 // of the transparent union.
3750 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3751 &E, 1,
3752 SourceLocation());
3753 Initializer->setType(UnionType);
3754 Initializer->setInitializedFieldInUnion(Field);
3755
3756 // Build a compound literal constructing a value of the transparent
3757 // union type from this initializer list.
3758 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3759 false);
3760}
3761
3762Sema::AssignConvertType
3763Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3764 QualType FromType = rExpr->getType();
3765
3766 // If the ArgType is a Union type, we want to handle a potential
3767 // transparent_union GCC extension.
3768 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003769 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003770 return Incompatible;
3771
3772 // The field to initialize within the transparent union.
3773 RecordDecl *UD = UT->getDecl();
3774 FieldDecl *InitField = 0;
3775 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003776 for (RecordDecl::field_iterator it = UD->field_begin(),
3777 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003778 it != itend; ++it) {
3779 if (it->getType()->isPointerType()) {
3780 // If the transparent union contains a pointer type, we allow:
3781 // 1) void pointer
3782 // 2) null pointer constant
3783 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003784 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003785 ImpCastExprToType(rExpr, it->getType());
3786 InitField = *it;
3787 break;
3788 }
3789
3790 if (rExpr->isNullPointerConstant(Context)) {
3791 ImpCastExprToType(rExpr, it->getType());
3792 InitField = *it;
3793 break;
3794 }
3795 }
3796
3797 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3798 == Compatible) {
3799 InitField = *it;
3800 break;
3801 }
3802 }
3803
3804 if (!InitField)
3805 return Incompatible;
3806
3807 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3808 return Compatible;
3809}
3810
Chris Lattner005ed752008-01-04 18:04:52 +00003811Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003812Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003813 if (getLangOptions().CPlusPlus) {
3814 if (!lhsType->isRecordType()) {
3815 // C++ 5.17p3: If the left operand is not of class type, the
3816 // expression is implicitly converted (C++ 4) to the
3817 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003818 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3819 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003820 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003821 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003822 }
3823
3824 // FIXME: Currently, we fall through and treat C++ classes like C
3825 // structures.
3826 }
3827
Steve Naroffcdee22d2007-11-27 17:58:44 +00003828 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3829 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003830 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003831 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003832 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003833 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003834 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003835 return Compatible;
3836 }
Mike Stump9afab102009-02-19 03:04:26 +00003837
Chris Lattner5f505bf2007-10-16 02:55:40 +00003838 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003839 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003840 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003841 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003842 //
Mike Stump9afab102009-02-19 03:04:26 +00003843 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003844 if (!lhsType->isReferenceType())
3845 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003846
Chris Lattner005ed752008-01-04 18:04:52 +00003847 Sema::AssignConvertType result =
3848 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003849
Steve Naroff0f32f432007-08-24 22:33:52 +00003850 // C99 6.5.16.1p2: The value of the right operand is converted to the
3851 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003852 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3853 // so that we can use references in built-in functions even in C.
3854 // The getNonReferenceType() call makes sure that the resulting expression
3855 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003856 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003857 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003858 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003859}
3860
Chris Lattner1eafdea2008-11-18 01:30:42 +00003861QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003862 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003863 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003864 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003865 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003866}
3867
Mike Stump9afab102009-02-19 03:04:26 +00003868inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003869 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003870 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003871 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003872 QualType lhsType =
3873 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3874 QualType rhsType =
3875 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003876
Nate Begemanc5f0f652008-07-14 18:02:46 +00003877 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003878 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003879 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003880
Nate Begemanc5f0f652008-07-14 18:02:46 +00003881 // Handle the case of a vector & extvector type of the same size and element
3882 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003883 if (getLangOptions().LaxVectorConversions) {
3884 // FIXME: Should we warn here?
3885 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003886 if (const VectorType *RV = rhsType->getAsVectorType())
3887 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003888 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003889 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003890 }
3891 }
3892 }
Mike Stump9afab102009-02-19 03:04:26 +00003893
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003894 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3895 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3896 bool swapped = false;
3897 if (rhsType->isExtVectorType()) {
3898 swapped = true;
3899 std::swap(rex, lex);
3900 std::swap(rhsType, lhsType);
3901 }
3902
Nate Begemanf1695892009-06-28 19:12:57 +00003903 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003904 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3905 QualType EltTy = LV->getElementType();
3906 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3907 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003908 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003909 if (swapped) std::swap(rex, lex);
3910 return lhsType;
3911 }
3912 }
3913 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3914 rhsType->isRealFloatingType()) {
3915 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003916 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003917 if (swapped) std::swap(rex, lex);
3918 return lhsType;
3919 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003920 }
3921 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003922
Nate Begemanf1695892009-06-28 19:12:57 +00003923 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003924 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003925 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003926 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003927 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003928}
3929
Chris Lattner4b009652007-07-25 00:24:17 +00003930inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003931 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003932{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003933 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003934 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003935
Steve Naroff8f708362007-08-24 19:07:16 +00003936 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003937
Chris Lattner4b009652007-07-25 00:24:17 +00003938 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003939 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003940 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003941}
3942
3943inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003944 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003945{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003946 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3947 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3948 return CheckVectorOperands(Loc, lex, rex);
3949 return InvalidOperands(Loc, lex, rex);
3950 }
Chris Lattner4b009652007-07-25 00:24:17 +00003951
Steve Naroff8f708362007-08-24 19:07:16 +00003952 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003953
Chris Lattner4b009652007-07-25 00:24:17 +00003954 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003955 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003956 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003957}
3958
3959inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003960 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003961{
Eli Friedman3cd92882009-03-28 01:22:36 +00003962 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3963 QualType compType = CheckVectorOperands(Loc, lex, rex);
3964 if (CompLHSTy) *CompLHSTy = compType;
3965 return compType;
3966 }
Chris Lattner4b009652007-07-25 00:24:17 +00003967
Eli Friedman3cd92882009-03-28 01:22:36 +00003968 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003969
Chris Lattner4b009652007-07-25 00:24:17 +00003970 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003971 if (lex->getType()->isArithmeticType() &&
3972 rex->getType()->isArithmeticType()) {
3973 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003974 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003975 }
Chris Lattner4b009652007-07-25 00:24:17 +00003976
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003977 // Put any potential pointer into PExp
3978 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00003979 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003980 std::swap(PExp, IExp);
3981
Steve Naroff79ae19a2009-07-14 18:25:06 +00003982 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003983
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003984 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00003985 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00003986
Chris Lattner184f92d2009-04-24 23:50:08 +00003987 // Check for arithmetic on pointers to incomplete types.
3988 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003989 if (getLangOptions().CPlusPlus) {
3990 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003991 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003992 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003993 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003994
3995 // GNU extension: arithmetic on pointer to void
3996 Diag(Loc, diag::ext_gnu_void_ptr)
3997 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003998 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003999 if (getLangOptions().CPlusPlus) {
4000 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4001 << lex->getType() << lex->getSourceRange();
4002 return QualType();
4003 }
4004
4005 // GNU extension: arithmetic on pointer to function
4006 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4007 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004008 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004009 // Check if we require a complete type.
4010 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004011 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004012 PExp->getType()->isObjCObjectPointerType()) &&
4013 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004014 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4015 << PExp->getSourceRange()
4016 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00004017 return QualType();
4018 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004019 // Diagnose bad cases where we step over interface counts.
4020 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4021 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4022 << PointeeTy << PExp->getSourceRange();
4023 return QualType();
4024 }
4025
Eli Friedman3cd92882009-03-28 01:22:36 +00004026 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004027 QualType LHSTy = Context.isPromotableBitField(lex);
4028 if (LHSTy.isNull()) {
4029 LHSTy = lex->getType();
4030 if (LHSTy->isPromotableIntegerType())
4031 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004032 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004033 *CompLHSTy = LHSTy;
4034 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004035 return PExp->getType();
4036 }
4037 }
4038
Chris Lattner1eafdea2008-11-18 01:30:42 +00004039 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004040}
4041
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004042// C99 6.5.6
4043QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004044 SourceLocation Loc, QualType* CompLHSTy) {
4045 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4046 QualType compType = CheckVectorOperands(Loc, lex, rex);
4047 if (CompLHSTy) *CompLHSTy = compType;
4048 return compType;
4049 }
Mike Stump9afab102009-02-19 03:04:26 +00004050
Eli Friedman3cd92882009-03-28 01:22:36 +00004051 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004052
Chris Lattnerf6da2912007-12-09 21:53:25 +00004053 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004054
Chris Lattnerf6da2912007-12-09 21:53:25 +00004055 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004056 if (lex->getType()->isArithmeticType()
4057 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004058 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004059 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004060 }
Steve Naroff329ec222009-07-10 23:34:53 +00004061
Chris Lattnerf6da2912007-12-09 21:53:25 +00004062 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004063 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004064 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004065
Douglas Gregor05e28f62009-03-24 19:52:54 +00004066 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004067
Douglas Gregor05e28f62009-03-24 19:52:54 +00004068 bool ComplainAboutVoid = false;
4069 Expr *ComplainAboutFunc = 0;
4070 if (lpointee->isVoidType()) {
4071 if (getLangOptions().CPlusPlus) {
4072 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4073 << lex->getSourceRange() << rex->getSourceRange();
4074 return QualType();
4075 }
4076
4077 // GNU C extension: arithmetic on pointer to void
4078 ComplainAboutVoid = true;
4079 } else if (lpointee->isFunctionType()) {
4080 if (getLangOptions().CPlusPlus) {
4081 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004082 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004083 return QualType();
4084 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004085
4086 // GNU C extension: arithmetic on pointer to function
4087 ComplainAboutFunc = lex;
4088 } else if (!lpointee->isDependentType() &&
4089 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004090 PDiag(diag::err_typecheck_sub_ptr_object)
4091 << lex->getSourceRange()
4092 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004093 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004094
Chris Lattner184f92d2009-04-24 23:50:08 +00004095 // Diagnose bad cases where we step over interface counts.
4096 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4097 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4098 << lpointee << lex->getSourceRange();
4099 return QualType();
4100 }
4101
Chris Lattnerf6da2912007-12-09 21:53:25 +00004102 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004103 if (rex->getType()->isIntegerType()) {
4104 if (ComplainAboutVoid)
4105 Diag(Loc, diag::ext_gnu_void_ptr)
4106 << lex->getSourceRange() << rex->getSourceRange();
4107 if (ComplainAboutFunc)
4108 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4109 << ComplainAboutFunc->getType()
4110 << ComplainAboutFunc->getSourceRange();
4111
Eli Friedman3cd92882009-03-28 01:22:36 +00004112 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004113 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004114 }
Mike Stump9afab102009-02-19 03:04:26 +00004115
Chris Lattnerf6da2912007-12-09 21:53:25 +00004116 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004117 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004118 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004119
Douglas Gregor05e28f62009-03-24 19:52:54 +00004120 // RHS must be a completely-type object type.
4121 // Handle the GNU void* extension.
4122 if (rpointee->isVoidType()) {
4123 if (getLangOptions().CPlusPlus) {
4124 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4125 << lex->getSourceRange() << rex->getSourceRange();
4126 return QualType();
4127 }
Mike Stump9afab102009-02-19 03:04:26 +00004128
Douglas Gregor05e28f62009-03-24 19:52:54 +00004129 ComplainAboutVoid = true;
4130 } else if (rpointee->isFunctionType()) {
4131 if (getLangOptions().CPlusPlus) {
4132 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004133 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004134 return QualType();
4135 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004136
4137 // GNU extension: arithmetic on pointer to function
4138 if (!ComplainAboutFunc)
4139 ComplainAboutFunc = rex;
4140 } else if (!rpointee->isDependentType() &&
4141 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004142 PDiag(diag::err_typecheck_sub_ptr_object)
4143 << rex->getSourceRange()
4144 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004145 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004146
Eli Friedman143ddc92009-05-16 13:54:38 +00004147 if (getLangOptions().CPlusPlus) {
4148 // Pointee types must be the same: C++ [expr.add]
4149 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4150 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4151 << lex->getType() << rex->getType()
4152 << lex->getSourceRange() << rex->getSourceRange();
4153 return QualType();
4154 }
4155 } else {
4156 // Pointee types must be compatible C99 6.5.6p3
4157 if (!Context.typesAreCompatible(
4158 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4159 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4160 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4161 << lex->getType() << rex->getType()
4162 << lex->getSourceRange() << rex->getSourceRange();
4163 return QualType();
4164 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004165 }
Mike Stump9afab102009-02-19 03:04:26 +00004166
Douglas Gregor05e28f62009-03-24 19:52:54 +00004167 if (ComplainAboutVoid)
4168 Diag(Loc, diag::ext_gnu_void_ptr)
4169 << lex->getSourceRange() << rex->getSourceRange();
4170 if (ComplainAboutFunc)
4171 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4172 << ComplainAboutFunc->getType()
4173 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004174
4175 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004176 return Context.getPointerDiffType();
4177 }
4178 }
Mike Stump9afab102009-02-19 03:04:26 +00004179
Chris Lattner1eafdea2008-11-18 01:30:42 +00004180 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004181}
4182
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004183// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004184QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004185 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004186 // C99 6.5.7p2: Each of the operands shall have integer type.
4187 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004188 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004189
Chris Lattner2c8bff72007-12-12 05:47:28 +00004190 // Shifts don't perform usual arithmetic conversions, they just do integer
4191 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004192 QualType LHSTy = Context.isPromotableBitField(lex);
4193 if (LHSTy.isNull()) {
4194 LHSTy = lex->getType();
4195 if (LHSTy->isPromotableIntegerType())
4196 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004197 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004198 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004199 ImpCastExprToType(lex, LHSTy);
4200
Chris Lattner2c8bff72007-12-12 05:47:28 +00004201 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004202
Ryan Flynnf109fff2009-08-07 16:20:20 +00004203 // Sanity-check shift operands
4204 llvm::APSInt Right;
4205 // Check right/shifter operand
4206 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004207 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004208 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4209 else {
4210 llvm::APInt LeftBits(Right.getBitWidth(),
4211 Context.getTypeSize(lex->getType()));
4212 if (Right.uge(LeftBits))
4213 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4214 }
4215 }
4216
Chris Lattner2c8bff72007-12-12 05:47:28 +00004217 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004218 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004219}
4220
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004221// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004222QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004223 unsigned OpaqueOpc, bool isRelational) {
4224 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4225
Nate Begemanc5f0f652008-07-14 18:02:46 +00004226 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004227 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004228
Chris Lattner254f3bc2007-08-26 01:18:55 +00004229 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004230 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4231 UsualArithmeticConversions(lex, rex);
4232 else {
4233 UsualUnaryConversions(lex);
4234 UsualUnaryConversions(rex);
4235 }
Chris Lattner4b009652007-07-25 00:24:17 +00004236 QualType lType = lex->getType();
4237 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004238
Mike Stumpea3d74e2009-05-07 18:43:07 +00004239 if (!lType->isFloatingType()
4240 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004241 // For non-floating point types, check for self-comparisons of the form
4242 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4243 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004244 // NOTE: Don't warn about comparisons of enum constants. These can arise
4245 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004246 Expr *LHSStripped = lex->IgnoreParens();
4247 Expr *RHSStripped = rex->IgnoreParens();
4248 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4249 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004250 if (DRL->getDecl() == DRR->getDecl() &&
4251 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004252 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004253
4254 if (isa<CastExpr>(LHSStripped))
4255 LHSStripped = LHSStripped->IgnoreParenCasts();
4256 if (isa<CastExpr>(RHSStripped))
4257 RHSStripped = RHSStripped->IgnoreParenCasts();
4258
4259 // Warn about comparisons against a string constant (unless the other
4260 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004261 Expr *literalString = 0;
4262 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004263 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004264 !RHSStripped->isNullPointerConstant(Context)) {
4265 literalString = lex;
4266 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004267 } else if ((isa<StringLiteral>(RHSStripped) ||
4268 isa<ObjCEncodeExpr>(RHSStripped)) &&
4269 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004270 literalString = rex;
4271 literalStringStripped = RHSStripped;
4272 }
4273
4274 if (literalString) {
4275 std::string resultComparison;
4276 switch (Opc) {
4277 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4278 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4279 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4280 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4281 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4282 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4283 default: assert(false && "Invalid comparison operator");
4284 }
4285 Diag(Loc, diag::warn_stringcompare)
4286 << isa<ObjCEncodeExpr>(literalStringStripped)
4287 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004288 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4289 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4290 "strcmp(")
4291 << CodeModificationHint::CreateInsertion(
4292 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004293 resultComparison);
4294 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004295 }
Mike Stump9afab102009-02-19 03:04:26 +00004296
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004297 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004298 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004299
Chris Lattner254f3bc2007-08-26 01:18:55 +00004300 if (isRelational) {
4301 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004302 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004303 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004304 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004305 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004306 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004307 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004308 }
Mike Stump9afab102009-02-19 03:04:26 +00004309
Chris Lattner254f3bc2007-08-26 01:18:55 +00004310 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004311 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004312 }
Mike Stump9afab102009-02-19 03:04:26 +00004313
Chris Lattner22be8422007-08-26 01:10:14 +00004314 bool LHSIsNull = lex->isNullPointerConstant(Context);
4315 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004316
Chris Lattner254f3bc2007-08-26 01:18:55 +00004317 // All of the following pointer related warnings are GCC extensions, except
4318 // when handling null pointer constants. One day, we can consider making them
4319 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004320 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004321 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004322 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004323 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004324 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004325
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004326 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004327 if (LCanPointeeTy == RCanPointeeTy)
4328 return ResultTy;
4329
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004330 // C++ [expr.rel]p2:
4331 // [...] Pointer conversions (4.10) and qualification
4332 // conversions (4.4) are performed on pointer operands (or on
4333 // a pointer operand and a null pointer constant) to bring
4334 // them to their composite pointer type. [...]
4335 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004336 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004337 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004338 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004339 if (T.isNull()) {
4340 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4341 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4342 return QualType();
4343 }
4344
4345 ImpCastExprToType(lex, T);
4346 ImpCastExprToType(rex, T);
4347 return ResultTy;
4348 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004349 // C99 6.5.9p2 and C99 6.5.8p2
4350 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4351 RCanPointeeTy.getUnqualifiedType())) {
4352 // Valid unless a relational comparison of function pointers
4353 if (isRelational && LCanPointeeTy->isFunctionType()) {
4354 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4355 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4356 }
4357 } else if (!isRelational &&
4358 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4359 // Valid unless comparison between non-null pointer and function pointer
4360 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4361 && !LHSIsNull && !RHSIsNull) {
4362 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4363 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4364 }
4365 } else {
4366 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004367 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004368 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004369 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004370 if (LCanPointeeTy != RCanPointeeTy)
4371 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004372 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004373 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004374
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004375 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004376 // Comparison of pointers with null pointer constants and equality
4377 // comparisons of member pointers to null pointer constants.
4378 if (RHSIsNull &&
4379 (lType->isPointerType() ||
4380 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004381 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004382 return ResultTy;
4383 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004384 if (LHSIsNull &&
4385 (rType->isPointerType() ||
4386 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004387 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004388 return ResultTy;
4389 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004390
4391 // Comparison of member pointers.
4392 if (!isRelational &&
4393 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4394 // C++ [expr.eq]p2:
4395 // In addition, pointers to members can be compared, or a pointer to
4396 // member and a null pointer constant. Pointer to member conversions
4397 // (4.11) and qualification conversions (4.4) are performed to bring
4398 // them to a common type. If one operand is a null pointer constant,
4399 // the common type is the type of the other operand. Otherwise, the
4400 // common type is a pointer to member type similar (4.4) to the type
4401 // of one of the operands, with a cv-qualification signature (4.4)
4402 // that is the union of the cv-qualification signatures of the operand
4403 // types.
4404 QualType T = FindCompositePointerType(lex, rex);
4405 if (T.isNull()) {
4406 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4407 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4408 return QualType();
4409 }
4410
4411 ImpCastExprToType(lex, T);
4412 ImpCastExprToType(rex, T);
4413 return ResultTy;
4414 }
4415
4416 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004417 if (lType->isNullPtrType() && rType->isNullPtrType())
4418 return ResultTy;
4419 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004420
Steve Naroff3454b6c2008-09-04 15:10:53 +00004421 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004422 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004423 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4424 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004425
Steve Naroff3454b6c2008-09-04 15:10:53 +00004426 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004427 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004428 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004429 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004430 }
4431 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004432 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004433 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004434 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004435 if (!isRelational
4436 && ((lType->isBlockPointerType() && rType->isPointerType())
4437 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004438 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004439 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004440 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004441 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004442 ->getPointeeType()->isVoidType())))
4443 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4444 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004445 }
4446 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004447 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004448 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004449
Steve Naroff329ec222009-07-10 23:34:53 +00004450 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004451 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004452 const PointerType *LPT = lType->getAs<PointerType>();
4453 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004454 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004455 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004456 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004457 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004458
Steve Naroff030fcda2008-11-17 19:49:16 +00004459 if (!LPtrToVoid && !RPtrToVoid &&
4460 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004461 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004462 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004463 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004464 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004465 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004466 }
Steve Naroff329ec222009-07-10 23:34:53 +00004467 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004468 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004469 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4470 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004471 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004472 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004473 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004474 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004475 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004476 unsigned DiagID = 0;
4477 if (RHSIsNull) {
4478 if (isRelational)
4479 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4480 } else if (isRelational)
4481 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4482 else
4483 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4484
4485 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004486 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004487 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004488 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004489 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004490 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004491 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004492 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004493 unsigned DiagID = 0;
4494 if (LHSIsNull) {
4495 if (isRelational)
4496 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4497 } else if (isRelational)
4498 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4499 else
4500 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004501
Chris Lattner124569f2009-08-23 00:03:44 +00004502 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004503 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004504 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004505 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004506 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004507 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004508 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004509 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004510 if (!isRelational && RHSIsNull
4511 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004512 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004513 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004514 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004515 if (!isRelational && LHSIsNull
4516 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004517 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004518 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004519 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004520 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004521}
4522
Nate Begemanc5f0f652008-07-14 18:02:46 +00004523/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004524/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004525/// like a scalar comparison, a vector comparison produces a vector of integer
4526/// types.
4527QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004528 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004529 bool isRelational) {
4530 // Check to make sure we're operating on vectors of the same type and width,
4531 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004532 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004533 if (vType.isNull())
4534 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004535
Nate Begemanc5f0f652008-07-14 18:02:46 +00004536 QualType lType = lex->getType();
4537 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004538
Nate Begemanc5f0f652008-07-14 18:02:46 +00004539 // For non-floating point types, check for self-comparisons of the form
4540 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4541 // often indicate logic errors in the program.
4542 if (!lType->isFloatingType()) {
4543 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4544 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4545 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004546 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004547 }
Mike Stump9afab102009-02-19 03:04:26 +00004548
Nate Begemanc5f0f652008-07-14 18:02:46 +00004549 // Check for comparisons of floating point operands using != and ==.
4550 if (!isRelational && lType->isFloatingType()) {
4551 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004552 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004553 }
Mike Stump9afab102009-02-19 03:04:26 +00004554
Nate Begemanc5f0f652008-07-14 18:02:46 +00004555 // Return the type for the comparison, which is the same as vector type for
4556 // integer vectors, or an integer type of identical size and number of
4557 // elements for floating point vectors.
4558 if (lType->isIntegerType())
4559 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004560
Nate Begemanc5f0f652008-07-14 18:02:46 +00004561 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004562 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004563 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004564 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004565 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004566 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4567
Mike Stump9afab102009-02-19 03:04:26 +00004568 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004569 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004570 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4571}
4572
Chris Lattner4b009652007-07-25 00:24:17 +00004573inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004574 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004575{
4576 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004577 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004578
Steve Naroff8f708362007-08-24 19:07:16 +00004579 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004580
Chris Lattner4b009652007-07-25 00:24:17 +00004581 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004582 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004583 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004584}
4585
4586inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004587 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004588{
4589 UsualUnaryConversions(lex);
4590 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004591
Eli Friedmanbea3f842008-05-13 20:16:47 +00004592 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004593 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004594 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004595}
4596
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004597/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4598/// is a read-only property; return true if so. A readonly property expression
4599/// depends on various declarations and thus must be treated specially.
4600///
Mike Stump9afab102009-02-19 03:04:26 +00004601static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004602{
4603 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4604 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4605 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4606 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004607 if (const ObjCObjectPointerType *OPT =
4608 BaseType->getAsObjCInterfacePointerType())
4609 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4610 if (S.isPropertyReadonly(PDecl, IFace))
4611 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004612 }
4613 }
4614 return false;
4615}
4616
Chris Lattner4c2642c2008-11-18 01:22:49 +00004617/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4618/// emit an error and return true. If so, return false.
4619static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004620 SourceLocation OrigLoc = Loc;
4621 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4622 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004623 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4624 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004625 if (IsLV == Expr::MLV_Valid)
4626 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004627
Chris Lattner4c2642c2008-11-18 01:22:49 +00004628 unsigned Diag = 0;
4629 bool NeedType = false;
4630 switch (IsLV) { // C99 6.5.16p2
4631 default: assert(0 && "Unknown result from isModifiableLvalue!");
4632 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004633 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004634 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4635 NeedType = true;
4636 break;
Mike Stump9afab102009-02-19 03:04:26 +00004637 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004638 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4639 NeedType = true;
4640 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004641 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004642 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4643 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004644 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004645 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4646 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004647 case Expr::MLV_IncompleteType:
4648 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004649 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00004650 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4651 << E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004652 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004653 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4654 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004655 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004656 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4657 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004658 case Expr::MLV_ReadonlyProperty:
4659 Diag = diag::error_readonly_property_assignment;
4660 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004661 case Expr::MLV_NoSetterProperty:
4662 Diag = diag::error_nosetter_property_assignment;
4663 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004664 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004665
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004666 SourceRange Assign;
4667 if (Loc != OrigLoc)
4668 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004669 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004670 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004671 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004672 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004673 return true;
4674}
4675
4676
4677
4678// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004679QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4680 SourceLocation Loc,
4681 QualType CompoundType) {
4682 // Verify that LHS is a modifiable lvalue, and emit error if not.
4683 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004684 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004685
4686 QualType LHSType = LHS->getType();
4687 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004688
Chris Lattner005ed752008-01-04 18:04:52 +00004689 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004690 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004691 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004692 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004693 // Special case of NSObject attributes on c-style pointer types.
4694 if (ConvTy == IncompatiblePointer &&
4695 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004696 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004697 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004698 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004699 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004700
Chris Lattner34c85082008-08-21 18:04:13 +00004701 // If the RHS is a unary plus or minus, check to see if they = and + are
4702 // right next to each other. If so, the user may have typo'd "x =+ 4"
4703 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004704 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004705 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4706 RHSCheck = ICE->getSubExpr();
4707 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4708 if ((UO->getOpcode() == UnaryOperator::Plus ||
4709 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004710 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004711 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004712 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4713 // And there is a space or other character before the subexpr of the
4714 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004715 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4716 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004717 Diag(Loc, diag::warn_not_compound_assign)
4718 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4719 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004720 }
Chris Lattner34c85082008-08-21 18:04:13 +00004721 }
4722 } else {
4723 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004724 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004725 }
Chris Lattner005ed752008-01-04 18:04:52 +00004726
Chris Lattner1eafdea2008-11-18 01:30:42 +00004727 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4728 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004729 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004730
Chris Lattner4b009652007-07-25 00:24:17 +00004731 // C99 6.5.16p3: The type of an assignment expression is the type of the
4732 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004733 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004734 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4735 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004736 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004737 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004738 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004739}
4740
Chris Lattner1eafdea2008-11-18 01:30:42 +00004741// C99 6.5.17
4742QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004743 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004744 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004745
4746 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4747 // incomplete in C++).
4748
Chris Lattner1eafdea2008-11-18 01:30:42 +00004749 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004750}
4751
4752/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4753/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004754QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4755 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004756 if (Op->isTypeDependent())
4757 return Context.DependentTy;
4758
Chris Lattnere65182c2008-11-21 07:05:48 +00004759 QualType ResType = Op->getType();
4760 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004761
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004762 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4763 // Decrement of bool is not allowed.
4764 if (!isInc) {
4765 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4766 return QualType();
4767 }
4768 // Increment of bool sets it to true, but is deprecated.
4769 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4770 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004771 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004772 } else if (ResType->isAnyPointerType()) {
4773 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004774
Chris Lattnere65182c2008-11-21 07:05:48 +00004775 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004776 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004777 if (getLangOptions().CPlusPlus) {
4778 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4779 << Op->getSourceRange();
4780 return QualType();
4781 }
4782
4783 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004784 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004785 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004786 if (getLangOptions().CPlusPlus) {
4787 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4788 << Op->getType() << Op->getSourceRange();
4789 return QualType();
4790 }
4791
4792 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004793 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004794 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004795 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4796 << Op->getSourceRange()
4797 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004798 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004799 // Diagnose bad cases where we step over interface counts.
4800 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4801 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4802 << PointeeTy << Op->getSourceRange();
4803 return QualType();
4804 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004805 } else if (ResType->isComplexType()) {
4806 // C99 does not support ++/-- on complex types, we allow as an extension.
4807 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004808 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004809 } else {
4810 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004811 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004812 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004813 }
Mike Stump9afab102009-02-19 03:04:26 +00004814 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004815 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004816 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004817 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004818 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004819}
4820
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004821/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004822/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004823/// where the declaration is needed for type checking. We only need to
4824/// handle cases when the expression references a function designator
4825/// or is an lvalue. Here are some examples:
4826/// - &(x) => x
4827/// - &*****f => f for f a function designator.
4828/// - &s.xx => s
4829/// - &s.zz[1].yy -> s, if zz is an array
4830/// - *(x + 1) -> x, if x is an array
4831/// - &"123"[2] -> 0
4832/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004833static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004834 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004835 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004836 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004837 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004838 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004839 // If this is an arrow operator, the address is an offset from
4840 // the base's value, so the object the base refers to is
4841 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004842 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004843 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004844 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004845 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004846 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004847 // FIXME: This code shouldn't be necessary! We should catch the implicit
4848 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004849 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4850 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4851 if (ICE->getSubExpr()->getType()->isArrayType())
4852 return getPrimaryDecl(ICE->getSubExpr());
4853 }
4854 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004855 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004856 case Stmt::UnaryOperatorClass: {
4857 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004858
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004859 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004860 case UnaryOperator::Real:
4861 case UnaryOperator::Imag:
4862 case UnaryOperator::Extension:
4863 return getPrimaryDecl(UO->getSubExpr());
4864 default:
4865 return 0;
4866 }
4867 }
Chris Lattner4b009652007-07-25 00:24:17 +00004868 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004869 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004870 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004871 // If the result of an implicit cast is an l-value, we care about
4872 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004873 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004874 default:
4875 return 0;
4876 }
4877}
4878
4879/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004880/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004881/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004882/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004883/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004884/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004885/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004886QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004887 // Make sure to ignore parentheses in subsequent checks
4888 op = op->IgnoreParens();
4889
Douglas Gregore6be68a2008-12-17 22:52:20 +00004890 if (op->isTypeDependent())
4891 return Context.DependentTy;
4892
Steve Naroff9c6c3592008-01-13 17:10:08 +00004893 if (getLangOptions().C99) {
4894 // Implement C99-only parts of addressof rules.
4895 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4896 if (uOp->getOpcode() == UnaryOperator::Deref)
4897 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4898 // (assuming the deref expression is valid).
4899 return uOp->getSubExpr()->getType();
4900 }
4901 // Technically, there should be a check for array subscript
4902 // expressions here, but the result of one is always an lvalue anyway.
4903 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004904 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004905 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004906
Eli Friedman14ab4c42009-05-16 23:27:50 +00004907 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4908 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004909 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004910 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004911 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004912 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4913 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004914 return QualType();
4915 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004916 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004917 // The operand cannot be a bit-field
4918 Diag(OpLoc, diag::err_typecheck_address_of)
4919 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004920 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004921 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4922 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004923 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004924 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004925 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004926 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004927 } else if (isa<ObjCPropertyRefExpr>(op)) {
4928 // cannot take address of a property expression.
4929 Diag(OpLoc, diag::err_typecheck_address_of)
4930 << "property expression" << op->getSourceRange();
4931 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004932 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004933 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004934 // with the register storage-class specifier.
4935 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4936 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004937 Diag(OpLoc, diag::err_typecheck_address_of)
4938 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004939 return QualType();
4940 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004941 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4942 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004943 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004944 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004945 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004946 // Could be a pointer to member, though, if there is an explicit
4947 // scope qualifier for the class.
4948 if (isa<QualifiedDeclRefExpr>(op)) {
4949 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004950 if (Ctx && Ctx->isRecord()) {
4951 if (FD->getType()->isReferenceType()) {
4952 Diag(OpLoc,
4953 diag::err_cannot_form_pointer_to_member_of_reference_type)
4954 << FD->getDeclName() << FD->getType();
4955 return QualType();
4956 }
4957
Sebastian Redl0c9da212009-02-03 20:19:35 +00004958 return Context.getMemberPointerType(op->getType(),
4959 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004960 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004961 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004962 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004963 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004964 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004965 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4966 return Context.getMemberPointerType(op->getType(),
4967 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4968 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004969 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004970 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004971
Eli Friedman14ab4c42009-05-16 23:27:50 +00004972 if (lval == Expr::LV_IncompleteVoidType) {
4973 // Taking the address of a void variable is technically illegal, but we
4974 // allow it in cases which are otherwise valid.
4975 // Example: "extern void x; void* y = &x;".
4976 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4977 }
4978
Chris Lattner4b009652007-07-25 00:24:17 +00004979 // If the operand has type "type", the result has type "pointer to type".
4980 return Context.getPointerType(op->getType());
4981}
4982
Chris Lattnerda5c0872008-11-23 09:13:29 +00004983QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004984 if (Op->isTypeDependent())
4985 return Context.DependentTy;
4986
Chris Lattnerda5c0872008-11-23 09:13:29 +00004987 UsualUnaryConversions(Op);
4988 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004989
Chris Lattnerda5c0872008-11-23 09:13:29 +00004990 // Note that per both C89 and C99, this is always legal, even if ptype is an
4991 // incomplete type or void. It would be possible to warn about dereferencing
4992 // a void pointer, but it's completely well-defined, and such a warning is
4993 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004994 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004995 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004996
Steve Naroff329ec222009-07-10 23:34:53 +00004997 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4998 return OPT->getPointeeType();
4999
Chris Lattner77d52da2008-11-20 06:06:08 +00005000 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005001 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005002 return QualType();
5003}
5004
5005static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5006 tok::TokenKind Kind) {
5007 BinaryOperator::Opcode Opc;
5008 switch (Kind) {
5009 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005010 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5011 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005012 case tok::star: Opc = BinaryOperator::Mul; break;
5013 case tok::slash: Opc = BinaryOperator::Div; break;
5014 case tok::percent: Opc = BinaryOperator::Rem; break;
5015 case tok::plus: Opc = BinaryOperator::Add; break;
5016 case tok::minus: Opc = BinaryOperator::Sub; break;
5017 case tok::lessless: Opc = BinaryOperator::Shl; break;
5018 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5019 case tok::lessequal: Opc = BinaryOperator::LE; break;
5020 case tok::less: Opc = BinaryOperator::LT; break;
5021 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5022 case tok::greater: Opc = BinaryOperator::GT; break;
5023 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5024 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5025 case tok::amp: Opc = BinaryOperator::And; break;
5026 case tok::caret: Opc = BinaryOperator::Xor; break;
5027 case tok::pipe: Opc = BinaryOperator::Or; break;
5028 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5029 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5030 case tok::equal: Opc = BinaryOperator::Assign; break;
5031 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5032 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5033 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5034 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5035 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5036 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5037 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5038 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5039 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5040 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5041 case tok::comma: Opc = BinaryOperator::Comma; break;
5042 }
5043 return Opc;
5044}
5045
5046static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5047 tok::TokenKind Kind) {
5048 UnaryOperator::Opcode Opc;
5049 switch (Kind) {
5050 default: assert(0 && "Unknown unary op!");
5051 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5052 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5053 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5054 case tok::star: Opc = UnaryOperator::Deref; break;
5055 case tok::plus: Opc = UnaryOperator::Plus; break;
5056 case tok::minus: Opc = UnaryOperator::Minus; break;
5057 case tok::tilde: Opc = UnaryOperator::Not; break;
5058 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005059 case tok::kw___real: Opc = UnaryOperator::Real; break;
5060 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5061 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5062 }
5063 return Opc;
5064}
5065
Douglas Gregord7f915e2008-11-06 23:29:22 +00005066/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5067/// operator @p Opc at location @c TokLoc. This routine only supports
5068/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005069Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5070 unsigned Op,
5071 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005072 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005073 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005074 // The following two variables are used for compound assignment operators
5075 QualType CompLHSTy; // Type of LHS after promotions for computation
5076 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005077
5078 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005079 case BinaryOperator::Assign:
5080 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5081 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005082 case BinaryOperator::PtrMemD:
5083 case BinaryOperator::PtrMemI:
5084 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5085 Opc == BinaryOperator::PtrMemI);
5086 break;
5087 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005088 case BinaryOperator::Div:
5089 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5090 break;
5091 case BinaryOperator::Rem:
5092 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5093 break;
5094 case BinaryOperator::Add:
5095 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5096 break;
5097 case BinaryOperator::Sub:
5098 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5099 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005100 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005101 case BinaryOperator::Shr:
5102 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5103 break;
5104 case BinaryOperator::LE:
5105 case BinaryOperator::LT:
5106 case BinaryOperator::GE:
5107 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005108 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005109 break;
5110 case BinaryOperator::EQ:
5111 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005112 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005113 break;
5114 case BinaryOperator::And:
5115 case BinaryOperator::Xor:
5116 case BinaryOperator::Or:
5117 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5118 break;
5119 case BinaryOperator::LAnd:
5120 case BinaryOperator::LOr:
5121 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5122 break;
5123 case BinaryOperator::MulAssign:
5124 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005125 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5126 CompLHSTy = CompResultTy;
5127 if (!CompResultTy.isNull())
5128 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005129 break;
5130 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005131 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5132 CompLHSTy = CompResultTy;
5133 if (!CompResultTy.isNull())
5134 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005135 break;
5136 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005137 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5138 if (!CompResultTy.isNull())
5139 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005140 break;
5141 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005142 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5143 if (!CompResultTy.isNull())
5144 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005145 break;
5146 case BinaryOperator::ShlAssign:
5147 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005148 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5149 CompLHSTy = CompResultTy;
5150 if (!CompResultTy.isNull())
5151 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005152 break;
5153 case BinaryOperator::AndAssign:
5154 case BinaryOperator::XorAssign:
5155 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005156 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5157 CompLHSTy = CompResultTy;
5158 if (!CompResultTy.isNull())
5159 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005160 break;
5161 case BinaryOperator::Comma:
5162 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5163 break;
5164 }
5165 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005166 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005167 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005168 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5169 else
5170 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005171 CompLHSTy, CompResultTy,
5172 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005173}
5174
Chris Lattner4b009652007-07-25 00:24:17 +00005175// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005176Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5177 tok::TokenKind Kind,
5178 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005179 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005180 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005181
Steve Naroff87d58b42007-09-16 03:34:24 +00005182 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5183 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005184
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005185 if (getLangOptions().CPlusPlus &&
5186 (lhs->getType()->isOverloadableType() ||
5187 rhs->getType()->isOverloadableType())) {
5188 // Find all of the overloaded operators visible from this
5189 // point. We perform both an operator-name lookup from the local
5190 // scope and an argument-dependent lookup based on the types of
5191 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005192 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005193 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5194 if (OverOp != OO_None) {
5195 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5196 Functions);
5197 Expr *Args[2] = { lhs, rhs };
5198 DeclarationName OpName
5199 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5200 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005201 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005202
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005203 // Build the (potentially-overloaded, potentially-dependent)
5204 // binary operation.
5205 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005206 }
5207
Douglas Gregord7f915e2008-11-06 23:29:22 +00005208 // Build a built-in binary operation.
5209 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005210}
5211
Douglas Gregorc78182d2009-03-13 23:49:33 +00005212Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5213 unsigned OpcIn,
5214 ExprArg InputArg) {
5215 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005216
Mike Stumpe127ae32009-05-16 07:39:55 +00005217 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005218 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005219 QualType resultType;
5220 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005221 case UnaryOperator::OffsetOf:
5222 assert(false && "Invalid unary operator");
5223 break;
5224
Chris Lattner4b009652007-07-25 00:24:17 +00005225 case UnaryOperator::PreInc:
5226 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005227 case UnaryOperator::PostInc:
5228 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005229 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005230 Opc == UnaryOperator::PreInc ||
5231 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005232 break;
Mike Stump9afab102009-02-19 03:04:26 +00005233 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005234 resultType = CheckAddressOfOperand(Input, OpLoc);
5235 break;
Mike Stump9afab102009-02-19 03:04:26 +00005236 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005237 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005238 resultType = CheckIndirectionOperand(Input, OpLoc);
5239 break;
5240 case UnaryOperator::Plus:
5241 case UnaryOperator::Minus:
5242 UsualUnaryConversions(Input);
5243 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005244 if (resultType->isDependentType())
5245 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005246 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5247 break;
5248 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5249 resultType->isEnumeralType())
5250 break;
5251 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5252 Opc == UnaryOperator::Plus &&
5253 resultType->isPointerType())
5254 break;
5255
Sebastian Redl8b769972009-01-19 00:08:26 +00005256 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5257 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005258 case UnaryOperator::Not: // bitwise complement
5259 UsualUnaryConversions(Input);
5260 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005261 if (resultType->isDependentType())
5262 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005263 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5264 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5265 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005266 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005267 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005268 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005269 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5270 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005271 break;
5272 case UnaryOperator::LNot: // logical negation
5273 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5274 DefaultFunctionArrayConversion(Input);
5275 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005276 if (resultType->isDependentType())
5277 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005278 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005279 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5280 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005281 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005282 // In C++, it's bool. C++ 5.3.1p8
5283 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005284 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005285 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005286 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005287 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005288 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005289 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005290 resultType = Input->getType();
5291 break;
5292 }
5293 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005294 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005295
5296 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005297 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005298}
5299
Douglas Gregorc78182d2009-03-13 23:49:33 +00005300// Unary Operators. 'Tok' is the token for the operator.
5301Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5302 tok::TokenKind Op, ExprArg input) {
5303 Expr *Input = (Expr*)input.get();
5304 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5305
5306 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5307 // Find all of the overloaded operators visible from this
5308 // point. We perform both an operator-name lookup from the local
5309 // scope and an argument-dependent lookup based on the types of
5310 // the arguments.
5311 FunctionSet Functions;
5312 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5313 if (OverOp != OO_None) {
5314 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5315 Functions);
5316 DeclarationName OpName
5317 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5318 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5319 }
5320
5321 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5322 }
5323
5324 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5325}
5326
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005327/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005328Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5329 SourceLocation LabLoc,
5330 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005331 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005332 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005333
Daniel Dunbar879788d2008-08-04 16:51:22 +00005334 // If we haven't seen this label yet, create a forward reference. It
5335 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005336 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005337 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005338
Chris Lattner4b009652007-07-25 00:24:17 +00005339 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005340 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5341 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005342}
5343
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005344Sema::OwningExprResult
5345Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5346 SourceLocation RPLoc) { // "({..})"
5347 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005348 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5349 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5350
Eli Friedmanbc941e12009-01-24 23:09:00 +00005351 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005352 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005353 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005354
Chris Lattner4b009652007-07-25 00:24:17 +00005355 // FIXME: there are a variety of strange constraints to enforce here, for
5356 // example, it is not possible to goto into a stmt expression apparently.
5357 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005358
Chris Lattner4b009652007-07-25 00:24:17 +00005359 // If there are sub stmts in the compound stmt, take the type of the last one
5360 // as the type of the stmtexpr.
5361 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005362
Chris Lattner200964f2008-07-26 19:51:01 +00005363 if (!Compound->body_empty()) {
5364 Stmt *LastStmt = Compound->body_back();
5365 // If LastStmt is a label, skip down through into the body.
5366 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5367 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005368
Chris Lattner200964f2008-07-26 19:51:01 +00005369 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005370 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005371 }
Mike Stump9afab102009-02-19 03:04:26 +00005372
Eli Friedman2b128322009-03-23 00:24:07 +00005373 // FIXME: Check that expression type is complete/non-abstract; statement
5374 // expressions are not lvalues.
5375
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005376 substmt.release();
5377 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005378}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005379
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005380Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5381 SourceLocation BuiltinLoc,
5382 SourceLocation TypeLoc,
5383 TypeTy *argty,
5384 OffsetOfComponent *CompPtr,
5385 unsigned NumComponents,
5386 SourceLocation RPLoc) {
5387 // FIXME: This function leaks all expressions in the offset components on
5388 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005389 // FIXME: Preserve type source info.
5390 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005391 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005392
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005393 bool Dependent = ArgTy->isDependentType();
5394
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005395 // We must have at least one component that refers to the type, and the first
5396 // one is known to be a field designator. Verify that the ArgTy represents
5397 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005398 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005399 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005400
Eli Friedman2b128322009-03-23 00:24:07 +00005401 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5402 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005403
Eli Friedman342d9432009-02-27 06:44:11 +00005404 // Otherwise, create a null pointer as the base, and iteratively process
5405 // the offsetof designators.
5406 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5407 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005408 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005409 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005410
Chris Lattnerb37522e2007-08-31 21:49:13 +00005411 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5412 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005413 // FIXME: This diagnostic isn't actually visible because the location is in
5414 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005415 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005416 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5417 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005418
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005419 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005420 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005421
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005422 // FIXME: Dependent case loses a lot of information here. And probably
5423 // leaks like a sieve.
5424 for (unsigned i = 0; i != NumComponents; ++i) {
5425 const OffsetOfComponent &OC = CompPtr[i];
5426 if (OC.isBrackets) {
5427 // Offset of an array sub-field. TODO: Should we allow vector elements?
5428 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5429 if (!AT) {
5430 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005431 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5432 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005433 }
5434
5435 // FIXME: C++: Verify that operator[] isn't overloaded.
5436
Eli Friedman342d9432009-02-27 06:44:11 +00005437 // Promote the array so it looks more like a normal array subscript
5438 // expression.
5439 DefaultFunctionArrayConversion(Res);
5440
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005441 // C99 6.5.2.1p1
5442 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005443 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005444 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005445 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005446 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005447 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005448
5449 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5450 OC.LocEnd);
5451 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005452 }
Mike Stump9afab102009-02-19 03:04:26 +00005453
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005454 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005455 if (!RC) {
5456 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005457 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5458 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005459 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005460
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005461 // Get the decl corresponding to this.
5462 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005463 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005464 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005465 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5466 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5467 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005468 DidWarnAboutNonPOD = true;
5469 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005470 }
5471
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005472 FieldDecl *MemberDecl
5473 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5474 LookupMemberName)
5475 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005476 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005477 if (!MemberDecl)
Anders Carlsson4355a392009-08-30 00:54:35 +00005478 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005479 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005480
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005481 // FIXME: C++: Verify that MemberDecl isn't a static field.
5482 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005483 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005484 Res = BuildAnonymousStructUnionMemberReference(
5485 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005486 } else {
5487 // MemberDecl->getType() doesn't get the right qualifiers, but it
5488 // doesn't matter here.
5489 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5490 MemberDecl->getType().getNonReferenceType());
5491 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005492 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005493 }
Mike Stump9afab102009-02-19 03:04:26 +00005494
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005495 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5496 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005497}
5498
5499
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005500Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5501 TypeTy *arg1,TypeTy *arg2,
5502 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005503 // FIXME: Preserve type source info.
5504 QualType argT1 = GetTypeFromParser(arg1);
5505 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005506
Steve Naroff63bad2d2007-08-01 22:05:33 +00005507 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005508
Douglas Gregore6211502009-05-19 22:28:02 +00005509 if (getLangOptions().CPlusPlus) {
5510 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5511 << SourceRange(BuiltinLoc, RPLoc);
5512 return ExprError();
5513 }
5514
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005515 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5516 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005517}
5518
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005519Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5520 ExprArg cond,
5521 ExprArg expr1, ExprArg expr2,
5522 SourceLocation RPLoc) {
5523 Expr *CondExpr = static_cast<Expr*>(cond.get());
5524 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5525 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005526
Steve Naroff93c53012007-08-03 21:21:27 +00005527 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5528
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005529 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005530 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005531 resType = Context.DependentTy;
5532 } else {
5533 // The conditional expression is required to be a constant expression.
5534 llvm::APSInt condEval(32);
5535 SourceLocation ExpLoc;
5536 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005537 return ExprError(Diag(ExpLoc,
5538 diag::err_typecheck_choose_expr_requires_constant)
5539 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005540
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005541 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5542 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5543 }
5544
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005545 cond.release(); expr1.release(); expr2.release();
5546 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5547 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005548}
5549
Steve Naroff52a81c02008-09-03 18:15:37 +00005550//===----------------------------------------------------------------------===//
5551// Clang Extensions.
5552//===----------------------------------------------------------------------===//
5553
5554/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005555void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005556 // Analyze block parameters.
5557 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005558
Steve Naroff52a81c02008-09-03 18:15:37 +00005559 // Add BSI to CurBlock.
5560 BSI->PrevBlockInfo = CurBlock;
5561 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005562
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005563 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005564 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005565 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005566 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005567 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5568 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005569
Steve Naroff52059382008-10-10 01:28:17 +00005570 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005571 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005572}
5573
Mike Stumpc1fddff2009-02-04 22:31:32 +00005574void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005575 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005576
5577 if (ParamInfo.getNumTypeObjects() == 0
5578 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005579 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005580 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5581
Mike Stump458287d2009-04-28 01:10:27 +00005582 if (T->isArrayType()) {
5583 Diag(ParamInfo.getSourceRange().getBegin(),
5584 diag::err_block_returns_array);
5585 return;
5586 }
5587
Mike Stumpc1fddff2009-02-04 22:31:32 +00005588 // The parameter list is optional, if there was none, assume ().
5589 if (!T->isFunctionType())
5590 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5591
5592 CurBlock->hasPrototype = true;
5593 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005594 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005595 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005596 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005597 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005598 // FIXME: remove the attribute.
5599 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005600 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5601
5602 // Do not allow returning a objc interface by-value.
5603 if (RetTy->isObjCInterfaceType()) {
5604 Diag(ParamInfo.getSourceRange().getBegin(),
5605 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5606 return;
5607 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005608 return;
5609 }
5610
Steve Naroff52a81c02008-09-03 18:15:37 +00005611 // Analyze arguments to block.
5612 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5613 "Not a function declarator!");
5614 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005615
Steve Naroff52059382008-10-10 01:28:17 +00005616 CurBlock->hasPrototype = FTI.hasPrototype;
5617 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005618
Steve Naroff52a81c02008-09-03 18:15:37 +00005619 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5620 // no arguments, not a function that takes a single void argument.
5621 if (FTI.hasPrototype &&
5622 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005623 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5624 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005625 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005626 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005627 } else if (FTI.hasPrototype) {
5628 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005629 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005630 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005631 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005632 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005633 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005634 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005635 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005636 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5637 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5638 // If this has an identifier, add it to the scope stack.
5639 if ((*AI)->getIdentifier())
5640 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005641
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005642 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005643 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005644 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005645 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005646 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005647 // FIXME: remove the attribute.
5648 }
5649
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005650 // Analyze the return type.
5651 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5652 QualType RetTy = T->getAsFunctionType()->getResultType();
5653
5654 // Do not allow returning a objc interface by-value.
5655 if (RetTy->isObjCInterfaceType()) {
5656 Diag(ParamInfo.getSourceRange().getBegin(),
5657 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5658 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005659 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005660}
5661
5662/// ActOnBlockError - If there is an error parsing a block, this callback
5663/// is invoked to pop the information about the block from the action impl.
5664void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5665 // Ensure that CurBlock is deleted.
5666 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005667
Chris Lattnere7765e12009-04-19 05:28:12 +00005668 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5669
Steve Naroff52a81c02008-09-03 18:15:37 +00005670 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005671 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005672 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005673 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005674}
5675
5676/// ActOnBlockStmtExpr - This is called when the body of a block statement
5677/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005678Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5679 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005680 // If blocks are disabled, emit an error.
5681 if (!LangOpts.Blocks)
5682 Diag(CaretLoc, diag::err_blocks_disable);
5683
Steve Naroff52a81c02008-09-03 18:15:37 +00005684 // Ensure that CurBlock is deleted.
5685 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005686
Steve Naroff52059382008-10-10 01:28:17 +00005687 PopDeclContext();
5688
Steve Naroff52a81c02008-09-03 18:15:37 +00005689 // Pop off CurBlock, handle nested blocks.
5690 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005691
Steve Naroff52a81c02008-09-03 18:15:37 +00005692 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005693 if (!BSI->ReturnType.isNull())
5694 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005695
Steve Naroff52a81c02008-09-03 18:15:37 +00005696 llvm::SmallVector<QualType, 8> ArgTypes;
5697 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5698 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005699
Mike Stump8e288f42009-07-28 22:04:01 +00005700 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005701 QualType BlockTy;
5702 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005703 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5704 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005705 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005706 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005707 BSI->isVariadic, 0, false, false, 0, 0,
5708 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005709
Eli Friedman2b128322009-03-23 00:24:07 +00005710 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005711 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005712 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005713
Chris Lattnere7765e12009-04-19 05:28:12 +00005714 // If needed, diagnose invalid gotos and switches in the block.
5715 if (CurFunctionNeedsScopeChecking)
5716 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5717 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5718
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005719 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005720 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005721 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5722 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005723}
5724
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005725Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5726 ExprArg expr, TypeTy *type,
5727 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005728 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005729 Expr *E = static_cast<Expr*>(expr.get());
5730 Expr *OrigExpr = E;
5731
Anders Carlsson36760332007-10-15 20:28:48 +00005732 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005733
5734 // Get the va_list type
5735 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005736 if (VaListType->isArrayType()) {
5737 // Deal with implicit array decay; for example, on x86-64,
5738 // va_list is an array, but it's supposed to decay to
5739 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005740 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005741 // Make sure the input expression also decays appropriately.
5742 UsualUnaryConversions(E);
5743 } else {
5744 // Otherwise, the va_list argument must be an l-value because
5745 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005746 if (!E->isTypeDependent() &&
5747 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005748 return ExprError();
5749 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005750
Douglas Gregor25990972009-05-19 23:10:31 +00005751 if (!E->isTypeDependent() &&
5752 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005753 return ExprError(Diag(E->getLocStart(),
5754 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005755 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005756 }
Mike Stump9afab102009-02-19 03:04:26 +00005757
Eli Friedman2b128322009-03-23 00:24:07 +00005758 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005759 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005760
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005761 expr.release();
5762 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5763 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005764}
5765
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005766Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005767 // The type of __null will be int or long, depending on the size of
5768 // pointers on the target.
5769 QualType Ty;
5770 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5771 Ty = Context.IntTy;
5772 else
5773 Ty = Context.LongTy;
5774
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005775 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005776}
5777
Chris Lattner005ed752008-01-04 18:04:52 +00005778bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5779 SourceLocation Loc,
5780 QualType DstType, QualType SrcType,
5781 Expr *SrcExpr, const char *Flavor) {
5782 // Decode the result (notice that AST's are still created for extensions).
5783 bool isInvalid = false;
5784 unsigned DiagKind;
5785 switch (ConvTy) {
5786 default: assert(0 && "Unknown conversion type");
5787 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005788 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005789 DiagKind = diag::ext_typecheck_convert_pointer_int;
5790 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005791 case IntToPointer:
5792 DiagKind = diag::ext_typecheck_convert_int_pointer;
5793 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005794 case IncompatiblePointer:
5795 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5796 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005797 case IncompatiblePointerSign:
5798 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5799 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005800 case FunctionVoidPointer:
5801 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5802 break;
5803 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005804 // If the qualifiers lost were because we were applying the
5805 // (deprecated) C++ conversion from a string literal to a char*
5806 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5807 // Ideally, this check would be performed in
5808 // CheckPointerTypesForAssignment. However, that would require a
5809 // bit of refactoring (so that the second argument is an
5810 // expression, rather than a type), which should be done as part
5811 // of a larger effort to fix CheckPointerTypesForAssignment for
5812 // C++ semantics.
5813 if (getLangOptions().CPlusPlus &&
5814 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5815 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005816 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5817 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005818 case IntToBlockPointer:
5819 DiagKind = diag::err_int_to_block_pointer;
5820 break;
5821 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005822 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005823 break;
Steve Naroff19608432008-10-14 22:18:38 +00005824 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005825 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005826 // it can give a more specific diagnostic.
5827 DiagKind = diag::warn_incompatible_qualified_id;
5828 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005829 case IncompatibleVectors:
5830 DiagKind = diag::warn_incompatible_vectors;
5831 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005832 case Incompatible:
5833 DiagKind = diag::err_typecheck_convert_incompatible;
5834 isInvalid = true;
5835 break;
5836 }
Mike Stump9afab102009-02-19 03:04:26 +00005837
Chris Lattner271d4c22008-11-24 05:29:24 +00005838 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5839 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005840 return isInvalid;
5841}
Anders Carlssond5201b92008-11-30 19:50:32 +00005842
Chris Lattnereec8ae22009-04-25 21:59:05 +00005843bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005844 llvm::APSInt ICEResult;
5845 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5846 if (Result)
5847 *Result = ICEResult;
5848 return false;
5849 }
5850
Anders Carlssond5201b92008-11-30 19:50:32 +00005851 Expr::EvalResult EvalResult;
5852
Mike Stump9afab102009-02-19 03:04:26 +00005853 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005854 EvalResult.HasSideEffects) {
5855 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5856
5857 if (EvalResult.Diag) {
5858 // We only show the note if it's not the usual "invalid subexpression"
5859 // or if it's actually in a subexpression.
5860 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5861 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5862 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5863 }
Mike Stump9afab102009-02-19 03:04:26 +00005864
Anders Carlssond5201b92008-11-30 19:50:32 +00005865 return true;
5866 }
5867
Eli Friedmance329412009-04-25 22:26:58 +00005868 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5869 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005870
Eli Friedmance329412009-04-25 22:26:58 +00005871 if (EvalResult.Diag &&
5872 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5873 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005874
Anders Carlssond5201b92008-11-30 19:50:32 +00005875 if (Result)
5876 *Result = EvalResult.Val.getInt();
5877 return false;
5878}
Douglas Gregor98189262009-06-19 23:52:42 +00005879
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005880Sema::ExpressionEvaluationContext
5881Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5882 // Introduce a new set of potentially referenced declarations to the stack.
5883 if (NewContext == PotentiallyPotentiallyEvaluated)
5884 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5885
5886 std::swap(ExprEvalContext, NewContext);
5887 return NewContext;
5888}
5889
5890void
5891Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5892 ExpressionEvaluationContext NewContext) {
5893 ExprEvalContext = NewContext;
5894
5895 if (OldContext == PotentiallyPotentiallyEvaluated) {
5896 // Mark any remaining declarations in the current position of the stack
5897 // as "referenced". If they were not meant to be referenced, semantic
5898 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5899 PotentiallyReferencedDecls RemainingDecls;
5900 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5901 PotentiallyReferencedDeclStack.pop_back();
5902
5903 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5904 IEnd = RemainingDecls.end();
5905 I != IEnd; ++I)
5906 MarkDeclarationReferenced(I->first, I->second);
5907 }
5908}
Douglas Gregor98189262009-06-19 23:52:42 +00005909
5910/// \brief Note that the given declaration was referenced in the source code.
5911///
5912/// This routine should be invoke whenever a given declaration is referenced
5913/// in the source code, and where that reference occurred. If this declaration
5914/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5915/// C99 6.9p3), then the declaration will be marked as used.
5916///
5917/// \param Loc the location where the declaration was referenced.
5918///
5919/// \param D the declaration that has been referenced by the source code.
5920void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5921 assert(D && "No declaration?");
5922
Douglas Gregorcad27f62009-06-22 23:06:13 +00005923 if (D->isUsed())
5924 return;
5925
Douglas Gregor98189262009-06-19 23:52:42 +00005926 // Mark a parameter declaration "used", regardless of whether we're in a
5927 // template or not.
5928 if (isa<ParmVarDecl>(D))
5929 D->setUsed(true);
5930
5931 // Do not mark anything as "used" within a dependent context; wait for
5932 // an instantiation.
5933 if (CurContext->isDependentContext())
5934 return;
5935
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005936 switch (ExprEvalContext) {
5937 case Unevaluated:
5938 // We are in an expression that is not potentially evaluated; do nothing.
5939 return;
5940
5941 case PotentiallyEvaluated:
5942 // We are in a potentially-evaluated expression, so this declaration is
5943 // "used"; handle this below.
5944 break;
5945
5946 case PotentiallyPotentiallyEvaluated:
5947 // We are in an expression that may be potentially evaluated; queue this
5948 // declaration reference until we know whether the expression is
5949 // potentially evaluated.
5950 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5951 return;
5952 }
5953
Douglas Gregor98189262009-06-19 23:52:42 +00005954 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005955 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005956 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005957 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5958 if (!Constructor->isUsed())
5959 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005960 } else if (Constructor->isImplicit() &&
5961 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005962 if (!Constructor->isUsed())
5963 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5964 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005965 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5966 if (Destructor->isImplicit() && !Destructor->isUsed())
5967 DefineImplicitDestructor(Loc, Destructor);
5968
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005969 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5970 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5971 MethodDecl->getOverloadedOperator() == OO_Equal) {
5972 if (!MethodDecl->isUsed())
5973 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5974 }
5975 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00005976 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005977 // Implicit instantiation of function templates and member functions of
5978 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00005979 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005980 // FIXME: distinguish between implicit instantiations of function
5981 // templates and explicit specializations (the latter don't get
5982 // instantiated, naturally).
5983 if (Function->getInstantiatedFromMemberFunction() ||
5984 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00005985 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00005986 }
5987
5988
Douglas Gregor98189262009-06-19 23:52:42 +00005989 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00005990 Function->setUsed(true);
5991 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00005992 }
Douglas Gregor98189262009-06-19 23:52:42 +00005993
5994 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00005995 // Implicit instantiation of static data members of class templates.
5996 // FIXME: distinguish between implicit instantiations (which we need to
5997 // actually instantiate) and explicit specializations.
5998 if (Var->isStaticDataMember() &&
5999 Var->getInstantiatedFromStaticDataMember())
6000 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6001
Douglas Gregor98189262009-06-19 23:52:42 +00006002 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006003
Douglas Gregor98189262009-06-19 23:52:42 +00006004 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006005 return;
6006}
Douglas Gregor98189262009-06-19 23:52:42 +00006007}
6008