blob: f304ac30945c8df48a1a02c88aac4ba85a118033 [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 Gregore399ad42009-08-26 22:36:53 +0000881/// \brief Build a MemberExpr or CXXQualifiedMemberExpr, as appropriate.
882static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
883 const CXXScopeSpec *SS, NamedDecl *Member,
884 SourceLocation Loc, QualType Ty) {
885 if (SS && SS->isSet())
886 return new (C) CXXQualifiedMemberExpr(Base, isArrow,
887 (NestedNameSpecifier *)SS->getScopeRep(),
888 SS->getRange(),
889 Member, Loc, Ty);
890
891 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
892}
893
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000894/// \brief Complete semantic analysis for a reference to the given declaration.
895Sema::OwningExprResult
896Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
897 bool HasTrailingLParen,
898 const CXXScopeSpec *SS,
899 bool isAddressOfOperand) {
900 assert(D && "Cannot refer to a NULL declaration");
901 DeclarationName Name = D->getDeclName();
902
Sebastian Redl0c9da212009-02-03 20:19:35 +0000903 // If this is an expression of the form &Class::member, don't build an
904 // implicit member ref, because we want a pointer to the member in general,
905 // not any specific instance's member.
906 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000907 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000908 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000909 QualType DType;
910 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
911 DType = FD->getType().getNonReferenceType();
912 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
913 DType = Method->getType();
914 } else if (isa<OverloadedFunctionDecl>(D)) {
915 DType = Context.OverloadTy;
916 }
917 // Could be an inner type. That's diagnosed below, so ignore it here.
918 if (!DType.isNull()) {
919 // The pointer is type- and value-dependent if it points into something
920 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000921 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000922 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000923 }
924 }
925 }
926
Douglas Gregor723d3332009-01-07 00:43:41 +0000927 // We may have found a field within an anonymous union or struct
928 // (C++ [class.union]).
929 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
930 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
931 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000932
Douglas Gregor3257fb52008-12-22 05:46:06 +0000933 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
934 if (!MD->isStatic()) {
935 // C++ [class.mfct.nonstatic]p2:
936 // [...] if name lookup (3.4.1) resolves the name in the
937 // id-expression to a nonstatic nontype member of class X or of
938 // a base class of X, the id-expression is transformed into a
939 // class member access expression (5.2.5) using (*this) (9.3.2)
940 // as the postfix-expression to the left of the '.' operator.
941 DeclContext *Ctx = 0;
942 QualType MemberType;
943 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
944 Ctx = FD->getDeclContext();
945 MemberType = FD->getType();
946
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000947 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000948 MemberType = RefType->getPointeeType();
949 else if (!FD->isMutable()) {
950 unsigned combinedQualifiers
951 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
952 MemberType = MemberType.getQualifiedType(combinedQualifiers);
953 }
954 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
955 if (!Method->isStatic()) {
956 Ctx = Method->getParent();
957 MemberType = Method->getType();
958 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000959 } else if (FunctionTemplateDecl *FunTmpl
960 = dyn_cast<FunctionTemplateDecl>(D)) {
961 if (CXXMethodDecl *Method
962 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
963 if (!Method->isStatic()) {
964 Ctx = Method->getParent();
965 MemberType = Context.OverloadTy;
966 }
967 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000968 } else if (OverloadedFunctionDecl *Ovl
969 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000970 // FIXME: We need an abstraction for iterating over one or more function
971 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000972 for (OverloadedFunctionDecl::function_iterator
973 Func = Ovl->function_begin(),
974 FuncEnd = Ovl->function_end();
975 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000976 CXXMethodDecl *DMethod = 0;
977 if (FunctionTemplateDecl *FunTmpl
978 = dyn_cast<FunctionTemplateDecl>(*Func))
979 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
980 else
981 DMethod = dyn_cast<CXXMethodDecl>(*Func);
982
983 if (DMethod && !DMethod->isStatic()) {
984 Ctx = DMethod->getDeclContext();
985 MemberType = Context.OverloadTy;
986 break;
987 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000988 }
989 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000990
991 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000992 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
993 QualType ThisType = Context.getTagDeclType(MD->getParent());
994 if ((Context.getCanonicalType(CtxType)
995 == Context.getCanonicalType(ThisType)) ||
996 IsDerivedFrom(ThisType, CtxType)) {
997 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000998 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000999 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001000 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001001 if (PerformObjectMemberConversion(This, D))
1002 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001003 if (DiagnoseUseOfDecl(D, Loc))
1004 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00001005 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1006 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001007 }
1008 }
1009 }
1010 }
1011
Douglas Gregor8acb7272008-12-11 16:49:14 +00001012 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001013 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1014 if (MD->isStatic())
1015 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001016 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1017 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001018 }
1019
Douglas Gregor3257fb52008-12-22 05:46:06 +00001020 // Any other ways we could have found the field in a well-formed
1021 // program would have been turned into implicit member expressions
1022 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001023 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1024 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001025 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001026
Chris Lattner4b009652007-07-25 00:24:17 +00001027 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001028 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001029 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001030 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001031 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001032 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001033
Steve Naroffd6163f32008-09-05 22:11:13 +00001034 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001035 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001036 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1037 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001038 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001039 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1040 false, false, SS);
Anders Carlsson89908542009-08-29 01:06:32 +00001041 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
1042 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1043 /*TypeDependent=*/true,
1044 /*ValueDependent=*/true, SS);
1045
Steve Naroffd6163f32008-09-05 22:11:13 +00001046 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001047
Douglas Gregoraa57e862009-02-18 21:56:37 +00001048 // Check whether this declaration can be used. Note that we suppress
1049 // this check when we're going to perform argument-dependent lookup
1050 // on this function name, because this might not be the function
1051 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001052 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1053 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001054 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1055 return ExprError();
1056
Steve Naroffd6163f32008-09-05 22:11:13 +00001057 // Only create DeclRefExpr's for valid Decl's.
1058 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001059 return ExprError();
1060
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001061 // If the identifier reference is inside a block, and it refers to a value
1062 // that is outside the block, create a BlockDeclRefExpr instead of a
1063 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1064 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001065 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001066 // We do not do this for things like enum constants, global variables, etc,
1067 // as they do not get snapshotted.
1068 //
1069 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001070 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001071 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001072 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001073 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001074 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001075 // This is to record that a 'const' was actually synthesize and added.
1076 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001077 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001078
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001079 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001080 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1081 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001082 }
1083 // If this reference is not in a block or if the referenced variable is
1084 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001085
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001086 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001087 bool ValueDependent = false;
1088 if (getLangOptions().CPlusPlus) {
1089 // C++ [temp.dep.expr]p3:
1090 // An id-expression is type-dependent if it contains:
1091 // - an identifier that was declared with a dependent type,
1092 if (VD->getType()->isDependentType())
1093 TypeDependent = true;
1094 // - FIXME: a template-id that is dependent,
1095 // - a conversion-function-id that specifies a dependent type,
1096 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1097 Name.getCXXNameType()->isDependentType())
1098 TypeDependent = true;
1099 // - a nested-name-specifier that contains a class-name that
1100 // names a dependent type.
1101 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001102 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001103 DC; DC = DC->getParent()) {
1104 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001105 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001106 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1107 if (Context.getTypeDeclType(Record)->isDependentType()) {
1108 TypeDependent = true;
1109 break;
1110 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001111 }
1112 }
1113 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001114
Douglas Gregora5d84612008-12-10 20:57:37 +00001115 // C++ [temp.dep.constexpr]p2:
1116 //
1117 // An identifier is value-dependent if it is:
1118 // - a name declared with a dependent type,
1119 if (TypeDependent)
1120 ValueDependent = true;
1121 // - the name of a non-type template parameter,
1122 else if (isa<NonTypeTemplateParmDecl>(VD))
1123 ValueDependent = true;
1124 // - a constant with integral or enumeration type and is
1125 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001126 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1127 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1128 Dcl->getInit()) {
1129 ValueDependent = Dcl->getInit()->isValueDependent();
1130 }
1131 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001132 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001133
Anders Carlsson4571d812009-06-24 00:10:43 +00001134 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1135 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001136}
1137
Sebastian Redlcd883f72009-01-18 18:53:16 +00001138Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1139 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001140 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001141
Chris Lattner4b009652007-07-25 00:24:17 +00001142 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001143 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001144 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1145 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1146 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001147 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001148
Chris Lattner7e637512008-01-12 08:14:25 +00001149 // Pre-defined identifiers are of type char[x], where x is the length of the
1150 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001151 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001152 if (FunctionDecl *FD = getCurFunctionDecl())
1153 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001154 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1155 Length = MD->getSynthesizedMethodSize();
1156 else {
1157 Diag(Loc, diag::ext_predef_outside_function);
1158 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1159 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1160 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001161
1162
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001163 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001164 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001165 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001166 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001167}
1168
Sebastian Redlcd883f72009-01-18 18:53:16 +00001169Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001170 llvm::SmallString<16> CharBuffer;
1171 CharBuffer.resize(Tok.getLength());
1172 const char *ThisTokBegin = &CharBuffer[0];
1173 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001174
Chris Lattner4b009652007-07-25 00:24:17 +00001175 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1176 Tok.getLocation(), PP);
1177 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001178 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001179
1180 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1181
Sebastian Redl75324932009-01-20 22:23:13 +00001182 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1183 Literal.isWide(),
1184 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001185}
1186
Sebastian Redlcd883f72009-01-18 18:53:16 +00001187Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1188 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001189 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1190 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001191 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001192 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001193 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001194 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001195 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001196
Chris Lattner4b009652007-07-25 00:24:17 +00001197 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001198 // Add padding so that NumericLiteralParser can overread by one character.
1199 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001200 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001201
Chris Lattner4b009652007-07-25 00:24:17 +00001202 // Get the spelling of the token, which eliminates trigraphs, etc.
1203 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001204
Chris Lattner4b009652007-07-25 00:24:17 +00001205 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1206 Tok.getLocation(), PP);
1207 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001208 return ExprError();
1209
Chris Lattner1de66eb2007-08-26 03:42:43 +00001210 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001211
Chris Lattner1de66eb2007-08-26 03:42:43 +00001212 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001213 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001214 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001215 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001216 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001217 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001218 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001219 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001220
1221 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1222
Ted Kremenekddedbe22007-11-29 00:56:49 +00001223 // isExact will be set by GetFloatValue().
1224 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001225 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1226 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001227
Chris Lattner1de66eb2007-08-26 03:42:43 +00001228 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001229 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001230 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001231 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001232
Neil Booth7421e9c2007-08-29 22:00:19 +00001233 // long long is a C99 feature.
1234 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001235 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001236 Diag(Tok.getLocation(), diag::ext_longlong);
1237
Chris Lattner4b009652007-07-25 00:24:17 +00001238 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001239 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001240
Chris Lattner4b009652007-07-25 00:24:17 +00001241 if (Literal.GetIntegerValue(ResultVal)) {
1242 // If this value didn't fit into uintmax_t, warn and force to ull.
1243 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001244 Ty = Context.UnsignedLongLongTy;
1245 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001246 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001247 } else {
1248 // If this value fits into a ULL, try to figure out what else it fits into
1249 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001250
Chris Lattner4b009652007-07-25 00:24:17 +00001251 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1252 // be an unsigned int.
1253 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1254
1255 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001256 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001257 if (!Literal.isLong && !Literal.isLongLong) {
1258 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001259 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001260
Chris Lattner4b009652007-07-25 00:24:17 +00001261 // Does it fit in a unsigned int?
1262 if (ResultVal.isIntN(IntSize)) {
1263 // Does it fit in a signed int?
1264 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001265 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001266 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001267 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001268 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001269 }
Chris Lattner4b009652007-07-25 00:24:17 +00001270 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001271
Chris Lattner4b009652007-07-25 00:24:17 +00001272 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001273 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001274 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001275
Chris Lattner4b009652007-07-25 00:24:17 +00001276 // Does it fit in a unsigned long?
1277 if (ResultVal.isIntN(LongSize)) {
1278 // Does it fit in a signed long?
1279 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001280 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001281 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001282 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001283 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001284 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001285 }
1286
Chris Lattner4b009652007-07-25 00:24:17 +00001287 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001288 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001289 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001290
Chris Lattner4b009652007-07-25 00:24:17 +00001291 // Does it fit in a unsigned long long?
1292 if (ResultVal.isIntN(LongLongSize)) {
1293 // Does it fit in a signed long long?
1294 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001295 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001296 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001297 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001298 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001299 }
1300 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001301
Chris Lattner4b009652007-07-25 00:24:17 +00001302 // If we still couldn't decide a type, we probably have something that
1303 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001304 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001305 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001306 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001307 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001308 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001309
Chris Lattnere4068872008-05-09 05:59:00 +00001310 if (ResultVal.getBitWidth() != Width)
1311 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001312 }
Sebastian Redl75324932009-01-20 22:23:13 +00001313 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001314 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001315
Chris Lattner1de66eb2007-08-26 03:42:43 +00001316 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1317 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001318 Res = new (Context) ImaginaryLiteral(Res,
1319 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001320
1321 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001322}
1323
Sebastian Redlcd883f72009-01-18 18:53:16 +00001324Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1325 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001326 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001327 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001328 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001329}
1330
1331/// The UsualUnaryConversions() function is *not* called by this routine.
1332/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001333bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001334 SourceLocation OpLoc,
1335 const SourceRange &ExprRange,
1336 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001337 if (exprType->isDependentType())
1338 return false;
1339
Chris Lattner4b009652007-07-25 00:24:17 +00001340 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001341 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001342 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001343 if (isSizeof)
1344 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1345 return false;
1346 }
1347
Chris Lattner95933c12009-04-24 00:30:45 +00001348 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001349 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001350 Diag(OpLoc, diag::ext_sizeof_void_type)
1351 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001352 return false;
1353 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001354
Chris Lattner95933c12009-04-24 00:30:45 +00001355 if (RequireCompleteType(OpLoc, exprType,
1356 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssona21e7872009-08-26 23:45:07 +00001357 PDiag(diag::err_alignof_incomplete_type)
1358 << ExprRange))
Chris Lattner95933c12009-04-24 00:30:45 +00001359 return true;
1360
1361 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001362 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001363 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001364 << exprType << isSizeof << ExprRange;
1365 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001366 }
1367
Chris Lattner95933c12009-04-24 00:30:45 +00001368 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001369}
1370
Chris Lattner8d9f7962009-01-24 20:17:12 +00001371bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1372 const SourceRange &ExprRange) {
1373 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001374
Chris Lattner8d9f7962009-01-24 20:17:12 +00001375 // alignof decl is always ok.
1376 if (isa<DeclRefExpr>(E))
1377 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001378
1379 // Cannot know anything else if the expression is dependent.
1380 if (E->isTypeDependent())
1381 return false;
1382
Douglas Gregor531434b2009-05-02 02:18:30 +00001383 if (E->getBitField()) {
1384 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1385 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001386 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001387
1388 // Alignment of a field access is always okay, so long as it isn't a
1389 // bit-field.
1390 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001391 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001392 return false;
1393
Chris Lattner8d9f7962009-01-24 20:17:12 +00001394 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1395}
1396
Douglas Gregor396f1142009-03-13 21:01:28 +00001397/// \brief Build a sizeof or alignof expression given a type operand.
1398Action::OwningExprResult
1399Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1400 bool isSizeOf, SourceRange R) {
1401 if (T.isNull())
1402 return ExprError();
1403
1404 if (!T->isDependentType() &&
1405 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1406 return ExprError();
1407
1408 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1409 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1410 Context.getSizeType(), OpLoc,
1411 R.getEnd()));
1412}
1413
1414/// \brief Build a sizeof or alignof expression given an expression
1415/// operand.
1416Action::OwningExprResult
1417Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1418 bool isSizeOf, SourceRange R) {
1419 // Verify that the operand is valid.
1420 bool isInvalid = false;
1421 if (E->isTypeDependent()) {
1422 // Delay type-checking for type-dependent expressions.
1423 } else if (!isSizeOf) {
1424 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001425 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001426 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1427 isInvalid = true;
1428 } else {
1429 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1430 }
1431
1432 if (isInvalid)
1433 return ExprError();
1434
1435 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1436 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1437 Context.getSizeType(), OpLoc,
1438 R.getEnd()));
1439}
1440
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001441/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1442/// the same for @c alignof and @c __alignof
1443/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001444Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001445Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1446 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001447 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001448 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001449
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001450 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001451 // FIXME: Preserve type source info.
1452 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001453 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1454 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001455
Douglas Gregor396f1142009-03-13 21:01:28 +00001456 // Get the end location.
1457 Expr *ArgEx = (Expr *)TyOrEx;
1458 Action::OwningExprResult Result
1459 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1460
1461 if (Result.isInvalid())
1462 DeleteExpr(ArgEx);
1463
1464 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001465}
1466
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001467QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001468 if (V->isTypeDependent())
1469 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001470
Chris Lattnera16e42d2007-08-26 05:39:26 +00001471 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001472 if (const ComplexType *CT = V->getType()->getAsComplexType())
1473 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001474
1475 // Otherwise they pass through real integer and floating point types here.
1476 if (V->getType()->isArithmeticType())
1477 return V->getType();
1478
1479 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001480 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1481 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001482 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001483}
1484
1485
Chris Lattner4b009652007-07-25 00:24:17 +00001486
Sebastian Redl8b769972009-01-19 00:08:26 +00001487Action::OwningExprResult
1488Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1489 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001490 // Since this might be a postfix expression, get rid of ParenListExprs.
1491 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001492 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001493
Chris Lattner4b009652007-07-25 00:24:17 +00001494 UnaryOperator::Opcode Opc;
1495 switch (Kind) {
1496 default: assert(0 && "Unknown unary op!");
1497 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1498 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1499 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001500
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001501 if (getLangOptions().CPlusPlus &&
1502 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1503 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001504 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001505 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1506
1507 // C++ [over.inc]p1:
1508 //
1509 // [...] If the function is a member function with one
1510 // parameter (which shall be of type int) or a non-member
1511 // function with two parameters (the second of which shall be
1512 // of type int), it defines the postfix increment operator ++
1513 // for objects of that type. When the postfix increment is
1514 // called as a result of using the ++ operator, the int
1515 // argument will have value zero.
1516 Expr *Args[2] = {
1517 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001518 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1519 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001520 };
1521
1522 // Build the candidate set for overloading
1523 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001524 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001525
1526 // Perform overload resolution.
1527 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001528 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001529 case OR_Success: {
1530 // We found a built-in operator or an overloaded operator.
1531 FunctionDecl *FnDecl = Best->Function;
1532
1533 if (FnDecl) {
1534 // We matched an overloaded operator. Build a call to that
1535 // operator.
1536
1537 // Convert the arguments.
1538 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1539 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001540 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001541 } else {
1542 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001543 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001544 FnDecl->getParamDecl(0)->getType(),
1545 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001546 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001547 }
1548
1549 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001550 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001551 = FnDecl->getType()->getAsFunctionType()->getResultType();
1552 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001553
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001554 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001555 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001556 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001557 UsualUnaryConversions(FnExpr);
1558
Sebastian Redl8b769972009-01-19 00:08:26 +00001559 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001560 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001561 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1562 Args, 2, ResultTy,
1563 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001564 } else {
1565 // We matched a built-in operator. Convert the arguments, then
1566 // break out so that we will build the appropriate built-in
1567 // operator node.
1568 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1569 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001570 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001571
1572 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001573 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001574 }
1575
1576 case OR_No_Viable_Function:
1577 // No viable function; fall through to handling this as a
1578 // built-in operator, which will produce an error message for us.
1579 break;
1580
1581 case OR_Ambiguous:
1582 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1583 << UnaryOperator::getOpcodeStr(Opc)
1584 << Arg->getSourceRange();
1585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001586 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001587
1588 case OR_Deleted:
1589 Diag(OpLoc, diag::err_ovl_deleted_oper)
1590 << Best->Function->isDeleted()
1591 << UnaryOperator::getOpcodeStr(Opc)
1592 << Arg->getSourceRange();
1593 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1594 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001595 }
1596
1597 // Either we found no viable overloaded operator or we matched a
1598 // built-in operator. In either case, fall through to trying to
1599 // build a built-in operation.
1600 }
1601
Eli Friedman94d30952009-07-22 23:24:42 +00001602 Input.release();
1603 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001604 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001605}
1606
Sebastian Redl8b769972009-01-19 00:08:26 +00001607Action::OwningExprResult
1608Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1609 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001610 // Since this might be a postfix expression, get rid of ParenListExprs.
1611 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1612
Sebastian Redl8b769972009-01-19 00:08:26 +00001613 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1614 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001615
Douglas Gregor80723c52008-11-19 17:17:41 +00001616 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001617 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1618 Base.release();
1619 Idx.release();
1620 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1621 Context.DependentTy, RLoc));
1622 }
1623
1624 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001625 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001626 LHSExp->getType()->isEnumeralType() ||
1627 RHSExp->getType()->isRecordType() ||
1628 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001629 // Add the appropriate overloaded operators (C++ [over.match.oper])
1630 // to the candidate set.
1631 OverloadCandidateSet CandidateSet;
1632 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001633 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1634 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001635
Douglas Gregor80723c52008-11-19 17:17:41 +00001636 // Perform overload resolution.
1637 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001638 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001639 case OR_Success: {
1640 // We found a built-in operator or an overloaded operator.
1641 FunctionDecl *FnDecl = Best->Function;
1642
1643 if (FnDecl) {
1644 // We matched an overloaded operator. Build a call to that
1645 // operator.
1646
1647 // Convert the arguments.
1648 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1649 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1650 PerformCopyInitialization(RHSExp,
1651 FnDecl->getParamDecl(0)->getType(),
1652 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001653 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001654 } else {
1655 // Convert the arguments.
1656 if (PerformCopyInitialization(LHSExp,
1657 FnDecl->getParamDecl(0)->getType(),
1658 "passing") ||
1659 PerformCopyInitialization(RHSExp,
1660 FnDecl->getParamDecl(1)->getType(),
1661 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001662 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001663 }
1664
1665 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001666 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001667 = FnDecl->getType()->getAsFunctionType()->getResultType();
1668 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001669
Douglas Gregor80723c52008-11-19 17:17:41 +00001670 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001671 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1672 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001673 UsualUnaryConversions(FnExpr);
1674
Sebastian Redl8b769972009-01-19 00:08:26 +00001675 Base.release();
1676 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001677 Args[0] = LHSExp;
1678 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001679 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1680 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001681 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001682 } else {
1683 // We matched a built-in operator. Convert the arguments, then
1684 // break out so that we will build the appropriate built-in
1685 // operator node.
1686 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1687 "passing") ||
1688 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1689 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001690 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001691
1692 break;
1693 }
1694 }
1695
1696 case OR_No_Viable_Function:
1697 // No viable function; fall through to handling this as a
1698 // built-in operator, which will produce an error message for us.
1699 break;
1700
1701 case OR_Ambiguous:
1702 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1703 << "[]"
1704 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1705 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001706 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001707
1708 case OR_Deleted:
1709 Diag(LLoc, diag::err_ovl_deleted_oper)
1710 << Best->Function->isDeleted()
1711 << "[]"
1712 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1713 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1714 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001715 }
1716
1717 // Either we found no viable overloaded operator or we matched a
1718 // built-in operator. In either case, fall through to trying to
1719 // build a built-in operation.
1720 }
1721
Chris Lattner4b009652007-07-25 00:24:17 +00001722 // Perform default conversions.
1723 DefaultFunctionArrayConversion(LHSExp);
1724 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001725
Chris Lattner4b009652007-07-25 00:24:17 +00001726 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1727
1728 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001729 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001730 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001731 // and index from the expression types.
1732 Expr *BaseExpr, *IndexExpr;
1733 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001734 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1735 BaseExpr = LHSExp;
1736 IndexExpr = RHSExp;
1737 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001738 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001739 BaseExpr = LHSExp;
1740 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001741 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001742 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001743 // Handle the uncommon case of "123[Ptr]".
1744 BaseExpr = RHSExp;
1745 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001746 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001747 } else if (const ObjCObjectPointerType *PTy =
1748 LHSTy->getAsObjCObjectPointerType()) {
1749 BaseExpr = LHSExp;
1750 IndexExpr = RHSExp;
1751 ResultType = PTy->getPointeeType();
1752 } else if (const ObjCObjectPointerType *PTy =
1753 RHSTy->getAsObjCObjectPointerType()) {
1754 // Handle the uncommon case of "123[Ptr]".
1755 BaseExpr = RHSExp;
1756 IndexExpr = LHSExp;
1757 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001758 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1759 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001760 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001761
Chris Lattner4b009652007-07-25 00:24:17 +00001762 // FIXME: need to deal with const...
1763 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001764 } else if (LHSTy->isArrayType()) {
1765 // If we see an array that wasn't promoted by
1766 // DefaultFunctionArrayConversion, it must be an array that
1767 // wasn't promoted because of the C90 rule that doesn't
1768 // allow promoting non-lvalue arrays. Warn, then
1769 // force the promotion here.
1770 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1771 LHSExp->getSourceRange();
1772 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1773 LHSTy = LHSExp->getType();
1774
1775 BaseExpr = LHSExp;
1776 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001777 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001778 } else if (RHSTy->isArrayType()) {
1779 // Same as previous, except for 123[f().a] case
1780 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1781 RHSExp->getSourceRange();
1782 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1783 RHSTy = RHSExp->getType();
1784
1785 BaseExpr = RHSExp;
1786 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001787 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001788 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001789 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1790 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001791 }
Chris Lattner4b009652007-07-25 00:24:17 +00001792 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001793 if (!(IndexExpr->getType()->isIntegerType() &&
1794 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001795 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1796 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001797
Douglas Gregor05e28f62009-03-24 19:52:54 +00001798 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1799 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1800 // type. Note that Functions are not objects, and that (in C99 parlance)
1801 // incomplete types are not object types.
1802 if (ResultType->isFunctionType()) {
1803 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1804 << ResultType << BaseExpr->getSourceRange();
1805 return ExprError();
1806 }
Chris Lattner95933c12009-04-24 00:30:45 +00001807
Douglas Gregor05e28f62009-03-24 19:52:54 +00001808 if (!ResultType->isDependentType() &&
Anders Carlssona21e7872009-08-26 23:45:07 +00001809 RequireCompleteType(LLoc, ResultType,
1810 PDiag(diag::err_subscript_incomplete_type)
1811 << BaseExpr->getSourceRange()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00001812 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001813
1814 // Diagnose bad cases where we step over interface counts.
1815 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1816 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1817 << ResultType << BaseExpr->getSourceRange();
1818 return ExprError();
1819 }
1820
Sebastian Redl8b769972009-01-19 00:08:26 +00001821 Base.release();
1822 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001823 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001824 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001825}
1826
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001827QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001828CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001829 const IdentifierInfo *CompName,
1830 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001831 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001832
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001833 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001834 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001835
Mike Stump9afab102009-02-19 03:04:26 +00001836 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001837 // special names that indicate a subset of exactly half the elements are
1838 // to be selected.
1839 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001840
Nate Begeman1486b502009-01-18 01:47:54 +00001841 // This flag determines whether or not CompName has an 's' char prefix,
1842 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001843 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001844
1845 // Check that we've found one of the special components, or that the component
1846 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001847 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001848 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1849 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001850 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001851 do
1852 compStr++;
1853 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001854 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001855 do
1856 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001857 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001858 }
Nate Begeman1486b502009-01-18 01:47:54 +00001859
Mike Stump9afab102009-02-19 03:04:26 +00001860 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001861 // We didn't get to the end of the string. This means the component names
1862 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001863 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1864 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001865 return QualType();
1866 }
Mike Stump9afab102009-02-19 03:04:26 +00001867
Nate Begeman1486b502009-01-18 01:47:54 +00001868 // Ensure no component accessor exceeds the width of the vector type it
1869 // operates on.
1870 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001871 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001872
1873 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001874 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001875
1876 while (*compStr) {
1877 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1878 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1879 << baseType << SourceRange(CompLoc);
1880 return QualType();
1881 }
1882 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001883 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001884
Nate Begeman1486b502009-01-18 01:47:54 +00001885 // If this is a halving swizzle, verify that the base type has an even
1886 // number of elements.
1887 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001888 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001889 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001890 return QualType();
1891 }
Mike Stump9afab102009-02-19 03:04:26 +00001892
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001893 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001894 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001895 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001896 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001897 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001898 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001899 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001900 if (HexSwizzle)
1901 CompSize--;
1902
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001903 if (CompSize == 1)
1904 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001905
Nate Begemanaf6ed502008-04-18 23:10:10 +00001906 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001907 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001908 // diagostics look bad. We want extended vector types to appear built-in.
1909 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1910 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1911 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001912 }
1913 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001914}
1915
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001916static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001917 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001918 const Selector &Sel,
1919 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001920
Anders Carlsson9935ab92009-08-26 18:25:21 +00001921 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001922 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001923 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001924 return OMD;
1925
1926 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1927 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001928 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1929 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001930 return D;
1931 }
1932 return 0;
1933}
1934
Steve Naroffc75c1a82009-06-17 22:40:22 +00001935static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001936 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001937 const Selector &Sel,
1938 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001939 // Check protocols on qualified interfaces.
1940 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001941 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001942 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001943 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001944 GDecl = PD;
1945 break;
1946 }
1947 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001948 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001949 GDecl = OMD;
1950 break;
1951 }
1952 }
1953 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001954 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001955 E = QIdTy->qual_end(); I != E; ++I) {
1956 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001957 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001958 if (GDecl)
1959 return GDecl;
1960 }
1961 }
1962 return GDecl;
1963}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001964
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001965/// FindMethodInNestedImplementations - Look up a method in current and
1966/// all base class implementations.
1967///
1968ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1969 const ObjCInterfaceDecl *IFace,
1970 const Selector &Sel) {
1971 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001972 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001973 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001974
1975 if (!Method && IFace->getSuperClass())
1976 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1977 return Method;
1978}
Douglas Gregore399ad42009-08-26 22:36:53 +00001979
Anders Carlsson9935ab92009-08-26 18:25:21 +00001980Action::OwningExprResult
1981Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001982 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001983 DeclarationName MemberName,
Douglas Gregorda61ad22009-08-06 03:17:00 +00001984 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001985 if (SS && SS->isInvalid())
1986 return ExprError();
1987
Nate Begemane85f43d2009-08-10 23:49:36 +00001988 // Since this might be a postfix expression, get rid of ParenListExprs.
1989 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1990
Anders Carlssonc154a722009-05-01 19:30:39 +00001991 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001992 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00001993
Steve Naroff137e11d2007-12-16 21:42:28 +00001994 // Perform default conversions.
1995 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001996
Steve Naroff2cb66382007-07-26 03:11:44 +00001997 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00001998 // If this is an Objective-C pseudo-builtin and a definition is provided then
1999 // use that.
2000 if (BaseType->isObjCIdType()) {
2001 // We have an 'id' type. Rather than fall through, we check if this
2002 // is a reference to 'isa'.
2003 if (BaseType != Context.ObjCIdRedefinitionType) {
2004 BaseType = Context.ObjCIdRedefinitionType;
2005 ImpCastExprToType(BaseExpr, BaseType);
2006 }
2007 } else if (BaseType->isObjCClassType() &&
2008 BaseType != Context.ObjCClassRedefinitionType) {
2009 BaseType = Context.ObjCClassRedefinitionType;
2010 ImpCastExprToType(BaseExpr, BaseType);
2011 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002012 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002013
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002014 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2015 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002016 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002017 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002018 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2019 BaseExpr, true,
2020 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002021 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002022 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002023 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002024 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002025 else if (BaseType->isObjCObjectPointerType())
2026 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002027 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002028 return ExprError(Diag(MemberLoc,
2029 diag::err_typecheck_member_reference_arrow)
2030 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002031 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002032 if (BaseType->isDependentType()) {
2033 // Require that the base type isn't a pointer type
2034 // (so we'll report an error for)
2035 // T* t;
2036 // t.f;
2037 //
2038 // In Obj-C++, however, the above expression is valid, since it could be
2039 // accessing the 'f' property if T is an Obj-C interface. The extra check
2040 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002041 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002042
2043 if (!PT || (getLangOptions().ObjC1 &&
2044 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002045 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2046 BaseExpr, false,
2047 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002048 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002049 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002050 }
Chris Lattner4b009652007-07-25 00:24:17 +00002051 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002052
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002053 // Handle field access to simple records. This also handles access to fields
2054 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002055 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002056 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002057 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002058 PDiag(diag::err_typecheck_incomplete_tag)
2059 << BaseExpr->getSourceRange()))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002060 return ExprError();
2061
Douglas Gregorda61ad22009-08-06 03:17:00 +00002062 DeclContext *DC = RDecl;
2063 if (SS && SS->isSet()) {
2064 // If the member name was a qualified-id, look into the
2065 // nested-name-specifier.
2066 DC = computeDeclContext(*SS, false);
2067
2068 // FIXME: If DC is not computable, we should build a
2069 // CXXUnresolvedMemberExpr.
2070 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2071 }
2072
Steve Naroff2cb66382007-07-26 03:11:44 +00002073 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002074 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002075 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002076
Douglas Gregor12431cb2009-08-06 05:28:30 +00002077 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002078 QualType BaseTypeCanon
2079 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2080 QualType MemberTypeCanon
2081 = Context.getCanonicalType(
2082 Context.getTypeDeclType(
2083 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2084
2085 if (BaseTypeCanon != MemberTypeCanon &&
2086 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2087 return ExprError(Diag(SS->getBeginLoc(),
2088 diag::err_not_direct_base_or_virtual)
2089 << MemberTypeCanon << BaseTypeCanon);
2090 }
2091
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002092 if (!Result)
Anders Carlsson4355a392009-08-30 00:54:35 +00002093 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002094 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002095 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002096 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2097 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002098 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002099 }
2100
2101 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002102
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002103 // If the decl being referenced had an error, return an error for this
2104 // sub-expr without emitting another error, in order to avoid cascading
2105 // error cases.
2106 if (MemberDecl->isInvalidDecl())
2107 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002108
Douglas Gregoraa57e862009-02-18 21:56:37 +00002109 // Check the use of this field
2110 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2111 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002112
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002113 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002114 // We may have found a field within an anonymous union or struct
2115 // (C++ [class.union]).
2116 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002117 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002118 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002119
Douglas Gregor82d44772008-12-20 23:49:58 +00002120 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002121 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002122 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002123 MemberType = Ref->getPointeeType();
2124 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002125 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002126 unsigned combinedQualifiers =
2127 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002128 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002129 combinedQualifiers &= ~QualType::Const;
2130 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002131 if (BaseAddrSpace != MemberType.getAddressSpace())
2132 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002133 }
Eli Friedman76b49832008-02-06 22:48:16 +00002134
Douglas Gregorcad27f62009-06-22 23:06:13 +00002135 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002136 if (PerformObjectMemberConversion(BaseExpr, FD))
2137 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002138 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2139 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002140 }
2141
Douglas Gregorcad27f62009-06-22 23:06:13 +00002142 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2143 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002144 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2145 Var, MemberLoc,
2146 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002147 }
2148 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2149 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002150 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2151 MemberFn, MemberLoc,
2152 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002153 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002154 if (FunctionTemplateDecl *FunTmpl
2155 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2156 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002157 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2158 FunTmpl, MemberLoc,
2159 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002160 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002161 if (OverloadedFunctionDecl *Ovl
2162 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregore399ad42009-08-26 22:36:53 +00002163 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2164 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002165 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2166 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002167 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2168 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002169 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002170 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002171 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002172 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002173
Douglas Gregor82d44772008-12-20 23:49:58 +00002174 // We found a declaration kind that we didn't expect. This is a
2175 // generic error message that tells the user that she can't refer
2176 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002177 return ExprError(Diag(MemberLoc,
2178 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002179 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002180 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002181
Steve Naroff329ec222009-07-10 23:34:53 +00002182 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002183 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002184 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002185 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2186 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002187 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2188 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2189 ObjCMethodDecl *Getter;
2190 // FIXME: need to also look locally in the implementation.
2191 if ((Getter = IFace->lookupClassMethod(Sel))) {
2192 // Check the use of this method.
2193 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2194 return ExprError();
2195 }
2196 // If we found a getter then this may be a valid dot-reference, we
2197 // will look for the matching setter, in case it is needed.
2198 Selector SetterSel =
2199 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002200 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002201 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2202 if (!Setter) {
2203 // If this reference is in an @implementation, also check for 'private'
2204 // methods.
2205 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2206 }
2207 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002208 if (!Setter)
2209 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002210
2211 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2212 return ExprError();
2213
2214 if (Getter || Setter) {
2215 QualType PType;
2216
2217 if (Getter)
2218 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002219 else
2220 // Get the expression type from Setter's incoming parameter.
2221 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002222 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002223 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002224 Setter, MemberLoc, BaseExpr));
2225 }
2226 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002227 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002228 }
2229 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002230 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2231 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002232 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2233 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2234 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2235 const ObjCInterfaceType *IFaceT =
2236 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002237 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002238 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2239
Steve Naroff4e743962009-07-16 00:25:06 +00002240 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2241 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002242 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002243
2244 if (IV) {
2245 // If the decl being referenced had an error, return an error for this
2246 // sub-expr without emitting another error, in order to avoid cascading
2247 // error cases.
2248 if (IV->isInvalidDecl())
2249 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002250
Steve Naroff4e743962009-07-16 00:25:06 +00002251 // Check whether we can reference this field.
2252 if (DiagnoseUseOfDecl(IV, MemberLoc))
2253 return ExprError();
2254 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2255 IV->getAccessControl() != ObjCIvarDecl::Package) {
2256 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2257 if (ObjCMethodDecl *MD = getCurMethodDecl())
2258 ClassOfMethodDecl = MD->getClassInterface();
2259 else if (ObjCImpDecl && getCurFunctionDecl()) {
2260 // Case of a c-function declared inside an objc implementation.
2261 // FIXME: For a c-style function nested inside an objc implementation
2262 // class, there is no implementation context available, so we pass
2263 // down the context as argument to this routine. Ideally, this context
2264 // need be passed down in the AST node and somehow calculated from the
2265 // AST for a function decl.
2266 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2267 if (ObjCImplementationDecl *IMPD =
2268 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2269 ClassOfMethodDecl = IMPD->getClassInterface();
2270 else if (ObjCCategoryImplDecl* CatImplClass =
2271 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2272 ClassOfMethodDecl = CatImplClass->getClassInterface();
2273 }
2274
2275 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2276 if (ClassDeclared != IDecl ||
2277 ClassOfMethodDecl != ClassDeclared)
2278 Diag(MemberLoc, diag::error_private_ivar_access)
2279 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002280 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2281 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002282 Diag(MemberLoc, diag::error_protected_ivar_access)
2283 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002284 }
Steve Naroff4e743962009-07-16 00:25:06 +00002285
2286 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2287 MemberLoc, BaseExpr,
2288 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002289 }
Steve Naroff4e743962009-07-16 00:25:06 +00002290 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002291 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002292 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002293 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002294 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002295 // Handle properties on 'id' and qualified "id".
2296 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2297 BaseType->isObjCQualifiedIdType())) {
2298 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002299 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002300
Steve Naroff329ec222009-07-10 23:34:53 +00002301 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002302 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002303 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2304 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2305 // Check the use of this declaration
2306 if (DiagnoseUseOfDecl(PD, MemberLoc))
2307 return ExprError();
2308
2309 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2310 MemberLoc, BaseExpr));
2311 }
2312 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2313 // Check the use of this method.
2314 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2315 return ExprError();
2316
2317 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2318 OMD->getResultType(),
2319 OMD, OpLoc, MemberLoc,
2320 NULL, 0));
2321 }
2322 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002323
Steve Naroff329ec222009-07-10 23:34:53 +00002324 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002325 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002326 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002327 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2328 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002329 const ObjCObjectPointerType *OPT;
2330 if (OpKind == tok::period &&
2331 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2332 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2333 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002334 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002335
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002336 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002337 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002338 // Check whether we can reference this property.
2339 if (DiagnoseUseOfDecl(PD, MemberLoc))
2340 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002341 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002342 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002343 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002344 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2345 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002346 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002347 MemberLoc, BaseExpr));
2348 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002349 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002350 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2351 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002352 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002353 // Check whether we can reference this property.
2354 if (DiagnoseUseOfDecl(PD, MemberLoc))
2355 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002356
Steve Naroff774e4152009-01-21 00:14:39 +00002357 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002358 MemberLoc, BaseExpr));
2359 }
Steve Naroff329ec222009-07-10 23:34:53 +00002360 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2361 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002362 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002363 // Check whether we can reference this property.
2364 if (DiagnoseUseOfDecl(PD, MemberLoc))
2365 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002366
Steve Naroff329ec222009-07-10 23:34:53 +00002367 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2368 MemberLoc, BaseExpr));
2369 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002370 // If that failed, look for an "implicit" property by seeing if the nullary
2371 // selector is implemented.
2372
2373 // FIXME: The logic for looking up nullary and unary selectors should be
2374 // shared with the code in ActOnInstanceMessage.
2375
Anders Carlsson9935ab92009-08-26 18:25:21 +00002376 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002377 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002378
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002379 // If this reference is in an @implementation, check for 'private' methods.
2380 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002381 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002382
Steve Naroff04151f32008-10-22 19:16:27 +00002383 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002384 if (!Getter)
2385 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002386 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002387 // Check if we can reference this property.
2388 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2389 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002390 }
2391 // If we found a getter then this may be a valid dot-reference, we
2392 // will look for the matching setter, in case it is needed.
2393 Selector SetterSel =
2394 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002395 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002396 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002397 if (!Setter) {
2398 // If this reference is in an @implementation, also check for 'private'
2399 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002400 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002401 }
2402 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002403 if (!Setter)
2404 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002405
Steve Naroffdede0c92009-03-11 13:48:17 +00002406 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2407 return ExprError();
2408
2409 if (Getter || Setter) {
2410 QualType PType;
2411
2412 if (Getter)
2413 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002414 else
2415 // Get the expression type from Setter's incoming parameter.
2416 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002417 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002418 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002419 Setter, MemberLoc, BaseExpr));
2420 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002421 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002422 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002423 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002424
Steve Naroff29d293b2009-07-24 17:54:45 +00002425 // Handle the following exceptional case (*Obj).isa.
2426 if (OpKind == tok::period &&
2427 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002428 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002429 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2430 Context.getObjCIdType()));
2431
Chris Lattnera57cf472008-07-21 04:28:12 +00002432 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002433 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002434 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002435 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2436 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002437 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002438 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002439 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002440 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002441
Douglas Gregor762da552009-03-27 06:00:30 +00002442 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2443 << BaseType << BaseExpr->getSourceRange();
2444
2445 // If the user is trying to apply -> or . to a function or function
2446 // pointer, it's probably because they forgot parentheses to call
2447 // the function. Suggest the addition of those parentheses.
2448 if (BaseType == Context.OverloadTy ||
2449 BaseType->isFunctionType() ||
2450 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002451 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002452 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2453 Diag(Loc, diag::note_member_reference_needs_call)
2454 << CodeModificationHint::CreateInsertion(Loc, "()");
2455 }
2456
2457 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002458}
2459
Anders Carlsson9935ab92009-08-26 18:25:21 +00002460Action::OwningExprResult
2461Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2462 tok::TokenKind OpKind, SourceLocation MemberLoc,
2463 IdentifierInfo &Member,
2464 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2465 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2466 DeclarationName(&Member), ObjCImpDecl, SS);
2467}
2468
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002469Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2470 FunctionDecl *FD,
2471 ParmVarDecl *Param) {
2472 if (Param->hasUnparsedDefaultArg()) {
2473 Diag (CallLoc,
2474 diag::err_use_of_default_argument_to_function_declared_later) <<
2475 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2476 Diag(UnparsedDefaultArgLocs[Param],
2477 diag::note_default_argument_declared_here);
2478 } else {
2479 if (Param->hasUninstantiatedDefaultArg()) {
2480 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2481
2482 // Instantiate the expression.
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002483 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002484
2485 // FIXME: We should really make a new InstantiatingTemplate ctor
2486 // that has a better message - right now we're just piggy-backing
2487 // off the "default template argument" error message.
2488 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002489 ArgList.getInnermost().getFlatArgumentList(),
2490 ArgList.getInnermost().flat_size());
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002491
John McCall0ba26ee2009-08-25 22:02:44 +00002492 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002493 if (Result.isInvalid())
2494 return ExprError();
2495
2496 if (SetParamDefaultArgument(Param, move(Result),
2497 /*FIXME:EqualLoc*/
2498 UninstExpr->getSourceRange().getBegin()))
2499 return ExprError();
2500 }
2501
2502 Expr *DefaultExpr = Param->getDefaultArg();
2503
2504 // If the default expression creates temporaries, we need to
2505 // push them to the current stack of expression temporaries so they'll
2506 // be properly destroyed.
2507 if (CXXExprWithTemporaries *E
2508 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2509 assert(!E->shouldDestroyTemporaries() &&
2510 "Can't destroy temporaries in a default argument expr!");
2511 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2512 ExprTemporaries.push_back(E->getTemporary(I));
2513 }
2514 }
2515
2516 // We already type-checked the argument, so we know it works.
2517 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2518}
2519
Douglas Gregor3257fb52008-12-22 05:46:06 +00002520/// ConvertArgumentsForCall - Converts the arguments specified in
2521/// Args/NumArgs to the parameter types of the function FDecl with
2522/// function prototype Proto. Call is the call expression itself, and
2523/// Fn is the function expression. For a C++ member function, this
2524/// routine does not attempt to convert the object argument. Returns
2525/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002526bool
2527Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002528 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002529 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002530 Expr **Args, unsigned NumArgs,
2531 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002532 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002533 // assignment, to the types of the corresponding parameter, ...
2534 unsigned NumArgsInProto = Proto->getNumArgs();
2535 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002536 bool Invalid = false;
2537
Douglas Gregor3257fb52008-12-22 05:46:06 +00002538 // If too few arguments are available (and we don't have default
2539 // arguments for the remaining parameters), don't make the call.
2540 if (NumArgs < NumArgsInProto) {
2541 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2542 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2543 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2544 // Use default arguments for missing arguments
2545 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002546 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002547 }
2548
2549 // If too many are passed and not variadic, error on the extras and drop
2550 // them.
2551 if (NumArgs > NumArgsInProto) {
2552 if (!Proto->isVariadic()) {
2553 Diag(Args[NumArgsInProto]->getLocStart(),
2554 diag::err_typecheck_call_too_many_args)
2555 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2556 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2557 Args[NumArgs-1]->getLocEnd());
2558 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002559 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002560 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002561 }
2562 NumArgsToCheck = NumArgsInProto;
2563 }
Mike Stump9afab102009-02-19 03:04:26 +00002564
Douglas Gregor3257fb52008-12-22 05:46:06 +00002565 // Continue to check argument types (even if we have too few/many args).
2566 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2567 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002568
Douglas Gregor3257fb52008-12-22 05:46:06 +00002569 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002570 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002571 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002572
Eli Friedman83dec9e2009-03-22 22:00:50 +00002573 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2574 ProtoArgType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002575 PDiag(diag::err_call_incomplete_argument)
2576 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002577 return true;
2578
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002579 // Pass the argument.
2580 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2581 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002582 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002583 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002584
2585 OwningExprResult ArgExpr =
2586 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2587 FDecl, Param);
2588 if (ArgExpr.isInvalid())
2589 return true;
2590
2591 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002592 }
2593
Douglas Gregor3257fb52008-12-22 05:46:06 +00002594 Call->setArg(i, Arg);
2595 }
Mike Stump9afab102009-02-19 03:04:26 +00002596
Douglas Gregor3257fb52008-12-22 05:46:06 +00002597 // If this is a variadic call, handle args passed through "...".
2598 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002599 VariadicCallType CallType = VariadicFunction;
2600 if (Fn->getType()->isBlockPointerType())
2601 CallType = VariadicBlock; // Block
2602 else if (isa<MemberExpr>(Fn))
2603 CallType = VariadicMethod;
2604
Douglas Gregor3257fb52008-12-22 05:46:06 +00002605 // Promote the arguments (C99 6.5.2.2p7).
2606 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2607 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002608 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002609 Call->setArg(i, Arg);
2610 }
2611 }
2612
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002613 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002614}
2615
Steve Naroff87d58b42007-09-16 03:34:24 +00002616/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002617/// This provides the location of the left/right parens and a list of comma
2618/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002619Action::OwningExprResult
2620Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2621 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002622 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002623 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002624
2625 // Since this might be a postfix expression, get rid of ParenListExprs.
2626 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2627
Anders Carlssonc154a722009-05-01 19:30:39 +00002628 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002629 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002630 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002631 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002632 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002633 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002634
Douglas Gregor3257fb52008-12-22 05:46:06 +00002635 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002636 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002637 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002638 // FIXME: Will need to cache the results of name lookup (including ADL) in
2639 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002640 bool Dependent = false;
2641 if (Fn->isTypeDependent())
2642 Dependent = true;
2643 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2644 Dependent = true;
2645
2646 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002647 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002648 Context.DependentTy, RParenLoc));
2649
2650 // Determine whether this is a call to an object (C++ [over.call.object]).
2651 if (Fn->getType()->isRecordType())
2652 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2653 CommaLocs, RParenLoc));
2654
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002655 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002656 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2657 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2658 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2659 isa<CXXMethodDecl>(MemDecl) ||
2660 (isa<FunctionTemplateDecl>(MemDecl) &&
2661 isa<CXXMethodDecl>(
2662 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002663 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2664 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002665 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002666 }
2667
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002668 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002669 // Also, in C++, keep track of whether we should perform argument-dependent
2670 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002671 Expr *FnExpr = Fn;
2672 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002673 bool HasExplicitTemplateArgs = 0;
2674 const TemplateArgument *ExplicitTemplateArgs = 0;
2675 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002676 while (true) {
2677 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2678 FnExpr = IcExpr->getSubExpr();
2679 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002680 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002681 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002682 ADL = false;
2683 FnExpr = PExpr->getSubExpr();
2684 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002685 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002686 == UnaryOperator::AddrOf) {
2687 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002688 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002689 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2690 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002691 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002692 break;
Mike Stump9afab102009-02-19 03:04:26 +00002693 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002694 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2695 UnqualifiedName = DepName->getName();
2696 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002697 } else if (TemplateIdRefExpr *TemplateIdRef
2698 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2699 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002700 if (!NDecl)
2701 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002702 HasExplicitTemplateArgs = true;
2703 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2704 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2705
2706 // C++ [temp.arg.explicit]p6:
2707 // [Note: For simple function names, argument dependent lookup (3.4.2)
2708 // applies even when the function name is not visible within the
2709 // scope of the call. This is because the call still has the syntactic
2710 // form of a function call (3.4.1). But when a function template with
2711 // explicit template arguments is used, the call does not have the
2712 // correct syntactic form unless there is a function template with
2713 // that name visible at the point of the call. If no such name is
2714 // visible, the call is not syntactically well-formed and
2715 // argument-dependent lookup does not apply. If some such name is
2716 // visible, argument dependent lookup applies and additional function
2717 // templates may be found in other namespaces.
2718 //
2719 // The summary of this paragraph is that, if we get to this point and the
2720 // template-id was not a qualified name, then argument-dependent lookup
2721 // is still possible.
2722 if (TemplateIdRef->getQualifier())
2723 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002724 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002725 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002726 // Any kind of name that does not refer to a declaration (or
2727 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2728 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002729 break;
2730 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002731 }
Mike Stump9afab102009-02-19 03:04:26 +00002732
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002733 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002734 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002735 if (NDecl) {
2736 FDecl = dyn_cast<FunctionDecl>(NDecl);
2737 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002738 FDecl = FunctionTemplate->getTemplatedDecl();
2739 else
Douglas Gregor28857752009-06-30 22:34:41 +00002740 FDecl = dyn_cast<FunctionDecl>(NDecl);
2741 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002742 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002743
Douglas Gregorb60eb752009-06-25 22:08:12 +00002744 if (Ovl || FunctionTemplate ||
2745 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002746 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002747 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002748 ADL = false;
2749
Douglas Gregorfcb19192009-02-11 23:02:49 +00002750 // We don't perform ADL in C.
2751 if (!getLangOptions().CPlusPlus)
2752 ADL = false;
2753
Douglas Gregorb60eb752009-06-25 22:08:12 +00002754 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002755 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2756 HasExplicitTemplateArgs,
2757 ExplicitTemplateArgs,
2758 NumExplicitTemplateArgs,
2759 LParenLoc, Args, NumArgs, CommaLocs,
2760 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002761 if (!FDecl)
2762 return ExprError();
2763
2764 // Update Fn to refer to the actual function selected.
2765 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002766 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002767 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002768 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2769 QDRExpr->getLocation(),
2770 false, false,
2771 QDRExpr->getQualifierRange(),
2772 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002773 else
Mike Stump9afab102009-02-19 03:04:26 +00002774 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002775 Fn->getSourceRange().getBegin());
2776 Fn->Destroy(Context);
2777 Fn = NewFn;
2778 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002779 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002780
2781 // Promote the function operand.
2782 UsualUnaryConversions(Fn);
2783
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002784 // Make the call expr early, before semantic checks. This guarantees cleanup
2785 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002786 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2787 Args, NumArgs,
2788 Context.BoolTy,
2789 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002790
Steve Naroffd6163f32008-09-05 22:11:13 +00002791 const FunctionType *FuncT;
2792 if (!Fn->getType()->isBlockPointerType()) {
2793 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2794 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002795 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002796 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002797 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2798 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002799 FuncT = PT->getPointeeType()->getAsFunctionType();
2800 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002801 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002802 getAsFunctionType();
2803 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002804 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002805 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2806 << Fn->getType() << Fn->getSourceRange());
2807
Eli Friedman83dec9e2009-03-22 22:00:50 +00002808 // Check for a valid return type
2809 if (!FuncT->getResultType()->isVoidType() &&
2810 RequireCompleteType(Fn->getSourceRange().getBegin(),
2811 FuncT->getResultType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002812 PDiag(diag::err_call_incomplete_return)
2813 << TheCall->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002814 return ExprError();
2815
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002816 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002817 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002818
Douglas Gregor4fa58902009-02-26 23:50:07 +00002819 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002820 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002821 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002822 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002823 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002824 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002825
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002826 if (FDecl) {
2827 // Check if we have too few/too many template arguments, based
2828 // on our knowledge of the function definition.
2829 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002830 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002831 const FunctionProtoType *Proto =
2832 Def->getType()->getAsFunctionProtoType();
2833 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2834 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2835 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2836 }
2837 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002838 }
2839
Steve Naroffdb65e052007-08-28 23:30:39 +00002840 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002841 for (unsigned i = 0; i != NumArgs; i++) {
2842 Expr *Arg = Args[i];
2843 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002844 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2845 Arg->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002846 PDiag(diag::err_call_incomplete_argument)
2847 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002848 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002849 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002850 }
Chris Lattner4b009652007-07-25 00:24:17 +00002851 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002852
Douglas Gregor3257fb52008-12-22 05:46:06 +00002853 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2854 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002855 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2856 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002857
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002858 // Check for sentinels
2859 if (NDecl)
2860 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002861
Chris Lattner2e64c072007-08-10 20:18:51 +00002862 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002863 if (FDecl) {
2864 if (CheckFunctionCall(FDecl, TheCall.get()))
2865 return ExprError();
2866
2867 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2868 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2869 } else if (NDecl) {
2870 if (CheckBlockCall(NDecl, TheCall.get()))
2871 return ExprError();
2872 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002873
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002874 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002875}
2876
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002877Action::OwningExprResult
2878Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2879 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002880 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002881 //FIXME: Preserve type source info.
2882 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002883 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002884 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002885 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002886
Eli Friedman8c2173d2008-05-20 05:22:08 +00002887 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002888 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002889 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2890 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002891 } else if (!literalType->isDependentType() &&
2892 RequireCompleteType(LParenLoc, literalType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002893 PDiag(diag::err_typecheck_decl_incomplete_type)
2894 << SourceRange(LParenLoc,
2895 literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002896 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002897
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002898 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002899 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002900 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002901
Chris Lattnere5cb5862008-12-04 23:50:19 +00002902 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002903 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002904 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002905 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002906 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002907 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002908 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002909 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002910}
2911
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002912Action::OwningExprResult
2913Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002914 SourceLocation RBraceLoc) {
2915 unsigned NumInit = initlist.size();
2916 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002917
Steve Naroff0acc9c92007-09-15 18:49:24 +00002918 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002919 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002920
Mike Stump9afab102009-02-19 03:04:26 +00002921 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002922 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002923 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002924 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002925}
2926
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002927/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002928bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002929 CastExpr::CastKind& Kind,
2930 CXXMethodDecl *& ConversionDecl,
2931 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002932 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002933 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2934 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002935
Eli Friedman01e0f652009-08-15 19:02:19 +00002936 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002937
2938 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2939 // type needs to be scalar.
2940 if (castType->isVoidType()) {
2941 // Cast to void allows any expr type.
2942 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002943 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2944 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2945 (castType->isStructureType() || castType->isUnionType())) {
2946 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002947 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002948 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2949 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002950 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002951 } else if (castType->isUnionType()) {
2952 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002953 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002954 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002955 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002956 Field != FieldEnd; ++Field) {
2957 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2958 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2959 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2960 << castExpr->getSourceRange();
2961 break;
2962 }
2963 }
2964 if (Field == FieldEnd)
2965 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2966 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002967 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002968 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002969 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002970 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002971 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002972 }
Mike Stump9afab102009-02-19 03:04:26 +00002973 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002974 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002975 return Diag(castExpr->getLocStart(),
2976 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002977 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00002978 } else if (castType->isExtVectorType()) {
2979 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002980 return true;
2981 } else if (castType->isVectorType()) {
2982 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2983 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00002984 } else if (castExpr->getType()->isVectorType()) {
2985 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2986 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002987 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002988 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002989 } else if (!castType->isArithmeticType()) {
2990 QualType castExprType = castExpr->getType();
2991 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2992 return Diag(castExpr->getLocStart(),
2993 diag::err_cast_pointer_from_non_pointer_int)
2994 << castExprType << castExpr->getSourceRange();
2995 } else if (!castExpr->getType()->isArithmeticType()) {
2996 if (!castType->isIntegralType() && castType->isArithmeticType())
2997 return Diag(castExpr->getLocStart(),
2998 diag::err_cast_pointer_to_non_pointer_int)
2999 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003000 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003001 if (isa<ObjCSelectorExpr>(castExpr))
3002 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003003 return false;
3004}
3005
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003006bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003007 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003008
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003009 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003010 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003011 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003012 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003013 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003014 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003015 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003016 } else
3017 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003018 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003019 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003020
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003021 return false;
3022}
3023
Nate Begemanbd42e022009-06-26 00:50:28 +00003024bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3025 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3026
Nate Begeman9e063702009-06-27 22:05:55 +00003027 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3028 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003029 if (SrcTy->isVectorType()) {
3030 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3031 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3032 << DestTy << SrcTy << R;
3033 return false;
3034 }
3035
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003036 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003037 // conversion will take place first from scalar to elt type, and then
3038 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003039 if (SrcTy->isPointerType())
3040 return Diag(R.getBegin(),
3041 diag::err_invalid_conversion_between_vector_and_scalar)
3042 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003043 return false;
3044}
3045
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003046Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003047Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003048 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003049 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3050
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003051 assert((Ty != 0) && (Op.get() != 0) &&
3052 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003053
Nate Begemane85f43d2009-08-10 23:49:36 +00003054 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003055 //FIXME: Preserve type source info.
3056 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003057
3058 // If the Expr being casted is a ParenListExpr, handle it specially.
3059 if (isa<ParenListExpr>(castExpr))
3060 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003061 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003062 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003063 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003064 return ExprError();
Fariborz Jahanianec172132009-08-29 19:15:16 +00003065 if (ConversionDecl) {
3066 // encounterred a c-style cast requiring a conversion function.
3067 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) {
3068 castExpr =
3069 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(),
3070 castType, LParenLoc,
3071 CastExpr::CK_UserDefinedConversion,
3072 castExpr, CD,
3073 RParenLoc);
3074 Kind = CastExpr::CK_UserDefinedConversion;
3075 }
3076 // FIXME. AST for when dealing with conversion functions (FunctionDecl).
3077 }
Nate Begemane85f43d2009-08-10 23:49:36 +00003078
3079 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003080 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003081 Kind, castExpr, castType,
3082 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003083}
3084
Nate Begemane85f43d2009-08-10 23:49:36 +00003085/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3086/// of comma binary operators.
3087Action::OwningExprResult
3088Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3089 Expr *expr = EA.takeAs<Expr>();
3090 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3091 if (!E)
3092 return Owned(expr);
3093
3094 OwningExprResult Result(*this, E->getExpr(0));
3095
3096 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3097 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3098 Owned(E->getExpr(i)));
3099
3100 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3101}
3102
3103Action::OwningExprResult
3104Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3105 SourceLocation RParenLoc, ExprArg Op,
3106 QualType Ty) {
3107 ParenListExpr *PE = (ParenListExpr *)Op.get();
3108
3109 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3110 // then handle it as such.
3111 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3112 if (PE->getNumExprs() == 0) {
3113 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3114 return ExprError();
3115 }
3116
3117 llvm::SmallVector<Expr *, 8> initExprs;
3118 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3119 initExprs.push_back(PE->getExpr(i));
3120
3121 // FIXME: This means that pretty-printing the final AST will produce curly
3122 // braces instead of the original commas.
3123 Op.release();
3124 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3125 initExprs.size(), RParenLoc);
3126 E->setType(Ty);
3127 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3128 Owned(E));
3129 } else {
3130 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3131 // sequence of BinOp comma operators.
3132 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3133 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3134 }
3135}
3136
3137Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3138 SourceLocation R,
3139 MultiExprArg Val) {
3140 unsigned nexprs = Val.size();
3141 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3142 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3143 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3144 return Owned(expr);
3145}
3146
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003147/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3148/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003149/// C99 6.5.15
3150QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3151 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003152 // C++ is sufficiently different to merit its own checker.
3153 if (getLangOptions().CPlusPlus)
3154 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3155
Chris Lattnere2897262009-02-18 04:28:32 +00003156 UsualUnaryConversions(Cond);
3157 UsualUnaryConversions(LHS);
3158 UsualUnaryConversions(RHS);
3159 QualType CondTy = Cond->getType();
3160 QualType LHSTy = LHS->getType();
3161 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003162
3163 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003164 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3165 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3166 << CondTy;
3167 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003168 }
Mike Stump9afab102009-02-19 03:04:26 +00003169
Chris Lattner992ae932008-01-06 22:42:25 +00003170 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003171 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3172 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003173
Chris Lattner992ae932008-01-06 22:42:25 +00003174 // If both operands have arithmetic type, do the usual arithmetic conversions
3175 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003176 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3177 UsualArithmeticConversions(LHS, RHS);
3178 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003179 }
Mike Stump9afab102009-02-19 03:04:26 +00003180
Chris Lattner992ae932008-01-06 22:42:25 +00003181 // If both operands are the same structure or union type, the result is that
3182 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003183 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3184 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003185 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003186 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003187 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003188 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003189 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003190 }
Mike Stump9afab102009-02-19 03:04:26 +00003191
Chris Lattner992ae932008-01-06 22:42:25 +00003192 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003193 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003194 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3195 if (!LHSTy->isVoidType())
3196 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3197 << RHS->getSourceRange();
3198 if (!RHSTy->isVoidType())
3199 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3200 << LHS->getSourceRange();
3201 ImpCastExprToType(LHS, Context.VoidTy);
3202 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003203 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003204 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003205 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3206 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003207 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003208 RHS->isNullPointerConstant(Context)) {
3209 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3210 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003211 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003212 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003213 LHS->isNullPointerConstant(Context)) {
3214 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3215 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003216 }
David Chisnall44663db2009-08-17 16:35:33 +00003217 // Handle things like Class and struct objc_class*. Here we case the result
3218 // to the pseudo-builtin, because that will be implicitly cast back to the
3219 // redefinition type if an attempt is made to access its fields.
3220 if (LHSTy->isObjCClassType() &&
3221 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3222 ImpCastExprToType(RHS, LHSTy);
3223 return LHSTy;
3224 }
3225 if (RHSTy->isObjCClassType() &&
3226 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3227 ImpCastExprToType(LHS, RHSTy);
3228 return RHSTy;
3229 }
3230 // And the same for struct objc_object* / id
3231 if (LHSTy->isObjCIdType() &&
3232 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3233 ImpCastExprToType(RHS, LHSTy);
3234 return LHSTy;
3235 }
3236 if (RHSTy->isObjCIdType() &&
3237 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3238 ImpCastExprToType(LHS, RHSTy);
3239 return RHSTy;
3240 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003241 // Handle block pointer types.
3242 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3243 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3244 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3245 QualType destType = Context.getPointerType(Context.VoidTy);
3246 ImpCastExprToType(LHS, destType);
3247 ImpCastExprToType(RHS, destType);
3248 return destType;
3249 }
3250 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3251 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3252 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003253 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003254 // We have 2 block pointer types.
3255 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3256 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003257 return LHSTy;
3258 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003259 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003260 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3261 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003262
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003263 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3264 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003265 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3266 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3267 // In this situation, we assume void* type. No especially good
3268 // reason, but this is what gcc does, and we do have to pick
3269 // to get a consistent AST.
3270 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3271 ImpCastExprToType(LHS, incompatTy);
3272 ImpCastExprToType(RHS, incompatTy);
3273 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003274 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003275 // The block pointer types are compatible.
3276 ImpCastExprToType(LHS, LHSTy);
3277 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003278 return LHSTy;
3279 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003280 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003281 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003282
3283 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3284 // Two identical object pointer types are always compatible.
3285 return LHSTy;
3286 }
Steve Naroff329ec222009-07-10 23:34:53 +00003287 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3288 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003289 QualType compositeType = LHSTy;
3290
3291 // If both operands are interfaces and either operand can be
3292 // assigned to the other, use that type as the composite
3293 // type. This allows
3294 // xxx ? (A*) a : (B*) b
3295 // where B is a subclass of A.
3296 //
3297 // Additionally, as for assignment, if either type is 'id'
3298 // allow silent coercion. Finally, if the types are
3299 // incompatible then make sure to use 'id' as the composite
3300 // type so the result is acceptable for sending messages to.
3301
3302 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3303 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003304 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003305 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003306 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003307 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003308 } else if ((LHSTy->isObjCQualifiedIdType() ||
3309 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003310 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003311 // Need to handle "id<xx>" explicitly.
3312 // GCC allows qualified id and any Objective-C type to devolve to
3313 // id. Currently localizing to here until clear this should be
3314 // part of ObjCQualifiedIdTypesAreCompatible.
3315 compositeType = Context.getObjCIdType();
3316 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003317 compositeType = Context.getObjCIdType();
3318 } else {
3319 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3320 << LHSTy << RHSTy
3321 << LHS->getSourceRange() << RHS->getSourceRange();
3322 QualType incompatTy = Context.getObjCIdType();
3323 ImpCastExprToType(LHS, incompatTy);
3324 ImpCastExprToType(RHS, incompatTy);
3325 return incompatTy;
3326 }
3327 // The object pointer types are compatible.
3328 ImpCastExprToType(LHS, compositeType);
3329 ImpCastExprToType(RHS, compositeType);
3330 return compositeType;
3331 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003332 // Check Objective-C object pointer types and 'void *'
3333 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003334 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003335 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3336 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3337 QualType destType = Context.getPointerType(destPointee);
3338 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3339 ImpCastExprToType(RHS, destType); // promote to void*
3340 return destType;
3341 }
3342 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3343 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003344 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003345 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3346 QualType destType = Context.getPointerType(destPointee);
3347 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3348 ImpCastExprToType(LHS, destType); // promote to void*
3349 return destType;
3350 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003351 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3352 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3353 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003354 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3355 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003356
3357 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3358 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3359 // Figure out necessary qualifiers (C99 6.5.15p6)
3360 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3361 QualType destType = Context.getPointerType(destPointee);
3362 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3363 ImpCastExprToType(RHS, destType); // promote to void*
3364 return destType;
3365 }
3366 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3367 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3368 QualType destType = Context.getPointerType(destPointee);
3369 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3370 ImpCastExprToType(RHS, destType); // promote to void*
3371 return destType;
3372 }
3373
3374 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3375 // Two identical pointer types are always compatible.
3376 return LHSTy;
3377 }
3378 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3379 rhptee.getUnqualifiedType())) {
3380 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3381 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3382 // In this situation, we assume void* type. No especially good
3383 // reason, but this is what gcc does, and we do have to pick
3384 // to get a consistent AST.
3385 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3386 ImpCastExprToType(LHS, incompatTy);
3387 ImpCastExprToType(RHS, incompatTy);
3388 return incompatTy;
3389 }
3390 // The pointer types are compatible.
3391 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3392 // differently qualified versions of compatible types, the result type is
3393 // a pointer to an appropriately qualified version of the *composite*
3394 // type.
3395 // FIXME: Need to calculate the composite type.
3396 // FIXME: Need to add qualifiers
3397 ImpCastExprToType(LHS, LHSTy);
3398 ImpCastExprToType(RHS, LHSTy);
3399 return LHSTy;
3400 }
3401
3402 // GCC compatibility: soften pointer/integer mismatch.
3403 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3404 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3405 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3406 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3407 return RHSTy;
3408 }
3409 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3410 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3411 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3412 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3413 return LHSTy;
3414 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003415
Chris Lattner992ae932008-01-06 22:42:25 +00003416 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003417 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3418 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003419 return QualType();
3420}
3421
Steve Naroff87d58b42007-09-16 03:34:24 +00003422/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003423/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003424Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3425 SourceLocation ColonLoc,
3426 ExprArg Cond, ExprArg LHS,
3427 ExprArg RHS) {
3428 Expr *CondExpr = (Expr *) Cond.get();
3429 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003430
3431 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3432 // was the condition.
3433 bool isLHSNull = LHSExpr == 0;
3434 if (isLHSNull)
3435 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003436
3437 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003438 RHSExpr, QuestionLoc);
3439 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003440 return ExprError();
3441
3442 Cond.release();
3443 LHS.release();
3444 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003445 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003446 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003447 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003448}
3449
Chris Lattner4b009652007-07-25 00:24:17 +00003450// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003451// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003452// routine is it effectively iqnores the qualifiers on the top level pointee.
3453// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3454// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003455Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003456Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3457 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003458
David Chisnall44663db2009-08-17 16:35:33 +00003459 if ((lhsType->isObjCClassType() &&
3460 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3461 (rhsType->isObjCClassType() &&
3462 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3463 return Compatible;
3464 }
3465
Chris Lattner4b009652007-07-25 00:24:17 +00003466 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003467 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3468 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003469
Chris Lattner4b009652007-07-25 00:24:17 +00003470 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003471 lhptee = Context.getCanonicalType(lhptee);
3472 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003473
Chris Lattner005ed752008-01-04 18:04:52 +00003474 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003475
3476 // C99 6.5.16.1p1: This following citation is common to constraints
3477 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3478 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003479 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003480 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003481 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003482
Mike Stump9afab102009-02-19 03:04:26 +00003483 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3484 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003485 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003486 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003487 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003488 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003489
Chris Lattner4ca3d772008-01-03 22:56:36 +00003490 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003491 assert(rhptee->isFunctionType());
3492 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003493 }
Mike Stump9afab102009-02-19 03:04:26 +00003494
Chris Lattner4ca3d772008-01-03 22:56:36 +00003495 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003496 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003497 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003498
3499 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003500 assert(lhptee->isFunctionType());
3501 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003502 }
Mike Stump9afab102009-02-19 03:04:26 +00003503 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003504 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003505 lhptee = lhptee.getUnqualifiedType();
3506 rhptee = rhptee.getUnqualifiedType();
3507 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3508 // Check if the pointee types are compatible ignoring the sign.
3509 // We explicitly check for char so that we catch "char" vs
3510 // "unsigned char" on systems where "char" is unsigned.
3511 if (lhptee->isCharType()) {
3512 lhptee = Context.UnsignedCharTy;
3513 } else if (lhptee->isSignedIntegerType()) {
3514 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3515 }
3516 if (rhptee->isCharType()) {
3517 rhptee = Context.UnsignedCharTy;
3518 } else if (rhptee->isSignedIntegerType()) {
3519 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3520 }
3521 if (lhptee == rhptee) {
3522 // Types are compatible ignoring the sign. Qualifier incompatibility
3523 // takes priority over sign incompatibility because the sign
3524 // warning can be disabled.
3525 if (ConvTy != Compatible)
3526 return ConvTy;
3527 return IncompatiblePointerSign;
3528 }
3529 // General pointer incompatibility takes priority over qualifiers.
3530 return IncompatiblePointer;
3531 }
Chris Lattner005ed752008-01-04 18:04:52 +00003532 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003533}
3534
Steve Naroff3454b6c2008-09-04 15:10:53 +00003535/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3536/// block pointer types are compatible or whether a block and normal pointer
3537/// are compatible. It is more restrict than comparing two function pointer
3538// types.
Mike Stump9afab102009-02-19 03:04:26 +00003539Sema::AssignConvertType
3540Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003541 QualType rhsType) {
3542 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003543
Steve Naroff3454b6c2008-09-04 15:10:53 +00003544 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003545 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3546 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003547
Steve Naroff3454b6c2008-09-04 15:10:53 +00003548 // make sure we operate on the canonical type
3549 lhptee = Context.getCanonicalType(lhptee);
3550 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003551
Steve Naroff3454b6c2008-09-04 15:10:53 +00003552 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003553
Steve Naroff3454b6c2008-09-04 15:10:53 +00003554 // For blocks we enforce that qualifiers are identical.
3555 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3556 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003557
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003558 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003559 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003560 return ConvTy;
3561}
3562
Mike Stump9afab102009-02-19 03:04:26 +00003563/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3564/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003565/// pointers. Here are some objectionable examples that GCC considers warnings:
3566///
3567/// int a, *pint;
3568/// short *pshort;
3569/// struct foo *pfoo;
3570///
3571/// pint = pshort; // warning: assignment from incompatible pointer type
3572/// a = pint; // warning: assignment makes integer from pointer without a cast
3573/// pint = a; // warning: assignment makes pointer from integer without a cast
3574/// pint = pfoo; // warning: assignment from incompatible pointer type
3575///
3576/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003577/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003578///
Chris Lattner005ed752008-01-04 18:04:52 +00003579Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003580Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003581 // Get canonical types. We're not formatting these types, just comparing
3582 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003583 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3584 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003585
3586 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003587 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003588
David Chisnall44663db2009-08-17 16:35:33 +00003589 if ((lhsType->isObjCClassType() &&
3590 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3591 (rhsType->isObjCClassType() &&
3592 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3593 return Compatible;
3594 }
3595
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003596 // If the left-hand side is a reference type, then we are in a
3597 // (rare!) case where we've allowed the use of references in C,
3598 // e.g., as a parameter type in a built-in function. In this case,
3599 // just make sure that the type referenced is compatible with the
3600 // right-hand side type. The caller is responsible for adjusting
3601 // lhsType so that the resulting expression does not have reference
3602 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003603 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003604 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003605 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003606 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003607 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003608 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3609 // to the same ExtVector type.
3610 if (lhsType->isExtVectorType()) {
3611 if (rhsType->isExtVectorType())
3612 return lhsType == rhsType ? Compatible : Incompatible;
3613 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3614 return Compatible;
3615 }
3616
Nate Begemanc5f0f652008-07-14 18:02:46 +00003617 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003618 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003619 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003620 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003621 if (getLangOptions().LaxVectorConversions &&
3622 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003623 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003624 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003625 }
3626 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003627 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003628
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003629 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003630 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003631
Chris Lattner390564e2008-04-07 06:49:41 +00003632 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003633 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003634 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003635
Chris Lattner390564e2008-04-07 06:49:41 +00003636 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003637 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003638
Steve Naroff8194a542009-07-20 17:56:53 +00003639 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003640 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003641 if (lhsType->isVoidPointerType()) // an exception to the rule.
3642 return Compatible;
3643 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003644 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003645 if (rhsType->getAs<BlockPointerType>()) {
3646 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003647 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003648
3649 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003650 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003651 return Compatible;
3652 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003653 return Incompatible;
3654 }
3655
3656 if (isa<BlockPointerType>(lhsType)) {
3657 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003658 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003659
Steve Naroffa982c712008-09-29 18:10:17 +00003660 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003661 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003662 return Compatible;
3663
Steve Naroff3454b6c2008-09-04 15:10:53 +00003664 if (rhsType->isBlockPointerType())
3665 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003666
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003667 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003668 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003669 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003670 }
Chris Lattner1853da22008-01-04 23:18:45 +00003671 return Incompatible;
3672 }
3673
Steve Naroff329ec222009-07-10 23:34:53 +00003674 if (isa<ObjCObjectPointerType>(lhsType)) {
3675 if (rhsType->isIntegerType())
3676 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003677
3678 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003679 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003680 if (rhsType->isVoidPointerType()) // an exception to the rule.
3681 return Compatible;
3682 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003683 }
3684 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003685 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3686 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003687 if (Context.typesAreCompatible(lhsType, rhsType))
3688 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003689 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3690 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003691 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003692 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003693 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003694 if (RHSPT->getPointeeType()->isVoidType())
3695 return Compatible;
3696 }
3697 // Treat block pointers as objects.
3698 if (rhsType->isBlockPointerType())
3699 return Compatible;
3700 return Incompatible;
3701 }
Chris Lattner390564e2008-04-07 06:49:41 +00003702 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003703 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003704 if (lhsType == Context.BoolTy)
3705 return Compatible;
3706
3707 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003708 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003709
Mike Stump9afab102009-02-19 03:04:26 +00003710 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003711 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003712
3713 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003714 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003715 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003716 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003717 }
Steve Naroff329ec222009-07-10 23:34:53 +00003718 if (isa<ObjCObjectPointerType>(rhsType)) {
3719 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3720 if (lhsType == Context.BoolTy)
3721 return Compatible;
3722
3723 if (lhsType->isIntegerType())
3724 return PointerToInt;
3725
Steve Naroff8194a542009-07-20 17:56:53 +00003726 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003727 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003728 if (lhsType->isVoidPointerType()) // an exception to the rule.
3729 return Compatible;
3730 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003731 }
3732 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003733 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003734 return Compatible;
3735 return Incompatible;
3736 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003737
Chris Lattner1853da22008-01-04 23:18:45 +00003738 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003739 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003740 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003741 }
3742 return Incompatible;
3743}
3744
Douglas Gregor144b06c2009-04-29 22:16:16 +00003745/// \brief Constructs a transparent union from an expression that is
3746/// used to initialize the transparent union.
3747static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3748 QualType UnionType, FieldDecl *Field) {
3749 // Build an initializer list that designates the appropriate member
3750 // of the transparent union.
3751 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3752 &E, 1,
3753 SourceLocation());
3754 Initializer->setType(UnionType);
3755 Initializer->setInitializedFieldInUnion(Field);
3756
3757 // Build a compound literal constructing a value of the transparent
3758 // union type from this initializer list.
3759 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3760 false);
3761}
3762
3763Sema::AssignConvertType
3764Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3765 QualType FromType = rExpr->getType();
3766
3767 // If the ArgType is a Union type, we want to handle a potential
3768 // transparent_union GCC extension.
3769 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003770 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003771 return Incompatible;
3772
3773 // The field to initialize within the transparent union.
3774 RecordDecl *UD = UT->getDecl();
3775 FieldDecl *InitField = 0;
3776 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003777 for (RecordDecl::field_iterator it = UD->field_begin(),
3778 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003779 it != itend; ++it) {
3780 if (it->getType()->isPointerType()) {
3781 // If the transparent union contains a pointer type, we allow:
3782 // 1) void pointer
3783 // 2) null pointer constant
3784 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003785 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003786 ImpCastExprToType(rExpr, it->getType());
3787 InitField = *it;
3788 break;
3789 }
3790
3791 if (rExpr->isNullPointerConstant(Context)) {
3792 ImpCastExprToType(rExpr, it->getType());
3793 InitField = *it;
3794 break;
3795 }
3796 }
3797
3798 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3799 == Compatible) {
3800 InitField = *it;
3801 break;
3802 }
3803 }
3804
3805 if (!InitField)
3806 return Incompatible;
3807
3808 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3809 return Compatible;
3810}
3811
Chris Lattner005ed752008-01-04 18:04:52 +00003812Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003813Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003814 if (getLangOptions().CPlusPlus) {
3815 if (!lhsType->isRecordType()) {
3816 // C++ 5.17p3: If the left operand is not of class type, the
3817 // expression is implicitly converted (C++ 4) to the
3818 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003819 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3820 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003821 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003822 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003823 }
3824
3825 // FIXME: Currently, we fall through and treat C++ classes like C
3826 // structures.
3827 }
3828
Steve Naroffcdee22d2007-11-27 17:58:44 +00003829 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3830 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003831 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003832 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003833 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003834 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003835 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003836 return Compatible;
3837 }
Mike Stump9afab102009-02-19 03:04:26 +00003838
Chris Lattner5f505bf2007-10-16 02:55:40 +00003839 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003840 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003841 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003842 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003843 //
Mike Stump9afab102009-02-19 03:04:26 +00003844 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003845 if (!lhsType->isReferenceType())
3846 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003847
Chris Lattner005ed752008-01-04 18:04:52 +00003848 Sema::AssignConvertType result =
3849 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003850
Steve Naroff0f32f432007-08-24 22:33:52 +00003851 // C99 6.5.16.1p2: The value of the right operand is converted to the
3852 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003853 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3854 // so that we can use references in built-in functions even in C.
3855 // The getNonReferenceType() call makes sure that the resulting expression
3856 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003857 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003858 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003859 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003860}
3861
Chris Lattner1eafdea2008-11-18 01:30:42 +00003862QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003863 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003864 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003865 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003866 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003867}
3868
Mike Stump9afab102009-02-19 03:04:26 +00003869inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003870 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003871 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003872 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003873 QualType lhsType =
3874 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3875 QualType rhsType =
3876 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003877
Nate Begemanc5f0f652008-07-14 18:02:46 +00003878 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003879 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003880 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003881
Nate Begemanc5f0f652008-07-14 18:02:46 +00003882 // Handle the case of a vector & extvector type of the same size and element
3883 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003884 if (getLangOptions().LaxVectorConversions) {
3885 // FIXME: Should we warn here?
3886 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003887 if (const VectorType *RV = rhsType->getAsVectorType())
3888 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003889 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003890 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003891 }
3892 }
3893 }
Mike Stump9afab102009-02-19 03:04:26 +00003894
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003895 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3896 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3897 bool swapped = false;
3898 if (rhsType->isExtVectorType()) {
3899 swapped = true;
3900 std::swap(rex, lex);
3901 std::swap(rhsType, lhsType);
3902 }
3903
Nate Begemanf1695892009-06-28 19:12:57 +00003904 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003905 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3906 QualType EltTy = LV->getElementType();
3907 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3908 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003909 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003910 if (swapped) std::swap(rex, lex);
3911 return lhsType;
3912 }
3913 }
3914 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3915 rhsType->isRealFloatingType()) {
3916 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003917 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003918 if (swapped) std::swap(rex, lex);
3919 return lhsType;
3920 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003921 }
3922 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003923
Nate Begemanf1695892009-06-28 19:12:57 +00003924 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003925 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003926 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003927 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003928 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003929}
3930
Chris Lattner4b009652007-07-25 00:24:17 +00003931inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003932 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003933{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003934 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003935 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003936
Steve Naroff8f708362007-08-24 19:07:16 +00003937 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003938
Chris Lattner4b009652007-07-25 00:24:17 +00003939 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003940 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003941 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003942}
3943
3944inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003945 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003946{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003947 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3948 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3949 return CheckVectorOperands(Loc, lex, rex);
3950 return InvalidOperands(Loc, lex, rex);
3951 }
Chris Lattner4b009652007-07-25 00:24:17 +00003952
Steve Naroff8f708362007-08-24 19:07:16 +00003953 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003954
Chris Lattner4b009652007-07-25 00:24:17 +00003955 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003956 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003957 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003958}
3959
3960inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003961 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003962{
Eli Friedman3cd92882009-03-28 01:22:36 +00003963 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3964 QualType compType = CheckVectorOperands(Loc, lex, rex);
3965 if (CompLHSTy) *CompLHSTy = compType;
3966 return compType;
3967 }
Chris Lattner4b009652007-07-25 00:24:17 +00003968
Eli Friedman3cd92882009-03-28 01:22:36 +00003969 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003970
Chris Lattner4b009652007-07-25 00:24:17 +00003971 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003972 if (lex->getType()->isArithmeticType() &&
3973 rex->getType()->isArithmeticType()) {
3974 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003975 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003976 }
Chris Lattner4b009652007-07-25 00:24:17 +00003977
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003978 // Put any potential pointer into PExp
3979 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00003980 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003981 std::swap(PExp, IExp);
3982
Steve Naroff79ae19a2009-07-14 18:25:06 +00003983 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003984
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003985 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00003986 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00003987
Chris Lattner184f92d2009-04-24 23:50:08 +00003988 // Check for arithmetic on pointers to incomplete types.
3989 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003990 if (getLangOptions().CPlusPlus) {
3991 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003992 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003993 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003994 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003995
3996 // GNU extension: arithmetic on pointer to void
3997 Diag(Loc, diag::ext_gnu_void_ptr)
3998 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003999 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004000 if (getLangOptions().CPlusPlus) {
4001 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4002 << lex->getType() << lex->getSourceRange();
4003 return QualType();
4004 }
4005
4006 // GNU extension: arithmetic on pointer to function
4007 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4008 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004009 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004010 // Check if we require a complete type.
4011 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004012 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004013 PExp->getType()->isObjCObjectPointerType()) &&
4014 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004015 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4016 << PExp->getSourceRange()
4017 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00004018 return QualType();
4019 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004020 // Diagnose bad cases where we step over interface counts.
4021 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4022 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4023 << PointeeTy << PExp->getSourceRange();
4024 return QualType();
4025 }
4026
Eli Friedman3cd92882009-03-28 01:22:36 +00004027 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004028 QualType LHSTy = Context.isPromotableBitField(lex);
4029 if (LHSTy.isNull()) {
4030 LHSTy = lex->getType();
4031 if (LHSTy->isPromotableIntegerType())
4032 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004033 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004034 *CompLHSTy = LHSTy;
4035 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004036 return PExp->getType();
4037 }
4038 }
4039
Chris Lattner1eafdea2008-11-18 01:30:42 +00004040 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004041}
4042
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004043// C99 6.5.6
4044QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004045 SourceLocation Loc, QualType* CompLHSTy) {
4046 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4047 QualType compType = CheckVectorOperands(Loc, lex, rex);
4048 if (CompLHSTy) *CompLHSTy = compType;
4049 return compType;
4050 }
Mike Stump9afab102009-02-19 03:04:26 +00004051
Eli Friedman3cd92882009-03-28 01:22:36 +00004052 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004053
Chris Lattnerf6da2912007-12-09 21:53:25 +00004054 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004055
Chris Lattnerf6da2912007-12-09 21:53:25 +00004056 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004057 if (lex->getType()->isArithmeticType()
4058 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004059 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004060 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004061 }
Steve Naroff329ec222009-07-10 23:34:53 +00004062
Chris Lattnerf6da2912007-12-09 21:53:25 +00004063 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004064 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004065 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004066
Douglas Gregor05e28f62009-03-24 19:52:54 +00004067 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004068
Douglas Gregor05e28f62009-03-24 19:52:54 +00004069 bool ComplainAboutVoid = false;
4070 Expr *ComplainAboutFunc = 0;
4071 if (lpointee->isVoidType()) {
4072 if (getLangOptions().CPlusPlus) {
4073 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4074 << lex->getSourceRange() << rex->getSourceRange();
4075 return QualType();
4076 }
4077
4078 // GNU C extension: arithmetic on pointer to void
4079 ComplainAboutVoid = true;
4080 } else if (lpointee->isFunctionType()) {
4081 if (getLangOptions().CPlusPlus) {
4082 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004083 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004084 return QualType();
4085 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004086
4087 // GNU C extension: arithmetic on pointer to function
4088 ComplainAboutFunc = lex;
4089 } else if (!lpointee->isDependentType() &&
4090 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004091 PDiag(diag::err_typecheck_sub_ptr_object)
4092 << lex->getSourceRange()
4093 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004094 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004095
Chris Lattner184f92d2009-04-24 23:50:08 +00004096 // Diagnose bad cases where we step over interface counts.
4097 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4098 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4099 << lpointee << lex->getSourceRange();
4100 return QualType();
4101 }
4102
Chris Lattnerf6da2912007-12-09 21:53:25 +00004103 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004104 if (rex->getType()->isIntegerType()) {
4105 if (ComplainAboutVoid)
4106 Diag(Loc, diag::ext_gnu_void_ptr)
4107 << lex->getSourceRange() << rex->getSourceRange();
4108 if (ComplainAboutFunc)
4109 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4110 << ComplainAboutFunc->getType()
4111 << ComplainAboutFunc->getSourceRange();
4112
Eli Friedman3cd92882009-03-28 01:22:36 +00004113 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004114 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004115 }
Mike Stump9afab102009-02-19 03:04:26 +00004116
Chris Lattnerf6da2912007-12-09 21:53:25 +00004117 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004118 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004119 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004120
Douglas Gregor05e28f62009-03-24 19:52:54 +00004121 // RHS must be a completely-type object type.
4122 // Handle the GNU void* extension.
4123 if (rpointee->isVoidType()) {
4124 if (getLangOptions().CPlusPlus) {
4125 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4126 << lex->getSourceRange() << rex->getSourceRange();
4127 return QualType();
4128 }
Mike Stump9afab102009-02-19 03:04:26 +00004129
Douglas Gregor05e28f62009-03-24 19:52:54 +00004130 ComplainAboutVoid = true;
4131 } else if (rpointee->isFunctionType()) {
4132 if (getLangOptions().CPlusPlus) {
4133 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004134 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004135 return QualType();
4136 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004137
4138 // GNU extension: arithmetic on pointer to function
4139 if (!ComplainAboutFunc)
4140 ComplainAboutFunc = rex;
4141 } else if (!rpointee->isDependentType() &&
4142 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004143 PDiag(diag::err_typecheck_sub_ptr_object)
4144 << rex->getSourceRange()
4145 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004146 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004147
Eli Friedman143ddc92009-05-16 13:54:38 +00004148 if (getLangOptions().CPlusPlus) {
4149 // Pointee types must be the same: C++ [expr.add]
4150 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4151 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4152 << lex->getType() << rex->getType()
4153 << lex->getSourceRange() << rex->getSourceRange();
4154 return QualType();
4155 }
4156 } else {
4157 // Pointee types must be compatible C99 6.5.6p3
4158 if (!Context.typesAreCompatible(
4159 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4160 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4161 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4162 << lex->getType() << rex->getType()
4163 << lex->getSourceRange() << rex->getSourceRange();
4164 return QualType();
4165 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004166 }
Mike Stump9afab102009-02-19 03:04:26 +00004167
Douglas Gregor05e28f62009-03-24 19:52:54 +00004168 if (ComplainAboutVoid)
4169 Diag(Loc, diag::ext_gnu_void_ptr)
4170 << lex->getSourceRange() << rex->getSourceRange();
4171 if (ComplainAboutFunc)
4172 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4173 << ComplainAboutFunc->getType()
4174 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004175
4176 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004177 return Context.getPointerDiffType();
4178 }
4179 }
Mike Stump9afab102009-02-19 03:04:26 +00004180
Chris Lattner1eafdea2008-11-18 01:30:42 +00004181 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004182}
4183
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004184// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004185QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004186 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004187 // C99 6.5.7p2: Each of the operands shall have integer type.
4188 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004189 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004190
Chris Lattner2c8bff72007-12-12 05:47:28 +00004191 // Shifts don't perform usual arithmetic conversions, they just do integer
4192 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004193 QualType LHSTy = Context.isPromotableBitField(lex);
4194 if (LHSTy.isNull()) {
4195 LHSTy = lex->getType();
4196 if (LHSTy->isPromotableIntegerType())
4197 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004198 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004199 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004200 ImpCastExprToType(lex, LHSTy);
4201
Chris Lattner2c8bff72007-12-12 05:47:28 +00004202 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004203
Ryan Flynnf109fff2009-08-07 16:20:20 +00004204 // Sanity-check shift operands
4205 llvm::APSInt Right;
4206 // Check right/shifter operand
4207 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004208 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004209 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4210 else {
4211 llvm::APInt LeftBits(Right.getBitWidth(),
4212 Context.getTypeSize(lex->getType()));
4213 if (Right.uge(LeftBits))
4214 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4215 }
4216 }
4217
Chris Lattner2c8bff72007-12-12 05:47:28 +00004218 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004219 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004220}
4221
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004222// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004223QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004224 unsigned OpaqueOpc, bool isRelational) {
4225 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4226
Nate Begemanc5f0f652008-07-14 18:02:46 +00004227 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004228 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004229
Chris Lattner254f3bc2007-08-26 01:18:55 +00004230 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004231 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4232 UsualArithmeticConversions(lex, rex);
4233 else {
4234 UsualUnaryConversions(lex);
4235 UsualUnaryConversions(rex);
4236 }
Chris Lattner4b009652007-07-25 00:24:17 +00004237 QualType lType = lex->getType();
4238 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004239
Mike Stumpea3d74e2009-05-07 18:43:07 +00004240 if (!lType->isFloatingType()
4241 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004242 // For non-floating point types, check for self-comparisons of the form
4243 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4244 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004245 // NOTE: Don't warn about comparisons of enum constants. These can arise
4246 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004247 Expr *LHSStripped = lex->IgnoreParens();
4248 Expr *RHSStripped = rex->IgnoreParens();
4249 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4250 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004251 if (DRL->getDecl() == DRR->getDecl() &&
4252 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004253 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004254
4255 if (isa<CastExpr>(LHSStripped))
4256 LHSStripped = LHSStripped->IgnoreParenCasts();
4257 if (isa<CastExpr>(RHSStripped))
4258 RHSStripped = RHSStripped->IgnoreParenCasts();
4259
4260 // Warn about comparisons against a string constant (unless the other
4261 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004262 Expr *literalString = 0;
4263 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004264 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004265 !RHSStripped->isNullPointerConstant(Context)) {
4266 literalString = lex;
4267 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004268 } else if ((isa<StringLiteral>(RHSStripped) ||
4269 isa<ObjCEncodeExpr>(RHSStripped)) &&
4270 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004271 literalString = rex;
4272 literalStringStripped = RHSStripped;
4273 }
4274
4275 if (literalString) {
4276 std::string resultComparison;
4277 switch (Opc) {
4278 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4279 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4280 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4281 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4282 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4283 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4284 default: assert(false && "Invalid comparison operator");
4285 }
4286 Diag(Loc, diag::warn_stringcompare)
4287 << isa<ObjCEncodeExpr>(literalStringStripped)
4288 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004289 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4290 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4291 "strcmp(")
4292 << CodeModificationHint::CreateInsertion(
4293 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004294 resultComparison);
4295 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004296 }
Mike Stump9afab102009-02-19 03:04:26 +00004297
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004298 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004299 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004300
Chris Lattner254f3bc2007-08-26 01:18:55 +00004301 if (isRelational) {
4302 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004303 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004304 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004305 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004306 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004307 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004308 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004309 }
Mike Stump9afab102009-02-19 03:04:26 +00004310
Chris Lattner254f3bc2007-08-26 01:18:55 +00004311 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004312 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004313 }
Mike Stump9afab102009-02-19 03:04:26 +00004314
Chris Lattner22be8422007-08-26 01:10:14 +00004315 bool LHSIsNull = lex->isNullPointerConstant(Context);
4316 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004317
Chris Lattner254f3bc2007-08-26 01:18:55 +00004318 // All of the following pointer related warnings are GCC extensions, except
4319 // when handling null pointer constants. One day, we can consider making them
4320 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004321 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004322 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004323 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004324 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004325 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004326
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004327 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004328 if (LCanPointeeTy == RCanPointeeTy)
4329 return ResultTy;
4330
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004331 // C++ [expr.rel]p2:
4332 // [...] Pointer conversions (4.10) and qualification
4333 // conversions (4.4) are performed on pointer operands (or on
4334 // a pointer operand and a null pointer constant) to bring
4335 // them to their composite pointer type. [...]
4336 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004337 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004338 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004339 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004340 if (T.isNull()) {
4341 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4342 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4343 return QualType();
4344 }
4345
4346 ImpCastExprToType(lex, T);
4347 ImpCastExprToType(rex, T);
4348 return ResultTy;
4349 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004350 // C99 6.5.9p2 and C99 6.5.8p2
4351 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4352 RCanPointeeTy.getUnqualifiedType())) {
4353 // Valid unless a relational comparison of function pointers
4354 if (isRelational && LCanPointeeTy->isFunctionType()) {
4355 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4356 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4357 }
4358 } else if (!isRelational &&
4359 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4360 // Valid unless comparison between non-null pointer and function pointer
4361 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4362 && !LHSIsNull && !RHSIsNull) {
4363 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4364 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4365 }
4366 } else {
4367 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004368 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004369 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004370 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004371 if (LCanPointeeTy != RCanPointeeTy)
4372 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004373 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004374 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004375
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004376 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004377 // Comparison of pointers with null pointer constants and equality
4378 // comparisons of member pointers to null pointer constants.
4379 if (RHSIsNull &&
4380 (lType->isPointerType() ||
4381 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004382 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004383 return ResultTy;
4384 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004385 if (LHSIsNull &&
4386 (rType->isPointerType() ||
4387 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004388 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004389 return ResultTy;
4390 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004391
4392 // Comparison of member pointers.
4393 if (!isRelational &&
4394 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4395 // C++ [expr.eq]p2:
4396 // In addition, pointers to members can be compared, or a pointer to
4397 // member and a null pointer constant. Pointer to member conversions
4398 // (4.11) and qualification conversions (4.4) are performed to bring
4399 // them to a common type. If one operand is a null pointer constant,
4400 // the common type is the type of the other operand. Otherwise, the
4401 // common type is a pointer to member type similar (4.4) to the type
4402 // of one of the operands, with a cv-qualification signature (4.4)
4403 // that is the union of the cv-qualification signatures of the operand
4404 // types.
4405 QualType T = FindCompositePointerType(lex, rex);
4406 if (T.isNull()) {
4407 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4408 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4409 return QualType();
4410 }
4411
4412 ImpCastExprToType(lex, T);
4413 ImpCastExprToType(rex, T);
4414 return ResultTy;
4415 }
4416
4417 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004418 if (lType->isNullPtrType() && rType->isNullPtrType())
4419 return ResultTy;
4420 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004421
Steve Naroff3454b6c2008-09-04 15:10:53 +00004422 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004423 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004424 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4425 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004426
Steve Naroff3454b6c2008-09-04 15:10:53 +00004427 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004428 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004429 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004430 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004431 }
4432 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004433 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004434 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004435 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004436 if (!isRelational
4437 && ((lType->isBlockPointerType() && rType->isPointerType())
4438 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004439 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004440 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004441 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004442 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004443 ->getPointeeType()->isVoidType())))
4444 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4445 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004446 }
4447 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004448 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004449 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004450
Steve Naroff329ec222009-07-10 23:34:53 +00004451 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004452 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004453 const PointerType *LPT = lType->getAs<PointerType>();
4454 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004455 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004456 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004457 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004458 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004459
Steve Naroff030fcda2008-11-17 19:49:16 +00004460 if (!LPtrToVoid && !RPtrToVoid &&
4461 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004462 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004463 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004464 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004465 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004466 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004467 }
Steve Naroff329ec222009-07-10 23:34:53 +00004468 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004469 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004470 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4471 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004472 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004473 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004474 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004475 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004476 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004477 unsigned DiagID = 0;
4478 if (RHSIsNull) {
4479 if (isRelational)
4480 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4481 } else if (isRelational)
4482 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4483 else
4484 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4485
4486 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004487 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004488 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004489 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004490 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004491 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004492 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004493 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004494 unsigned DiagID = 0;
4495 if (LHSIsNull) {
4496 if (isRelational)
4497 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4498 } else if (isRelational)
4499 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4500 else
4501 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004502
Chris Lattner124569f2009-08-23 00:03:44 +00004503 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004504 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004505 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004506 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004507 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004508 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004509 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004510 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004511 if (!isRelational && RHSIsNull
4512 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004513 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004514 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004515 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004516 if (!isRelational && LHSIsNull
4517 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004518 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004519 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004520 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004521 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004522}
4523
Nate Begemanc5f0f652008-07-14 18:02:46 +00004524/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004525/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004526/// like a scalar comparison, a vector comparison produces a vector of integer
4527/// types.
4528QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004529 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004530 bool isRelational) {
4531 // Check to make sure we're operating on vectors of the same type and width,
4532 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004533 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004534 if (vType.isNull())
4535 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004536
Nate Begemanc5f0f652008-07-14 18:02:46 +00004537 QualType lType = lex->getType();
4538 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004539
Nate Begemanc5f0f652008-07-14 18:02:46 +00004540 // For non-floating point types, check for self-comparisons of the form
4541 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4542 // often indicate logic errors in the program.
4543 if (!lType->isFloatingType()) {
4544 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4545 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4546 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004547 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004548 }
Mike Stump9afab102009-02-19 03:04:26 +00004549
Nate Begemanc5f0f652008-07-14 18:02:46 +00004550 // Check for comparisons of floating point operands using != and ==.
4551 if (!isRelational && lType->isFloatingType()) {
4552 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004553 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004554 }
Mike Stump9afab102009-02-19 03:04:26 +00004555
Nate Begemanc5f0f652008-07-14 18:02:46 +00004556 // Return the type for the comparison, which is the same as vector type for
4557 // integer vectors, or an integer type of identical size and number of
4558 // elements for floating point vectors.
4559 if (lType->isIntegerType())
4560 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004561
Nate Begemanc5f0f652008-07-14 18:02:46 +00004562 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004563 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004564 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004565 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004566 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004567 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4568
Mike Stump9afab102009-02-19 03:04:26 +00004569 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004570 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004571 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4572}
4573
Chris Lattner4b009652007-07-25 00:24:17 +00004574inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004575 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004576{
4577 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004578 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004579
Steve Naroff8f708362007-08-24 19:07:16 +00004580 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004581
Chris Lattner4b009652007-07-25 00:24:17 +00004582 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004583 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004584 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004585}
4586
4587inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004588 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004589{
4590 UsualUnaryConversions(lex);
4591 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004592
Eli Friedmanbea3f842008-05-13 20:16:47 +00004593 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004594 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004595 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004596}
4597
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004598/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4599/// is a read-only property; return true if so. A readonly property expression
4600/// depends on various declarations and thus must be treated specially.
4601///
Mike Stump9afab102009-02-19 03:04:26 +00004602static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004603{
4604 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4605 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4606 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4607 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004608 if (const ObjCObjectPointerType *OPT =
4609 BaseType->getAsObjCInterfacePointerType())
4610 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4611 if (S.isPropertyReadonly(PDecl, IFace))
4612 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004613 }
4614 }
4615 return false;
4616}
4617
Chris Lattner4c2642c2008-11-18 01:22:49 +00004618/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4619/// emit an error and return true. If so, return false.
4620static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004621 SourceLocation OrigLoc = Loc;
4622 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4623 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004624 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4625 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004626 if (IsLV == Expr::MLV_Valid)
4627 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004628
Chris Lattner4c2642c2008-11-18 01:22:49 +00004629 unsigned Diag = 0;
4630 bool NeedType = false;
4631 switch (IsLV) { // C99 6.5.16p2
4632 default: assert(0 && "Unknown result from isModifiableLvalue!");
4633 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004634 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004635 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4636 NeedType = true;
4637 break;
Mike Stump9afab102009-02-19 03:04:26 +00004638 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004639 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4640 NeedType = true;
4641 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004642 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004643 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4644 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004645 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004646 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4647 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004648 case Expr::MLV_IncompleteType:
4649 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004650 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00004651 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4652 << E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004653 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004654 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4655 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004656 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004657 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4658 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004659 case Expr::MLV_ReadonlyProperty:
4660 Diag = diag::error_readonly_property_assignment;
4661 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004662 case Expr::MLV_NoSetterProperty:
4663 Diag = diag::error_nosetter_property_assignment;
4664 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004665 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004666
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004667 SourceRange Assign;
4668 if (Loc != OrigLoc)
4669 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004670 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004671 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004672 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004673 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004674 return true;
4675}
4676
4677
4678
4679// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004680QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4681 SourceLocation Loc,
4682 QualType CompoundType) {
4683 // Verify that LHS is a modifiable lvalue, and emit error if not.
4684 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004685 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004686
4687 QualType LHSType = LHS->getType();
4688 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004689
Chris Lattner005ed752008-01-04 18:04:52 +00004690 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004691 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004692 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004693 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004694 // Special case of NSObject attributes on c-style pointer types.
4695 if (ConvTy == IncompatiblePointer &&
4696 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004697 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004698 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004699 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004700 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004701
Chris Lattner34c85082008-08-21 18:04:13 +00004702 // If the RHS is a unary plus or minus, check to see if they = and + are
4703 // right next to each other. If so, the user may have typo'd "x =+ 4"
4704 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004705 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004706 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4707 RHSCheck = ICE->getSubExpr();
4708 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4709 if ((UO->getOpcode() == UnaryOperator::Plus ||
4710 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004711 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004712 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004713 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4714 // And there is a space or other character before the subexpr of the
4715 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004716 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4717 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004718 Diag(Loc, diag::warn_not_compound_assign)
4719 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4720 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004721 }
Chris Lattner34c85082008-08-21 18:04:13 +00004722 }
4723 } else {
4724 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004725 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004726 }
Chris Lattner005ed752008-01-04 18:04:52 +00004727
Chris Lattner1eafdea2008-11-18 01:30:42 +00004728 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4729 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004730 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004731
Chris Lattner4b009652007-07-25 00:24:17 +00004732 // C99 6.5.16p3: The type of an assignment expression is the type of the
4733 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004734 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004735 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4736 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004737 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004738 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004739 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004740}
4741
Chris Lattner1eafdea2008-11-18 01:30:42 +00004742// C99 6.5.17
4743QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004744 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004745 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004746
4747 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4748 // incomplete in C++).
4749
Chris Lattner1eafdea2008-11-18 01:30:42 +00004750 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004751}
4752
4753/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4754/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004755QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4756 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004757 if (Op->isTypeDependent())
4758 return Context.DependentTy;
4759
Chris Lattnere65182c2008-11-21 07:05:48 +00004760 QualType ResType = Op->getType();
4761 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004762
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004763 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4764 // Decrement of bool is not allowed.
4765 if (!isInc) {
4766 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4767 return QualType();
4768 }
4769 // Increment of bool sets it to true, but is deprecated.
4770 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4771 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004772 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004773 } else if (ResType->isAnyPointerType()) {
4774 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004775
Chris Lattnere65182c2008-11-21 07:05:48 +00004776 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004777 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004778 if (getLangOptions().CPlusPlus) {
4779 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4780 << Op->getSourceRange();
4781 return QualType();
4782 }
4783
4784 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004785 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004786 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004787 if (getLangOptions().CPlusPlus) {
4788 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4789 << Op->getType() << Op->getSourceRange();
4790 return QualType();
4791 }
4792
4793 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004794 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004795 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004796 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4797 << Op->getSourceRange()
4798 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004799 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004800 // Diagnose bad cases where we step over interface counts.
4801 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4802 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4803 << PointeeTy << Op->getSourceRange();
4804 return QualType();
4805 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004806 } else if (ResType->isComplexType()) {
4807 // C99 does not support ++/-- on complex types, we allow as an extension.
4808 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004809 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004810 } else {
4811 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004812 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004813 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004814 }
Mike Stump9afab102009-02-19 03:04:26 +00004815 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004816 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004817 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004818 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004819 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004820}
4821
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004822/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004823/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004824/// where the declaration is needed for type checking. We only need to
4825/// handle cases when the expression references a function designator
4826/// or is an lvalue. Here are some examples:
4827/// - &(x) => x
4828/// - &*****f => f for f a function designator.
4829/// - &s.xx => s
4830/// - &s.zz[1].yy -> s, if zz is an array
4831/// - *(x + 1) -> x, if x is an array
4832/// - &"123"[2] -> 0
4833/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004834static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004835 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004836 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004837 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004838 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004839 case Stmt::MemberExprClass:
Douglas Gregore399ad42009-08-26 22:36:53 +00004840 case Stmt::CXXQualifiedMemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004841 // If this is an arrow operator, the address is an offset from
4842 // the base's value, so the object the base refers to is
4843 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004844 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004845 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004846 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004847 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004848 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004849 // FIXME: This code shouldn't be necessary! We should catch the implicit
4850 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004851 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4852 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4853 if (ICE->getSubExpr()->getType()->isArrayType())
4854 return getPrimaryDecl(ICE->getSubExpr());
4855 }
4856 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004857 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004858 case Stmt::UnaryOperatorClass: {
4859 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004860
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004861 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004862 case UnaryOperator::Real:
4863 case UnaryOperator::Imag:
4864 case UnaryOperator::Extension:
4865 return getPrimaryDecl(UO->getSubExpr());
4866 default:
4867 return 0;
4868 }
4869 }
Chris Lattner4b009652007-07-25 00:24:17 +00004870 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004871 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004872 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004873 // If the result of an implicit cast is an l-value, we care about
4874 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004875 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004876 default:
4877 return 0;
4878 }
4879}
4880
4881/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004882/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004883/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004884/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004885/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004886/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004887/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004888QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004889 // Make sure to ignore parentheses in subsequent checks
4890 op = op->IgnoreParens();
4891
Douglas Gregore6be68a2008-12-17 22:52:20 +00004892 if (op->isTypeDependent())
4893 return Context.DependentTy;
4894
Steve Naroff9c6c3592008-01-13 17:10:08 +00004895 if (getLangOptions().C99) {
4896 // Implement C99-only parts of addressof rules.
4897 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4898 if (uOp->getOpcode() == UnaryOperator::Deref)
4899 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4900 // (assuming the deref expression is valid).
4901 return uOp->getSubExpr()->getType();
4902 }
4903 // Technically, there should be a check for array subscript
4904 // expressions here, but the result of one is always an lvalue anyway.
4905 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004906 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004907 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004908
Eli Friedman14ab4c42009-05-16 23:27:50 +00004909 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4910 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004911 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004912 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004913 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004914 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4915 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004916 return QualType();
4917 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004918 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004919 // The operand cannot be a bit-field
4920 Diag(OpLoc, diag::err_typecheck_address_of)
4921 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004922 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004923 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4924 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004925 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004926 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004927 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004928 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004929 } else if (isa<ObjCPropertyRefExpr>(op)) {
4930 // cannot take address of a property expression.
4931 Diag(OpLoc, diag::err_typecheck_address_of)
4932 << "property expression" << op->getSourceRange();
4933 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004934 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004935 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004936 // with the register storage-class specifier.
4937 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4938 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004939 Diag(OpLoc, diag::err_typecheck_address_of)
4940 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004941 return QualType();
4942 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004943 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4944 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004945 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004946 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004947 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004948 // Could be a pointer to member, though, if there is an explicit
4949 // scope qualifier for the class.
4950 if (isa<QualifiedDeclRefExpr>(op)) {
4951 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004952 if (Ctx && Ctx->isRecord()) {
4953 if (FD->getType()->isReferenceType()) {
4954 Diag(OpLoc,
4955 diag::err_cannot_form_pointer_to_member_of_reference_type)
4956 << FD->getDeclName() << FD->getType();
4957 return QualType();
4958 }
4959
Sebastian Redl0c9da212009-02-03 20:19:35 +00004960 return Context.getMemberPointerType(op->getType(),
4961 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004962 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004963 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004964 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004965 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004966 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004967 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4968 return Context.getMemberPointerType(op->getType(),
4969 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4970 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004971 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004972 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004973
Eli Friedman14ab4c42009-05-16 23:27:50 +00004974 if (lval == Expr::LV_IncompleteVoidType) {
4975 // Taking the address of a void variable is technically illegal, but we
4976 // allow it in cases which are otherwise valid.
4977 // Example: "extern void x; void* y = &x;".
4978 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4979 }
4980
Chris Lattner4b009652007-07-25 00:24:17 +00004981 // If the operand has type "type", the result has type "pointer to type".
4982 return Context.getPointerType(op->getType());
4983}
4984
Chris Lattnerda5c0872008-11-23 09:13:29 +00004985QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004986 if (Op->isTypeDependent())
4987 return Context.DependentTy;
4988
Chris Lattnerda5c0872008-11-23 09:13:29 +00004989 UsualUnaryConversions(Op);
4990 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004991
Chris Lattnerda5c0872008-11-23 09:13:29 +00004992 // Note that per both C89 and C99, this is always legal, even if ptype is an
4993 // incomplete type or void. It would be possible to warn about dereferencing
4994 // a void pointer, but it's completely well-defined, and such a warning is
4995 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004996 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004997 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004998
Steve Naroff329ec222009-07-10 23:34:53 +00004999 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5000 return OPT->getPointeeType();
5001
Chris Lattner77d52da2008-11-20 06:06:08 +00005002 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005003 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005004 return QualType();
5005}
5006
5007static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5008 tok::TokenKind Kind) {
5009 BinaryOperator::Opcode Opc;
5010 switch (Kind) {
5011 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005012 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5013 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005014 case tok::star: Opc = BinaryOperator::Mul; break;
5015 case tok::slash: Opc = BinaryOperator::Div; break;
5016 case tok::percent: Opc = BinaryOperator::Rem; break;
5017 case tok::plus: Opc = BinaryOperator::Add; break;
5018 case tok::minus: Opc = BinaryOperator::Sub; break;
5019 case tok::lessless: Opc = BinaryOperator::Shl; break;
5020 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5021 case tok::lessequal: Opc = BinaryOperator::LE; break;
5022 case tok::less: Opc = BinaryOperator::LT; break;
5023 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5024 case tok::greater: Opc = BinaryOperator::GT; break;
5025 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5026 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5027 case tok::amp: Opc = BinaryOperator::And; break;
5028 case tok::caret: Opc = BinaryOperator::Xor; break;
5029 case tok::pipe: Opc = BinaryOperator::Or; break;
5030 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5031 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5032 case tok::equal: Opc = BinaryOperator::Assign; break;
5033 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5034 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5035 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5036 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5037 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5038 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5039 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5040 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5041 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5042 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5043 case tok::comma: Opc = BinaryOperator::Comma; break;
5044 }
5045 return Opc;
5046}
5047
5048static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5049 tok::TokenKind Kind) {
5050 UnaryOperator::Opcode Opc;
5051 switch (Kind) {
5052 default: assert(0 && "Unknown unary op!");
5053 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5054 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5055 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5056 case tok::star: Opc = UnaryOperator::Deref; break;
5057 case tok::plus: Opc = UnaryOperator::Plus; break;
5058 case tok::minus: Opc = UnaryOperator::Minus; break;
5059 case tok::tilde: Opc = UnaryOperator::Not; break;
5060 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005061 case tok::kw___real: Opc = UnaryOperator::Real; break;
5062 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5063 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5064 }
5065 return Opc;
5066}
5067
Douglas Gregord7f915e2008-11-06 23:29:22 +00005068/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5069/// operator @p Opc at location @c TokLoc. This routine only supports
5070/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005071Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5072 unsigned Op,
5073 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005074 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005075 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005076 // The following two variables are used for compound assignment operators
5077 QualType CompLHSTy; // Type of LHS after promotions for computation
5078 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005079
5080 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005081 case BinaryOperator::Assign:
5082 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5083 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005084 case BinaryOperator::PtrMemD:
5085 case BinaryOperator::PtrMemI:
5086 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5087 Opc == BinaryOperator::PtrMemI);
5088 break;
5089 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005090 case BinaryOperator::Div:
5091 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5092 break;
5093 case BinaryOperator::Rem:
5094 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5095 break;
5096 case BinaryOperator::Add:
5097 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5098 break;
5099 case BinaryOperator::Sub:
5100 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5101 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005102 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005103 case BinaryOperator::Shr:
5104 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5105 break;
5106 case BinaryOperator::LE:
5107 case BinaryOperator::LT:
5108 case BinaryOperator::GE:
5109 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005110 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005111 break;
5112 case BinaryOperator::EQ:
5113 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005114 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005115 break;
5116 case BinaryOperator::And:
5117 case BinaryOperator::Xor:
5118 case BinaryOperator::Or:
5119 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5120 break;
5121 case BinaryOperator::LAnd:
5122 case BinaryOperator::LOr:
5123 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5124 break;
5125 case BinaryOperator::MulAssign:
5126 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005127 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5128 CompLHSTy = CompResultTy;
5129 if (!CompResultTy.isNull())
5130 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005131 break;
5132 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005133 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5134 CompLHSTy = CompResultTy;
5135 if (!CompResultTy.isNull())
5136 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005137 break;
5138 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005139 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5140 if (!CompResultTy.isNull())
5141 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005142 break;
5143 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005144 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5145 if (!CompResultTy.isNull())
5146 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005147 break;
5148 case BinaryOperator::ShlAssign:
5149 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005150 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5151 CompLHSTy = CompResultTy;
5152 if (!CompResultTy.isNull())
5153 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005154 break;
5155 case BinaryOperator::AndAssign:
5156 case BinaryOperator::XorAssign:
5157 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005158 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5159 CompLHSTy = CompResultTy;
5160 if (!CompResultTy.isNull())
5161 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005162 break;
5163 case BinaryOperator::Comma:
5164 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5165 break;
5166 }
5167 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005168 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005169 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005170 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5171 else
5172 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005173 CompLHSTy, CompResultTy,
5174 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005175}
5176
Chris Lattner4b009652007-07-25 00:24:17 +00005177// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005178Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5179 tok::TokenKind Kind,
5180 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005181 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005182 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005183
Steve Naroff87d58b42007-09-16 03:34:24 +00005184 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5185 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005186
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005187 if (getLangOptions().CPlusPlus &&
5188 (lhs->getType()->isOverloadableType() ||
5189 rhs->getType()->isOverloadableType())) {
5190 // Find all of the overloaded operators visible from this
5191 // point. We perform both an operator-name lookup from the local
5192 // scope and an argument-dependent lookup based on the types of
5193 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005194 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005195 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5196 if (OverOp != OO_None) {
5197 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5198 Functions);
5199 Expr *Args[2] = { lhs, rhs };
5200 DeclarationName OpName
5201 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5202 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005203 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005204
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005205 // Build the (potentially-overloaded, potentially-dependent)
5206 // binary operation.
5207 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005208 }
5209
Douglas Gregord7f915e2008-11-06 23:29:22 +00005210 // Build a built-in binary operation.
5211 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005212}
5213
Douglas Gregorc78182d2009-03-13 23:49:33 +00005214Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5215 unsigned OpcIn,
5216 ExprArg InputArg) {
5217 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005218
Mike Stumpe127ae32009-05-16 07:39:55 +00005219 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005220 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005221 QualType resultType;
5222 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005223 case UnaryOperator::OffsetOf:
5224 assert(false && "Invalid unary operator");
5225 break;
5226
Chris Lattner4b009652007-07-25 00:24:17 +00005227 case UnaryOperator::PreInc:
5228 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005229 case UnaryOperator::PostInc:
5230 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005231 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005232 Opc == UnaryOperator::PreInc ||
5233 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005234 break;
Mike Stump9afab102009-02-19 03:04:26 +00005235 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005236 resultType = CheckAddressOfOperand(Input, OpLoc);
5237 break;
Mike Stump9afab102009-02-19 03:04:26 +00005238 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005239 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005240 resultType = CheckIndirectionOperand(Input, OpLoc);
5241 break;
5242 case UnaryOperator::Plus:
5243 case UnaryOperator::Minus:
5244 UsualUnaryConversions(Input);
5245 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005246 if (resultType->isDependentType())
5247 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005248 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5249 break;
5250 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5251 resultType->isEnumeralType())
5252 break;
5253 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5254 Opc == UnaryOperator::Plus &&
5255 resultType->isPointerType())
5256 break;
5257
Sebastian Redl8b769972009-01-19 00:08:26 +00005258 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5259 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005260 case UnaryOperator::Not: // bitwise complement
5261 UsualUnaryConversions(Input);
5262 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005263 if (resultType->isDependentType())
5264 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005265 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5266 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5267 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005268 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005269 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005270 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005271 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5272 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005273 break;
5274 case UnaryOperator::LNot: // logical negation
5275 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5276 DefaultFunctionArrayConversion(Input);
5277 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005278 if (resultType->isDependentType())
5279 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005280 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005281 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5282 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005283 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005284 // In C++, it's bool. C++ 5.3.1p8
5285 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005286 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005287 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005288 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005289 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005290 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005291 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005292 resultType = Input->getType();
5293 break;
5294 }
5295 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005296 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005297
5298 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005299 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005300}
5301
Douglas Gregorc78182d2009-03-13 23:49:33 +00005302// Unary Operators. 'Tok' is the token for the operator.
5303Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5304 tok::TokenKind Op, ExprArg input) {
5305 Expr *Input = (Expr*)input.get();
5306 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5307
5308 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5309 // Find all of the overloaded operators visible from this
5310 // point. We perform both an operator-name lookup from the local
5311 // scope and an argument-dependent lookup based on the types of
5312 // the arguments.
5313 FunctionSet Functions;
5314 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5315 if (OverOp != OO_None) {
5316 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5317 Functions);
5318 DeclarationName OpName
5319 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5320 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5321 }
5322
5323 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5324 }
5325
5326 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5327}
5328
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005329/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005330Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5331 SourceLocation LabLoc,
5332 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005333 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005334 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005335
Daniel Dunbar879788d2008-08-04 16:51:22 +00005336 // If we haven't seen this label yet, create a forward reference. It
5337 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005338 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005339 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005340
Chris Lattner4b009652007-07-25 00:24:17 +00005341 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005342 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5343 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005344}
5345
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005346Sema::OwningExprResult
5347Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5348 SourceLocation RPLoc) { // "({..})"
5349 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005350 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5351 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5352
Eli Friedmanbc941e12009-01-24 23:09:00 +00005353 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005354 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005355 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005356
Chris Lattner4b009652007-07-25 00:24:17 +00005357 // FIXME: there are a variety of strange constraints to enforce here, for
5358 // example, it is not possible to goto into a stmt expression apparently.
5359 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005360
Chris Lattner4b009652007-07-25 00:24:17 +00005361 // If there are sub stmts in the compound stmt, take the type of the last one
5362 // as the type of the stmtexpr.
5363 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005364
Chris Lattner200964f2008-07-26 19:51:01 +00005365 if (!Compound->body_empty()) {
5366 Stmt *LastStmt = Compound->body_back();
5367 // If LastStmt is a label, skip down through into the body.
5368 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5369 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005370
Chris Lattner200964f2008-07-26 19:51:01 +00005371 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005372 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005373 }
Mike Stump9afab102009-02-19 03:04:26 +00005374
Eli Friedman2b128322009-03-23 00:24:07 +00005375 // FIXME: Check that expression type is complete/non-abstract; statement
5376 // expressions are not lvalues.
5377
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005378 substmt.release();
5379 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005380}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005381
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005382Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5383 SourceLocation BuiltinLoc,
5384 SourceLocation TypeLoc,
5385 TypeTy *argty,
5386 OffsetOfComponent *CompPtr,
5387 unsigned NumComponents,
5388 SourceLocation RPLoc) {
5389 // FIXME: This function leaks all expressions in the offset components on
5390 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005391 // FIXME: Preserve type source info.
5392 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005393 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005394
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005395 bool Dependent = ArgTy->isDependentType();
5396
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005397 // We must have at least one component that refers to the type, and the first
5398 // one is known to be a field designator. Verify that the ArgTy represents
5399 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005400 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005401 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005402
Eli Friedman2b128322009-03-23 00:24:07 +00005403 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5404 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005405
Eli Friedman342d9432009-02-27 06:44:11 +00005406 // Otherwise, create a null pointer as the base, and iteratively process
5407 // the offsetof designators.
5408 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5409 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005410 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005411 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005412
Chris Lattnerb37522e2007-08-31 21:49:13 +00005413 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5414 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005415 // FIXME: This diagnostic isn't actually visible because the location is in
5416 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005417 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005418 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5419 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005420
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005421 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005422 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005423
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005424 // FIXME: Dependent case loses a lot of information here. And probably
5425 // leaks like a sieve.
5426 for (unsigned i = 0; i != NumComponents; ++i) {
5427 const OffsetOfComponent &OC = CompPtr[i];
5428 if (OC.isBrackets) {
5429 // Offset of an array sub-field. TODO: Should we allow vector elements?
5430 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5431 if (!AT) {
5432 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005433 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5434 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005435 }
5436
5437 // FIXME: C++: Verify that operator[] isn't overloaded.
5438
Eli Friedman342d9432009-02-27 06:44:11 +00005439 // Promote the array so it looks more like a normal array subscript
5440 // expression.
5441 DefaultFunctionArrayConversion(Res);
5442
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005443 // C99 6.5.2.1p1
5444 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005445 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005446 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005447 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005448 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005449 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005450
5451 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5452 OC.LocEnd);
5453 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005454 }
Mike Stump9afab102009-02-19 03:04:26 +00005455
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005456 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005457 if (!RC) {
5458 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005459 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5460 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005461 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005462
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005463 // Get the decl corresponding to this.
5464 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005465 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005466 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005467 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5468 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5469 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005470 DidWarnAboutNonPOD = true;
5471 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005472 }
5473
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005474 FieldDecl *MemberDecl
5475 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5476 LookupMemberName)
5477 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005478 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005479 if (!MemberDecl)
Anders Carlsson4355a392009-08-30 00:54:35 +00005480 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005481 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005482
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005483 // FIXME: C++: Verify that MemberDecl isn't a static field.
5484 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005485 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005486 Res = BuildAnonymousStructUnionMemberReference(
5487 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005488 } else {
5489 // MemberDecl->getType() doesn't get the right qualifiers, but it
5490 // doesn't matter here.
5491 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5492 MemberDecl->getType().getNonReferenceType());
5493 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005494 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005495 }
Mike Stump9afab102009-02-19 03:04:26 +00005496
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005497 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5498 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005499}
5500
5501
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005502Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5503 TypeTy *arg1,TypeTy *arg2,
5504 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005505 // FIXME: Preserve type source info.
5506 QualType argT1 = GetTypeFromParser(arg1);
5507 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005508
Steve Naroff63bad2d2007-08-01 22:05:33 +00005509 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005510
Douglas Gregore6211502009-05-19 22:28:02 +00005511 if (getLangOptions().CPlusPlus) {
5512 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5513 << SourceRange(BuiltinLoc, RPLoc);
5514 return ExprError();
5515 }
5516
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005517 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5518 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005519}
5520
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005521Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5522 ExprArg cond,
5523 ExprArg expr1, ExprArg expr2,
5524 SourceLocation RPLoc) {
5525 Expr *CondExpr = static_cast<Expr*>(cond.get());
5526 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5527 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005528
Steve Naroff93c53012007-08-03 21:21:27 +00005529 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5530
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005531 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005532 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005533 resType = Context.DependentTy;
5534 } else {
5535 // The conditional expression is required to be a constant expression.
5536 llvm::APSInt condEval(32);
5537 SourceLocation ExpLoc;
5538 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005539 return ExprError(Diag(ExpLoc,
5540 diag::err_typecheck_choose_expr_requires_constant)
5541 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005542
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005543 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5544 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5545 }
5546
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005547 cond.release(); expr1.release(); expr2.release();
5548 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5549 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005550}
5551
Steve Naroff52a81c02008-09-03 18:15:37 +00005552//===----------------------------------------------------------------------===//
5553// Clang Extensions.
5554//===----------------------------------------------------------------------===//
5555
5556/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005557void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005558 // Analyze block parameters.
5559 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005560
Steve Naroff52a81c02008-09-03 18:15:37 +00005561 // Add BSI to CurBlock.
5562 BSI->PrevBlockInfo = CurBlock;
5563 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005564
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005565 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005566 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005567 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005568 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005569 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5570 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005571
Steve Naroff52059382008-10-10 01:28:17 +00005572 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005573 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005574}
5575
Mike Stumpc1fddff2009-02-04 22:31:32 +00005576void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005577 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005578
5579 if (ParamInfo.getNumTypeObjects() == 0
5580 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005581 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005582 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5583
Mike Stump458287d2009-04-28 01:10:27 +00005584 if (T->isArrayType()) {
5585 Diag(ParamInfo.getSourceRange().getBegin(),
5586 diag::err_block_returns_array);
5587 return;
5588 }
5589
Mike Stumpc1fddff2009-02-04 22:31:32 +00005590 // The parameter list is optional, if there was none, assume ().
5591 if (!T->isFunctionType())
5592 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5593
5594 CurBlock->hasPrototype = true;
5595 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005596 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005597 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005598 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005599 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005600 // FIXME: remove the attribute.
5601 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005602 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5603
5604 // Do not allow returning a objc interface by-value.
5605 if (RetTy->isObjCInterfaceType()) {
5606 Diag(ParamInfo.getSourceRange().getBegin(),
5607 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5608 return;
5609 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005610 return;
5611 }
5612
Steve Naroff52a81c02008-09-03 18:15:37 +00005613 // Analyze arguments to block.
5614 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5615 "Not a function declarator!");
5616 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005617
Steve Naroff52059382008-10-10 01:28:17 +00005618 CurBlock->hasPrototype = FTI.hasPrototype;
5619 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005620
Steve Naroff52a81c02008-09-03 18:15:37 +00005621 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5622 // no arguments, not a function that takes a single void argument.
5623 if (FTI.hasPrototype &&
5624 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005625 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5626 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005627 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005628 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005629 } else if (FTI.hasPrototype) {
5630 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005631 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005632 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005633 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005634 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005635 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005636 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005637 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005638 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5639 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5640 // If this has an identifier, add it to the scope stack.
5641 if ((*AI)->getIdentifier())
5642 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005643
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005644 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005645 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005646 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005647 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005648 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005649 // FIXME: remove the attribute.
5650 }
5651
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005652 // Analyze the return type.
5653 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5654 QualType RetTy = T->getAsFunctionType()->getResultType();
5655
5656 // Do not allow returning a objc interface by-value.
5657 if (RetTy->isObjCInterfaceType()) {
5658 Diag(ParamInfo.getSourceRange().getBegin(),
5659 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5660 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005661 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005662}
5663
5664/// ActOnBlockError - If there is an error parsing a block, this callback
5665/// is invoked to pop the information about the block from the action impl.
5666void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5667 // Ensure that CurBlock is deleted.
5668 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005669
Chris Lattnere7765e12009-04-19 05:28:12 +00005670 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5671
Steve Naroff52a81c02008-09-03 18:15:37 +00005672 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005673 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005674 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005675 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005676}
5677
5678/// ActOnBlockStmtExpr - This is called when the body of a block statement
5679/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005680Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5681 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005682 // If blocks are disabled, emit an error.
5683 if (!LangOpts.Blocks)
5684 Diag(CaretLoc, diag::err_blocks_disable);
5685
Steve Naroff52a81c02008-09-03 18:15:37 +00005686 // Ensure that CurBlock is deleted.
5687 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005688
Steve Naroff52059382008-10-10 01:28:17 +00005689 PopDeclContext();
5690
Steve Naroff52a81c02008-09-03 18:15:37 +00005691 // Pop off CurBlock, handle nested blocks.
5692 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005693
Steve Naroff52a81c02008-09-03 18:15:37 +00005694 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005695 if (!BSI->ReturnType.isNull())
5696 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005697
Steve Naroff52a81c02008-09-03 18:15:37 +00005698 llvm::SmallVector<QualType, 8> ArgTypes;
5699 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5700 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005701
Mike Stump8e288f42009-07-28 22:04:01 +00005702 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005703 QualType BlockTy;
5704 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005705 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5706 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005707 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005708 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005709 BSI->isVariadic, 0, false, false, 0, 0,
5710 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005711
Eli Friedman2b128322009-03-23 00:24:07 +00005712 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005713 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005714 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005715
Chris Lattnere7765e12009-04-19 05:28:12 +00005716 // If needed, diagnose invalid gotos and switches in the block.
5717 if (CurFunctionNeedsScopeChecking)
5718 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5719 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5720
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005721 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005722 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005723 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5724 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005725}
5726
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005727Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5728 ExprArg expr, TypeTy *type,
5729 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005730 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005731 Expr *E = static_cast<Expr*>(expr.get());
5732 Expr *OrigExpr = E;
5733
Anders Carlsson36760332007-10-15 20:28:48 +00005734 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005735
5736 // Get the va_list type
5737 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005738 if (VaListType->isArrayType()) {
5739 // Deal with implicit array decay; for example, on x86-64,
5740 // va_list is an array, but it's supposed to decay to
5741 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005742 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005743 // Make sure the input expression also decays appropriately.
5744 UsualUnaryConversions(E);
5745 } else {
5746 // Otherwise, the va_list argument must be an l-value because
5747 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005748 if (!E->isTypeDependent() &&
5749 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005750 return ExprError();
5751 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005752
Douglas Gregor25990972009-05-19 23:10:31 +00005753 if (!E->isTypeDependent() &&
5754 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005755 return ExprError(Diag(E->getLocStart(),
5756 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005757 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005758 }
Mike Stump9afab102009-02-19 03:04:26 +00005759
Eli Friedman2b128322009-03-23 00:24:07 +00005760 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005761 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005762
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005763 expr.release();
5764 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5765 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005766}
5767
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005768Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005769 // The type of __null will be int or long, depending on the size of
5770 // pointers on the target.
5771 QualType Ty;
5772 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5773 Ty = Context.IntTy;
5774 else
5775 Ty = Context.LongTy;
5776
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005777 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005778}
5779
Chris Lattner005ed752008-01-04 18:04:52 +00005780bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5781 SourceLocation Loc,
5782 QualType DstType, QualType SrcType,
5783 Expr *SrcExpr, const char *Flavor) {
5784 // Decode the result (notice that AST's are still created for extensions).
5785 bool isInvalid = false;
5786 unsigned DiagKind;
5787 switch (ConvTy) {
5788 default: assert(0 && "Unknown conversion type");
5789 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005790 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005791 DiagKind = diag::ext_typecheck_convert_pointer_int;
5792 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005793 case IntToPointer:
5794 DiagKind = diag::ext_typecheck_convert_int_pointer;
5795 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005796 case IncompatiblePointer:
5797 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5798 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005799 case IncompatiblePointerSign:
5800 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5801 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005802 case FunctionVoidPointer:
5803 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5804 break;
5805 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005806 // If the qualifiers lost were because we were applying the
5807 // (deprecated) C++ conversion from a string literal to a char*
5808 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5809 // Ideally, this check would be performed in
5810 // CheckPointerTypesForAssignment. However, that would require a
5811 // bit of refactoring (so that the second argument is an
5812 // expression, rather than a type), which should be done as part
5813 // of a larger effort to fix CheckPointerTypesForAssignment for
5814 // C++ semantics.
5815 if (getLangOptions().CPlusPlus &&
5816 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5817 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005818 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5819 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005820 case IntToBlockPointer:
5821 DiagKind = diag::err_int_to_block_pointer;
5822 break;
5823 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005824 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005825 break;
Steve Naroff19608432008-10-14 22:18:38 +00005826 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005827 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005828 // it can give a more specific diagnostic.
5829 DiagKind = diag::warn_incompatible_qualified_id;
5830 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005831 case IncompatibleVectors:
5832 DiagKind = diag::warn_incompatible_vectors;
5833 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005834 case Incompatible:
5835 DiagKind = diag::err_typecheck_convert_incompatible;
5836 isInvalid = true;
5837 break;
5838 }
Mike Stump9afab102009-02-19 03:04:26 +00005839
Chris Lattner271d4c22008-11-24 05:29:24 +00005840 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5841 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005842 return isInvalid;
5843}
Anders Carlssond5201b92008-11-30 19:50:32 +00005844
Chris Lattnereec8ae22009-04-25 21:59:05 +00005845bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005846 llvm::APSInt ICEResult;
5847 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5848 if (Result)
5849 *Result = ICEResult;
5850 return false;
5851 }
5852
Anders Carlssond5201b92008-11-30 19:50:32 +00005853 Expr::EvalResult EvalResult;
5854
Mike Stump9afab102009-02-19 03:04:26 +00005855 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005856 EvalResult.HasSideEffects) {
5857 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5858
5859 if (EvalResult.Diag) {
5860 // We only show the note if it's not the usual "invalid subexpression"
5861 // or if it's actually in a subexpression.
5862 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5863 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5864 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5865 }
Mike Stump9afab102009-02-19 03:04:26 +00005866
Anders Carlssond5201b92008-11-30 19:50:32 +00005867 return true;
5868 }
5869
Eli Friedmance329412009-04-25 22:26:58 +00005870 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5871 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005872
Eli Friedmance329412009-04-25 22:26:58 +00005873 if (EvalResult.Diag &&
5874 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5875 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005876
Anders Carlssond5201b92008-11-30 19:50:32 +00005877 if (Result)
5878 *Result = EvalResult.Val.getInt();
5879 return false;
5880}
Douglas Gregor98189262009-06-19 23:52:42 +00005881
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005882Sema::ExpressionEvaluationContext
5883Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5884 // Introduce a new set of potentially referenced declarations to the stack.
5885 if (NewContext == PotentiallyPotentiallyEvaluated)
5886 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5887
5888 std::swap(ExprEvalContext, NewContext);
5889 return NewContext;
5890}
5891
5892void
5893Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5894 ExpressionEvaluationContext NewContext) {
5895 ExprEvalContext = NewContext;
5896
5897 if (OldContext == PotentiallyPotentiallyEvaluated) {
5898 // Mark any remaining declarations in the current position of the stack
5899 // as "referenced". If they were not meant to be referenced, semantic
5900 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5901 PotentiallyReferencedDecls RemainingDecls;
5902 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5903 PotentiallyReferencedDeclStack.pop_back();
5904
5905 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5906 IEnd = RemainingDecls.end();
5907 I != IEnd; ++I)
5908 MarkDeclarationReferenced(I->first, I->second);
5909 }
5910}
Douglas Gregor98189262009-06-19 23:52:42 +00005911
5912/// \brief Note that the given declaration was referenced in the source code.
5913///
5914/// This routine should be invoke whenever a given declaration is referenced
5915/// in the source code, and where that reference occurred. If this declaration
5916/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5917/// C99 6.9p3), then the declaration will be marked as used.
5918///
5919/// \param Loc the location where the declaration was referenced.
5920///
5921/// \param D the declaration that has been referenced by the source code.
5922void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5923 assert(D && "No declaration?");
5924
Douglas Gregorcad27f62009-06-22 23:06:13 +00005925 if (D->isUsed())
5926 return;
5927
Douglas Gregor98189262009-06-19 23:52:42 +00005928 // Mark a parameter declaration "used", regardless of whether we're in a
5929 // template or not.
5930 if (isa<ParmVarDecl>(D))
5931 D->setUsed(true);
5932
5933 // Do not mark anything as "used" within a dependent context; wait for
5934 // an instantiation.
5935 if (CurContext->isDependentContext())
5936 return;
5937
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005938 switch (ExprEvalContext) {
5939 case Unevaluated:
5940 // We are in an expression that is not potentially evaluated; do nothing.
5941 return;
5942
5943 case PotentiallyEvaluated:
5944 // We are in a potentially-evaluated expression, so this declaration is
5945 // "used"; handle this below.
5946 break;
5947
5948 case PotentiallyPotentiallyEvaluated:
5949 // We are in an expression that may be potentially evaluated; queue this
5950 // declaration reference until we know whether the expression is
5951 // potentially evaluated.
5952 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5953 return;
5954 }
5955
Douglas Gregor98189262009-06-19 23:52:42 +00005956 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005957 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005958 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005959 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5960 if (!Constructor->isUsed())
5961 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005962 } else if (Constructor->isImplicit() &&
5963 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005964 if (!Constructor->isUsed())
5965 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5966 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005967 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5968 if (Destructor->isImplicit() && !Destructor->isUsed())
5969 DefineImplicitDestructor(Loc, Destructor);
5970
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005971 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5972 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5973 MethodDecl->getOverloadedOperator() == OO_Equal) {
5974 if (!MethodDecl->isUsed())
5975 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5976 }
5977 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00005978 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005979 // Implicit instantiation of function templates and member functions of
5980 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00005981 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005982 // FIXME: distinguish between implicit instantiations of function
5983 // templates and explicit specializations (the latter don't get
5984 // instantiated, naturally).
5985 if (Function->getInstantiatedFromMemberFunction() ||
5986 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00005987 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00005988 }
5989
5990
Douglas Gregor98189262009-06-19 23:52:42 +00005991 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00005992 Function->setUsed(true);
5993 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00005994 }
Douglas Gregor98189262009-06-19 23:52:42 +00005995
5996 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00005997 // Implicit instantiation of static data members of class templates.
5998 // FIXME: distinguish between implicit instantiations (which we need to
5999 // actually instantiate) and explicit specializations.
6000 if (Var->isStaticDataMember() &&
6001 Var->getInstantiatedFromStaticDataMember())
6002 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6003
Douglas Gregor98189262009-06-19 23:52:42 +00006004 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006005
Douglas Gregor98189262009-06-19 23:52:42 +00006006 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006007 return;
6008}
Douglas Gregor98189262009-06-19 23:52:42 +00006009}
6010