blob: 213292e159b02afb3fe6d9c332157b905de628a9 [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"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
David Chisnall44663db2009-08-17 16:35:33 +000029
Douglas Gregoraa57e862009-02-18 21:56:37 +000030/// \brief Determine whether the use of this declaration is valid, and
31/// emit any corresponding diagnostics.
32///
33/// This routine diagnoses various problems with referencing
34/// declarations that can occur when using a declaration. For example,
35/// it might warn if a deprecated or unavailable declaration is being
36/// used, or produce an error (and return true) if a C++0x deleted
37/// function is being used.
38///
39/// \returns true if there was an error (this declaration cannot be
40/// referenced), false otherwise.
41bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000042 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000043 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000044 // Implementing deprecated stuff requires referencing deprecated
45 // stuff. Don't warn if we are implementing a deprecated
46 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000047 bool isSilenced = false;
48
49 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
50 // If this reference happens *in* a deprecated function or method, don't
51 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000052 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000053
54 // If this is an Objective-C method implementation, check to see if the
55 // method was deprecated on the declaration, not the definition.
56 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
57 // The semantic decl context of a ObjCMethodDecl is the
58 // ObjCImplementationDecl.
59 if (ObjCImplementationDecl *Impl
60 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
61
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000062 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000064 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000065 }
66 }
67 }
68
69 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000070 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71 }
72
Douglas Gregoraa57e862009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000075 if (FD->isDeleted()) {
76 Diag(Loc, diag::err_deleted_function_use);
77 Diag(D->getLocation(), diag::note_unavailable_here) << true;
78 return true;
79 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000080 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000081
82 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000083 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000084 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000085 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86 }
87
Douglas Gregoraa57e862009-02-18 21:56:37 +000088 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000089}
90
Fariborz Jahanian180f3412009-05-13 18:09:35 +000091/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
92/// (and other functions in future), which have been declared with sentinel
93/// attribute. It warns if call does not have the sentinel argument.
94///
95void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
96 Expr **Args, unsigned NumArgs)
97{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +000099 if (!attr)
100 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000103
Mike Stumpe127ae32009-05-16 07:39:55 +0000104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000107 bool warnNotEnoughArgs = false;
108 int isMethod = 0;
109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = MD->param_end();
112 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
119 isMethod = 1;
Mike Stump90fc78e2009-08-04 21:02:39 +0000120 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000121 // skip over named parameters.
122 ObjCMethodDecl::param_iterator P, E = FD->param_end();
123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124 if (nullPos)
125 --nullPos;
126 else
127 ++i;
128 }
129 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump90fc78e2009-08-04 21:02:39 +0000130 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000131 // block or function pointer call.
132 QualType Ty = V->getType();
133 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
134 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000135 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000137 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138 unsigned NumArgsInProto = Proto->getNumArgs();
139 unsigned k;
140 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141 if (nullPos)
142 --nullPos;
143 else
144 ++i;
145 }
146 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147 }
148 if (Ty->isBlockPointerType())
149 isMethod = 2;
Mike Stump90fc78e2009-08-04 21:02:39 +0000150 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000151 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000152 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000153 return;
154
155 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000158 return;
159 }
160 int sentinel = i;
161 while (sentinelPos > 0 && i < NumArgs-1) {
162 --sentinelPos;
163 ++i;
164 }
165 if (sentinelPos > 0) {
166 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000168 return;
169 }
170 while (i < NumArgs-1) {
171 ++i;
172 ++sentinel;
173 }
174 Expr *sentinelExpr = Args[sentinel];
175 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000177 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000178 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000179 }
180 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000181}
182
Douglas Gregor3bb30002009-02-26 21:00:50 +0000183SourceRange Sema::getExprRange(ExprTy *E) const {
184 Expr *Ex = (Expr *)E;
185 return Ex? Ex->getSourceRange() : SourceRange();
186}
187
Chris Lattner299b8842008-07-25 21:10:04 +0000188//===----------------------------------------------------------------------===//
189// Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
Chris Lattner299b8842008-07-25 21:10:04 +0000192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194 QualType Ty = E->getType();
195 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
Chris Lattner299b8842008-07-25 21:10:04 +0000197 if (Ty->isFunctionType())
198 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000199 else if (Ty->isArrayType()) {
200 // In C90 mode, arrays only promote to pointers if the array expression is
201 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
202 // type 'array of type' is converted to an expression that has type 'pointer
203 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
204 // that has type 'array of type' ...". The relevant change is "an lvalue"
205 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000206 //
207 // C++ 4.2p1:
208 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
209 // T" can be converted to an rvalue of type "pointer to T".
210 //
211 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
212 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000213 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
214 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000215 }
Chris Lattner299b8842008-07-25 21:10:04 +0000216}
217
218/// UsualUnaryConversions - Performs various conversions that are common to most
219/// operators (C99 6.3). The conversions of array and function types are
220/// sometimes surpressed. For example, the array->pointer conversion doesn't
221/// apply if the array is an argument to the sizeof or address (&) operators.
222/// In these instances, this routine should *not* be called.
223Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
224 QualType Ty = Expr->getType();
225 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
226
Douglas Gregor70b307e2009-05-01 20:41:21 +0000227 // C99 6.3.1.1p2:
228 //
229 // The following may be used in an expression wherever an int or
230 // unsigned int may be used:
231 // - an object or expression with an integer type whose integer
232 // conversion rank is less than or equal to the rank of int
233 // and unsigned int.
234 // - A bit-field of type _Bool, int, signed int, or unsigned int.
235 //
236 // If an int can represent all values of the original type, the
237 // value is converted to an int; otherwise, it is converted to an
238 // unsigned int. These are called the integer promotions. All
239 // other types are unchanged by the integer promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000240 QualType PTy = Context.isPromotableBitField(Expr);
241 if (!PTy.isNull()) {
242 ImpCastExprToType(Expr, PTy);
243 return Expr;
244 }
Douglas Gregor70b307e2009-05-01 20:41:21 +0000245 if (Ty->isPromotableIntegerType()) {
Eli Friedman6ae7d112009-08-19 07:44:53 +0000246 QualType PT = Context.getPromotedIntegerType(Ty);
247 ImpCastExprToType(Expr, PT);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000248 return Expr;
Eli Friedman1931cc82009-08-20 04:21:42 +0000249 }
250
Douglas Gregor70b307e2009-05-01 20:41:21 +0000251 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000252 return Expr;
253}
254
Chris Lattner9305c3d2008-07-25 22:25:12 +0000255/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
256/// do not have a prototype. Arguments that have type float are promoted to
257/// double. All other argument types are converted by UsualUnaryConversions().
258void Sema::DefaultArgumentPromotion(Expr *&Expr) {
259 QualType Ty = Expr->getType();
260 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
261
262 // If this is a 'float' (CVR qualified or typedef) promote to double.
263 if (const BuiltinType *BT = Ty->getAsBuiltinType())
264 if (BT->getKind() == BuiltinType::Float)
265 return ImpCastExprToType(Expr, Context.DoubleTy);
266
267 UsualUnaryConversions(Expr);
268}
269
Chris Lattner81f00ed2009-04-12 08:11:20 +0000270/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
271/// will warn if the resulting type is not a POD type, and rejects ObjC
272/// interfaces passed by value. This returns true if the argument type is
273/// completely illegal.
274bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000275 DefaultArgumentPromotion(Expr);
276
Chris Lattner81f00ed2009-04-12 08:11:20 +0000277 if (Expr->getType()->isObjCInterfaceType()) {
278 Diag(Expr->getLocStart(),
279 diag::err_cannot_pass_objc_interface_to_vararg)
280 << Expr->getType() << CT;
281 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000282 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000283
284 if (!Expr->getType()->isPODType())
285 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
286 << Expr->getType() << CT;
287
288 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000289}
290
291
Chris Lattner299b8842008-07-25 21:10:04 +0000292/// UsualArithmeticConversions - Performs various conversions that are common to
293/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
294/// routine returns the first non-arithmetic type found. The client is
295/// responsible for emitting appropriate error diagnostics.
296/// FIXME: verify the conversion rules for "complex int" are consistent with
297/// GCC.
298QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
299 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000300 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000301 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000302
303 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000304
Chris Lattner299b8842008-07-25 21:10:04 +0000305 // For conversion purposes, we ignore any qualifiers.
306 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000307 QualType lhs =
308 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
309 QualType rhs =
310 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000311
312 // If both types are identical, no conversion is needed.
313 if (lhs == rhs)
314 return lhs;
315
316 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
317 // The caller can deal with this (e.g. pointer + int).
318 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
319 return lhs;
320
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000321 // Perform bitfield promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000322 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000323 if (!LHSBitfieldPromoteTy.isNull())
324 lhs = LHSBitfieldPromoteTy;
Eli Friedman1931cc82009-08-20 04:21:42 +0000325 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000326 if (!RHSBitfieldPromoteTy.isNull())
327 rhs = RHSBitfieldPromoteTy;
328
Eli Friedman6ae7d112009-08-19 07:44:53 +0000329 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000330 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000331 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000332 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000333 return destType;
334}
335
Chris Lattner299b8842008-07-25 21:10:04 +0000336//===----------------------------------------------------------------------===//
337// Semantic Analysis for various Expression Types
338//===----------------------------------------------------------------------===//
339
340
Steve Naroff87d58b42007-09-16 03:34:24 +0000341/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000342/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
343/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
344/// multiple tokens. However, the common case is that StringToks points to one
345/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000346///
347Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000348Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000349 assert(NumStringToks && "Must have at least one string!");
350
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000351 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000352 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000353 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000354
355 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
356 for (unsigned i = 0; i != NumStringToks; ++i)
357 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000358
Chris Lattnera6dcce32008-02-11 00:02:17 +0000359 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000360 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000361 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000362
363 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
364 if (getLangOptions().CPlusPlus)
365 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000366
Chris Lattnera6dcce32008-02-11 00:02:17 +0000367 // Get an array type for the string, according to C99 6.4.5. This includes
368 // the nul terminator character as well as the string length for pascal
369 // strings.
370 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000371 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000372 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000373
Chris Lattner4b009652007-07-25 00:24:17 +0000374 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000375 return Owned(StringLiteral::Create(Context, Literal.GetString(),
376 Literal.GetStringLength(),
377 Literal.AnyWide, StrTy,
378 &StringTokLocs[0],
379 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000380}
381
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000382/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
383/// CurBlock to VD should cause it to be snapshotted (as we do for auto
384/// variables defined outside the block) or false if this is not needed (e.g.
385/// for values inside the block or for globals).
386///
Chris Lattner0b464252009-04-21 22:26:47 +0000387/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
388/// up-to-date.
389///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000390static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
391 ValueDecl *VD) {
392 // If the value is defined inside the block, we couldn't snapshot it even if
393 // we wanted to.
394 if (CurBlock->TheDecl == VD->getDeclContext())
395 return false;
396
397 // If this is an enum constant or function, it is constant, don't snapshot.
398 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
399 return false;
400
401 // If this is a reference to an extern, static, or global variable, no need to
402 // snapshot it.
403 // FIXME: What about 'const' variables in C++?
404 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000405 if (!Var->hasLocalStorage())
406 return false;
407
408 // Blocks that have these can't be constant.
409 CurBlock->hasBlockDeclRefExprs = true;
410
411 // If we have nested blocks, the decl may be declared in an outer block (in
412 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
413 // be defined outside all of the current blocks (in which case the blocks do
414 // all get the bit). Walk the nesting chain.
415 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
416 NextBlock = NextBlock->PrevBlockInfo) {
417 // If we found the defining block for the variable, don't mark the block as
418 // having a reference outside it.
419 if (NextBlock->TheDecl == VD->getDeclContext())
420 break;
421
422 // Otherwise, the DeclRef from the inner block causes the outer one to need
423 // a snapshot as well.
424 NextBlock->hasBlockDeclRefExprs = true;
425 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000426
427 return true;
428}
429
430
431
Steve Naroff0acc9c92007-09-15 18:49:24 +0000432/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000433/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000434/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000435/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000436/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000437Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
438 IdentifierInfo &II,
439 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000440 const CXXScopeSpec *SS,
441 bool isAddressOfOperand) {
442 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000443 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000444}
445
Douglas Gregor566782a2009-01-06 05:10:23 +0000446/// BuildDeclRefExpr - Build either a DeclRefExpr or a
447/// QualifiedDeclRefExpr based on whether or not SS is a
448/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000449Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000450Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
451 bool TypeDependent, bool ValueDependent,
452 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000453 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
454 Diag(Loc,
455 diag::err_auto_variable_cannot_appear_in_own_initializer)
456 << D->getDeclName();
457 return ExprError();
458 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000459
460 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
461 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
462 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
463 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
464 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
465 << D->getIdentifier() << FD->getDeclName();
466 Diag(D->getLocation(), diag::note_local_variable_declared_here)
467 << D->getIdentifier();
468 return ExprError();
469 }
470 }
471 }
472 }
473
Douglas Gregor98189262009-06-19 23:52:42 +0000474 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000475
476 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000477 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000478 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
479 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000480 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000481 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000482 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
483
484 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000485}
486
Douglas Gregor723d3332009-01-07 00:43:41 +0000487/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
488/// variable corresponding to the anonymous union or struct whose type
489/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000490static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
491 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000492 assert(Record->isAnonymousStructOrUnion() &&
493 "Record must be an anonymous struct or union!");
494
Mike Stumpe127ae32009-05-16 07:39:55 +0000495 // FIXME: Once Decls are directly linked together, this will be an O(1)
496 // operation rather than a slow walk through DeclContext's vector (which
497 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000498 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000499 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
500 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000501 D != DEnd; ++D) {
502 if (*D == Record) {
503 // The object for the anonymous struct/union directly
504 // follows its type in the list of declarations.
505 ++D;
506 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000507 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000508 return *D;
509 }
510 }
511
512 assert(false && "Missing object for anonymous record");
513 return 0;
514}
515
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000516/// \brief Given a field that represents a member of an anonymous
517/// struct/union, build the path from that field's context to the
518/// actual member.
519///
520/// Construct the sequence of field member references we'll have to
521/// perform to get to the field in the anonymous union/struct. The
522/// list of members is built from the field outward, so traverse it
523/// backwards to go from an object in the current context to the field
524/// we found.
525///
526/// \returns The variable from which the field access should begin,
527/// for an anonymous struct/union that is not a member of another
528/// class. Otherwise, returns NULL.
529VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
530 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000531 assert(Field->getDeclContext()->isRecord() &&
532 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
533 && "Field must be stored inside an anonymous struct or union");
534
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000535 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000536 VarDecl *BaseObject = 0;
537 DeclContext *Ctx = Field->getDeclContext();
538 do {
539 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000540 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000541 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000542 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000543 else {
544 BaseObject = cast<VarDecl>(AnonObject);
545 break;
546 }
547 Ctx = Ctx->getParent();
548 } while (Ctx->isRecord() &&
549 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000550
551 return BaseObject;
552}
553
554Sema::OwningExprResult
555Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
556 FieldDecl *Field,
557 Expr *BaseObjectExpr,
558 SourceLocation OpLoc) {
559 llvm::SmallVector<FieldDecl *, 4> AnonFields;
560 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
561 AnonFields);
562
Douglas Gregor723d3332009-01-07 00:43:41 +0000563 // Build the expression that refers to the base object, from
564 // which we will build a sequence of member references to each
565 // of the anonymous union objects and, eventually, the field we
566 // found via name lookup.
567 bool BaseObjectIsPointer = false;
568 unsigned ExtraQuals = 0;
569 if (BaseObject) {
570 // BaseObject is an anonymous struct/union variable (and is,
571 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000572 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000573 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000574 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000575 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000576 ExtraQuals
577 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
578 } else if (BaseObjectExpr) {
579 // The caller provided the base object expression. Determine
580 // whether its a pointer and whether it adds any qualifiers to the
581 // anonymous struct/union fields we're looking into.
582 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000583 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000584 BaseObjectIsPointer = true;
585 ObjectType = ObjectPtr->getPointeeType();
586 }
587 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
588 } else {
589 // We've found a member of an anonymous struct/union that is
590 // inside a non-anonymous struct/union, so in a well-formed
591 // program our base object expression is "this".
592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
593 if (!MD->isStatic()) {
594 QualType AnonFieldType
595 = Context.getTagDeclType(
596 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
597 QualType ThisType = Context.getTagDeclType(MD->getParent());
598 if ((Context.getCanonicalType(AnonFieldType)
599 == Context.getCanonicalType(ThisType)) ||
600 IsDerivedFrom(ThisType, AnonFieldType)) {
601 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000602 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000603 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000604 BaseObjectIsPointer = true;
605 }
606 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000607 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
608 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000609 }
610 ExtraQuals = MD->getTypeQualifiers();
611 }
612
613 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000614 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
615 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000616 }
617
618 // Build the implicit member references to the field of the
619 // anonymous struct/union.
620 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000621 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000622 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
623 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
624 FI != FIEnd; ++FI) {
625 QualType MemberType = (*FI)->getType();
626 if (!(*FI)->isMutable()) {
627 unsigned combinedQualifiers
628 = MemberType.getCVRQualifiers() | ExtraQuals;
629 MemberType = MemberType.getQualifiedType(combinedQualifiers);
630 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000631 if (BaseAddrSpace != MemberType.getAddressSpace())
632 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000633 MarkDeclarationReferenced(Loc, *FI);
Steve Naroff774e4152009-01-21 00:14:39 +0000634 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
635 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000636 BaseObjectIsPointer = false;
637 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000638 }
639
Sebastian Redlcd883f72009-01-18 18:53:16 +0000640 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000641}
642
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000643/// ActOnDeclarationNameExpr - The parser has read some kind of name
644/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
645/// performs lookup on that name and returns an expression that refers
646/// to that name. This routine isn't directly called from the parser,
647/// because the parser doesn't know about DeclarationName. Rather,
648/// this routine is called by ActOnIdentifierExpr,
649/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
650/// which form the DeclarationName from the corresponding syntactic
651/// forms.
652///
653/// HasTrailingLParen indicates whether this identifier is used in a
654/// function call context. LookupCtx is only used for a C++
655/// qualified-id (foo::bar) to indicate the class or namespace that
656/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000657///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000658/// isAddressOfOperand means that this expression is the direct operand
659/// of an address-of operator. This matters because this is the only
660/// situation where a qualified name referencing a non-static member may
661/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000662Sema::OwningExprResult
663Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
664 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000665 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000666 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000667 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000668 if (SS && SS->isInvalid())
669 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000670
671 // C++ [temp.dep.expr]p3:
672 // An id-expression is type-dependent if it contains:
673 // -- a nested-name-specifier that contains a class-name that
674 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000675 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000676 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000677 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
678 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000679 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
680 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000681 }
682
Douglas Gregor411889e2009-02-13 23:20:09 +0000683 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
684 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000685
Sebastian Redlcd883f72009-01-18 18:53:16 +0000686 if (Lookup.isAmbiguous()) {
687 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
688 SS && SS->isSet() ? SS->getRange()
689 : SourceRange());
690 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000691 }
692
693 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000694
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000695 // If this reference is in an Objective-C method, then ivar lookup happens as
696 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000697 IdentifierInfo *II = Name.getAsIdentifierInfo();
698 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000699 // There are two cases to handle here. 1) scoped lookup could have failed,
700 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000701 // found a decl, but that decl is outside the current instance method (i.e.
702 // a global variable). In these two cases, we do a lookup for an ivar with
703 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000704 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000705 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000706 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000707 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000708 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000709 if (DiagnoseUseOfDecl(IV, Loc))
710 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000711
712 // If we're referencing an invalid decl, just return this as a silent
713 // error node. The error diagnostic was already emitted on the decl.
714 if (IV->isInvalidDecl())
715 return ExprError();
716
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000717 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
718 // If a class method attemps to use a free standing ivar, this is
719 // an error.
720 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
721 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
722 << IV->getDeclName());
723 // If a class method uses a global variable, even if an ivar with
724 // same name exists, use the global.
725 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000726 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
727 ClassDeclared != IFace)
728 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000729 // FIXME: This should use a new expr for a direct reference, don't
730 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000731 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000732 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
733 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000734 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000735 return Owned(new (Context)
736 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000737 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000738 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000739 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000740 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000741 // We should warn if a local variable hides an ivar.
742 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000743 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000744 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000745 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
746 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000747 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000748 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000749 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000750 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000751 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000752 QualType T;
753
754 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000755 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
756 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000757 else
758 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000759 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000760 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000761 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000762
Douglas Gregoraa57e862009-02-18 21:56:37 +0000763 // Determine whether this name might be a candidate for
764 // argument-dependent lookup.
765 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
766 HasTrailingLParen;
767
768 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000769 // We've seen something of the form
770 //
771 // identifier(
772 //
773 // and we did not find any entity by the name
774 // "identifier". However, this identifier is still subject to
775 // argument-dependent lookup, so keep track of the name.
776 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
777 Context.OverloadTy,
778 Loc));
779 }
780
Chris Lattner4b009652007-07-25 00:24:17 +0000781 if (D == 0) {
782 // Otherwise, this could be an implicitly declared function reference (legal
783 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000784 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000785 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000786 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000787 else {
788 // If this name wasn't predeclared and if this is not a function call,
789 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000790 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000791 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
792 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000793 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
794 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000795 return ExprError(Diag(Loc, diag::err_undeclared_use)
796 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000797 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000798 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000799 }
800 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000801
802 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
803 // Warn about constructs like:
804 // if (void *X = foo()) { ... } else { X }.
805 // In the else block, the pointer is always false.
806
807 // FIXME: In a template instantiation, we don't have scope
808 // information to check this property.
809 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
810 Scope *CheckS = S;
811 while (CheckS) {
812 if (CheckS->isWithinElse() &&
813 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
814 if (Var->getType()->isBooleanType())
815 ExprError(Diag(Loc, diag::warn_value_always_false)
816 << Var->getDeclName());
817 else
818 ExprError(Diag(Loc, diag::warn_value_always_zero)
819 << Var->getDeclName());
820 break;
821 }
822
823 // Move up one more control parent to check again.
824 CheckS = CheckS->getControlParent();
825 if (CheckS)
826 CheckS = CheckS->getParent();
827 }
828 }
829 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
830 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
831 // C99 DR 316 says that, if a function type comes from a
832 // function definition (without a prototype), that type is only
833 // used for checking compatibility. Therefore, when referencing
834 // the function, we pretend that we don't have the full function
835 // type.
836 if (DiagnoseUseOfDecl(Func, Loc))
837 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000838
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000839 QualType T = Func->getType();
840 QualType NoProtoType = T;
841 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
842 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
843 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
844 }
845 }
846
847 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
848}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000849/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000850bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000851Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
852 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
853 if (CXXRecordDecl *RD =
854 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
855 QualType DestType =
856 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000857 if (DestType->isDependentType() || From->getType()->isDependentType())
858 return false;
859 QualType FromRecordType = From->getType();
860 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000861 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000862 DestType = Context.getPointerType(DestType);
863 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000864 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000865 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
866 CheckDerivedToBaseConversion(FromRecordType,
867 DestRecordType,
868 From->getSourceRange().getBegin(),
869 From->getSourceRange()))
870 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000871 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
872 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000873 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000874 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000875}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000876
877/// \brief Complete semantic analysis for a reference to the given declaration.
878Sema::OwningExprResult
879Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
880 bool HasTrailingLParen,
881 const CXXScopeSpec *SS,
882 bool isAddressOfOperand) {
883 assert(D && "Cannot refer to a NULL declaration");
884 DeclarationName Name = D->getDeclName();
885
Sebastian Redl0c9da212009-02-03 20:19:35 +0000886 // If this is an expression of the form &Class::member, don't build an
887 // implicit member ref, because we want a pointer to the member in general,
888 // not any specific instance's member.
889 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000890 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000891 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000892 QualType DType;
893 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
894 DType = FD->getType().getNonReferenceType();
895 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
896 DType = Method->getType();
897 } else if (isa<OverloadedFunctionDecl>(D)) {
898 DType = Context.OverloadTy;
899 }
900 // Could be an inner type. That's diagnosed below, so ignore it here.
901 if (!DType.isNull()) {
902 // The pointer is type- and value-dependent if it points into something
903 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000904 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000905 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000906 }
907 }
908 }
909
Douglas Gregor723d3332009-01-07 00:43:41 +0000910 // We may have found a field within an anonymous union or struct
911 // (C++ [class.union]).
912 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
913 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
914 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000915
Douglas Gregor3257fb52008-12-22 05:46:06 +0000916 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
917 if (!MD->isStatic()) {
918 // C++ [class.mfct.nonstatic]p2:
919 // [...] if name lookup (3.4.1) resolves the name in the
920 // id-expression to a nonstatic nontype member of class X or of
921 // a base class of X, the id-expression is transformed into a
922 // class member access expression (5.2.5) using (*this) (9.3.2)
923 // as the postfix-expression to the left of the '.' operator.
924 DeclContext *Ctx = 0;
925 QualType MemberType;
926 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
927 Ctx = FD->getDeclContext();
928 MemberType = FD->getType();
929
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000930 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000931 MemberType = RefType->getPointeeType();
932 else if (!FD->isMutable()) {
933 unsigned combinedQualifiers
934 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
935 MemberType = MemberType.getQualifiedType(combinedQualifiers);
936 }
937 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
938 if (!Method->isStatic()) {
939 Ctx = Method->getParent();
940 MemberType = Method->getType();
941 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000942 } else if (FunctionTemplateDecl *FunTmpl
943 = dyn_cast<FunctionTemplateDecl>(D)) {
944 if (CXXMethodDecl *Method
945 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
946 if (!Method->isStatic()) {
947 Ctx = Method->getParent();
948 MemberType = Context.OverloadTy;
949 }
950 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000951 } else if (OverloadedFunctionDecl *Ovl
952 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000953 // FIXME: We need an abstraction for iterating over one or more function
954 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000955 for (OverloadedFunctionDecl::function_iterator
956 Func = Ovl->function_begin(),
957 FuncEnd = Ovl->function_end();
958 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000959 CXXMethodDecl *DMethod = 0;
960 if (FunctionTemplateDecl *FunTmpl
961 = dyn_cast<FunctionTemplateDecl>(*Func))
962 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
963 else
964 DMethod = dyn_cast<CXXMethodDecl>(*Func);
965
966 if (DMethod && !DMethod->isStatic()) {
967 Ctx = DMethod->getDeclContext();
968 MemberType = Context.OverloadTy;
969 break;
970 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000971 }
972 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000973
974 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000975 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
976 QualType ThisType = Context.getTagDeclType(MD->getParent());
977 if ((Context.getCanonicalType(CtxType)
978 == Context.getCanonicalType(ThisType)) ||
979 IsDerivedFrom(ThisType, CtxType)) {
980 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000981 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000982 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +0000983 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000984 if (PerformObjectMemberConversion(This, D))
985 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +0000986 if (DiagnoseUseOfDecl(D, Loc))
987 return ExprError();
Douglas Gregor09be81b2009-02-04 17:27:36 +0000988 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +0000989 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000990 }
991 }
992 }
993 }
994
Douglas Gregor8acb7272008-12-11 16:49:14 +0000995 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000996 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
997 if (MD->isStatic())
998 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000999 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1000 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001001 }
1002
Douglas Gregor3257fb52008-12-22 05:46:06 +00001003 // Any other ways we could have found the field in a well-formed
1004 // program would have been turned into implicit member expressions
1005 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001006 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1007 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001008 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001009
Chris Lattner4b009652007-07-25 00:24:17 +00001010 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001011 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001012 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001013 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001014 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001015 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001016
Steve Naroffd6163f32008-09-05 22:11:13 +00001017 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001018 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001019 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1020 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001021 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001022 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1023 false, false, SS);
Steve Naroffd6163f32008-09-05 22:11:13 +00001024 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001025
Douglas Gregoraa57e862009-02-18 21:56:37 +00001026 // Check whether this declaration can be used. Note that we suppress
1027 // this check when we're going to perform argument-dependent lookup
1028 // on this function name, because this might not be the function
1029 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001030 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1031 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001032 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1033 return ExprError();
1034
Steve Naroffd6163f32008-09-05 22:11:13 +00001035 // Only create DeclRefExpr's for valid Decl's.
1036 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001037 return ExprError();
1038
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001039 // If the identifier reference is inside a block, and it refers to a value
1040 // that is outside the block, create a BlockDeclRefExpr instead of a
1041 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1042 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001043 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001044 // We do not do this for things like enum constants, global variables, etc,
1045 // as they do not get snapshotted.
1046 //
1047 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001048 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001049 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001050 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001051 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001052 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001053 // This is to record that a 'const' was actually synthesize and added.
1054 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001055 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001056
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001057 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001058 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1059 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001060 }
1061 // If this reference is not in a block or if the referenced variable is
1062 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001063
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001064 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001065 bool ValueDependent = false;
1066 if (getLangOptions().CPlusPlus) {
1067 // C++ [temp.dep.expr]p3:
1068 // An id-expression is type-dependent if it contains:
1069 // - an identifier that was declared with a dependent type,
1070 if (VD->getType()->isDependentType())
1071 TypeDependent = true;
1072 // - FIXME: a template-id that is dependent,
1073 // - a conversion-function-id that specifies a dependent type,
1074 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1075 Name.getCXXNameType()->isDependentType())
1076 TypeDependent = true;
1077 // - a nested-name-specifier that contains a class-name that
1078 // names a dependent type.
1079 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001080 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001081 DC; DC = DC->getParent()) {
1082 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001083 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001084 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1085 if (Context.getTypeDeclType(Record)->isDependentType()) {
1086 TypeDependent = true;
1087 break;
1088 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001089 }
1090 }
1091 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001092
Douglas Gregora5d84612008-12-10 20:57:37 +00001093 // C++ [temp.dep.constexpr]p2:
1094 //
1095 // An identifier is value-dependent if it is:
1096 // - a name declared with a dependent type,
1097 if (TypeDependent)
1098 ValueDependent = true;
1099 // - the name of a non-type template parameter,
1100 else if (isa<NonTypeTemplateParmDecl>(VD))
1101 ValueDependent = true;
1102 // - a constant with integral or enumeration type and is
1103 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001104 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1105 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1106 Dcl->getInit()) {
1107 ValueDependent = Dcl->getInit()->isValueDependent();
1108 }
1109 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001110 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001111
Anders Carlsson4571d812009-06-24 00:10:43 +00001112 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1113 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001114}
1115
Sebastian Redlcd883f72009-01-18 18:53:16 +00001116Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1117 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001118 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001119
Chris Lattner4b009652007-07-25 00:24:17 +00001120 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001121 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001122 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1123 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1124 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001125 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001126
Chris Lattner7e637512008-01-12 08:14:25 +00001127 // Pre-defined identifiers are of type char[x], where x is the length of the
1128 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001129 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001130 if (FunctionDecl *FD = getCurFunctionDecl())
1131 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001132 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1133 Length = MD->getSynthesizedMethodSize();
1134 else {
1135 Diag(Loc, diag::ext_predef_outside_function);
1136 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1137 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1138 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001139
1140
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001141 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001142 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001143 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001144 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001145}
1146
Sebastian Redlcd883f72009-01-18 18:53:16 +00001147Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001148 llvm::SmallString<16> CharBuffer;
1149 CharBuffer.resize(Tok.getLength());
1150 const char *ThisTokBegin = &CharBuffer[0];
1151 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001152
Chris Lattner4b009652007-07-25 00:24:17 +00001153 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1154 Tok.getLocation(), PP);
1155 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001156 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001157
1158 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1159
Sebastian Redl75324932009-01-20 22:23:13 +00001160 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1161 Literal.isWide(),
1162 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001163}
1164
Sebastian Redlcd883f72009-01-18 18:53:16 +00001165Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1166 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001167 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1168 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001169 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001170 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001171 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001172 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001173 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001174
Chris Lattner4b009652007-07-25 00:24:17 +00001175 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001176 // Add padding so that NumericLiteralParser can overread by one character.
1177 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001178 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001179
Chris Lattner4b009652007-07-25 00:24:17 +00001180 // Get the spelling of the token, which eliminates trigraphs, etc.
1181 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001182
Chris Lattner4b009652007-07-25 00:24:17 +00001183 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1184 Tok.getLocation(), PP);
1185 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001186 return ExprError();
1187
Chris Lattner1de66eb2007-08-26 03:42:43 +00001188 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001189
Chris Lattner1de66eb2007-08-26 03:42:43 +00001190 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001191 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001192 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001193 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001194 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001195 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001196 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001197 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001198
1199 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1200
Ted Kremenekddedbe22007-11-29 00:56:49 +00001201 // isExact will be set by GetFloatValue().
1202 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001203 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1204 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001205
Chris Lattner1de66eb2007-08-26 03:42:43 +00001206 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001207 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001208 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001209 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001210
Neil Booth7421e9c2007-08-29 22:00:19 +00001211 // long long is a C99 feature.
1212 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001213 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001214 Diag(Tok.getLocation(), diag::ext_longlong);
1215
Chris Lattner4b009652007-07-25 00:24:17 +00001216 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001217 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001218
Chris Lattner4b009652007-07-25 00:24:17 +00001219 if (Literal.GetIntegerValue(ResultVal)) {
1220 // If this value didn't fit into uintmax_t, warn and force to ull.
1221 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001222 Ty = Context.UnsignedLongLongTy;
1223 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001224 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001225 } else {
1226 // If this value fits into a ULL, try to figure out what else it fits into
1227 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001228
Chris Lattner4b009652007-07-25 00:24:17 +00001229 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1230 // be an unsigned int.
1231 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1232
1233 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001234 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001235 if (!Literal.isLong && !Literal.isLongLong) {
1236 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001237 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001238
Chris Lattner4b009652007-07-25 00:24:17 +00001239 // Does it fit in a unsigned int?
1240 if (ResultVal.isIntN(IntSize)) {
1241 // Does it fit in a signed int?
1242 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001243 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001244 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001245 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001246 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001247 }
Chris Lattner4b009652007-07-25 00:24:17 +00001248 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001249
Chris Lattner4b009652007-07-25 00:24:17 +00001250 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001251 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001252 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001253
Chris Lattner4b009652007-07-25 00:24:17 +00001254 // Does it fit in a unsigned long?
1255 if (ResultVal.isIntN(LongSize)) {
1256 // Does it fit in a signed long?
1257 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001258 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001259 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001260 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001261 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001262 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001263 }
1264
Chris Lattner4b009652007-07-25 00:24:17 +00001265 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001266 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001267 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001268
Chris Lattner4b009652007-07-25 00:24:17 +00001269 // Does it fit in a unsigned long long?
1270 if (ResultVal.isIntN(LongLongSize)) {
1271 // Does it fit in a signed long long?
1272 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001273 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001274 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001275 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001276 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001277 }
1278 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001279
Chris Lattner4b009652007-07-25 00:24:17 +00001280 // If we still couldn't decide a type, we probably have something that
1281 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001282 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001283 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001284 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001285 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001286 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001287
Chris Lattnere4068872008-05-09 05:59:00 +00001288 if (ResultVal.getBitWidth() != Width)
1289 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001290 }
Sebastian Redl75324932009-01-20 22:23:13 +00001291 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001292 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001293
Chris Lattner1de66eb2007-08-26 03:42:43 +00001294 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1295 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001296 Res = new (Context) ImaginaryLiteral(Res,
1297 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001298
1299 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001300}
1301
Sebastian Redlcd883f72009-01-18 18:53:16 +00001302Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1303 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001304 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001305 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001306 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001307}
1308
1309/// The UsualUnaryConversions() function is *not* called by this routine.
1310/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001311bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001312 SourceLocation OpLoc,
1313 const SourceRange &ExprRange,
1314 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001315 if (exprType->isDependentType())
1316 return false;
1317
Chris Lattner4b009652007-07-25 00:24:17 +00001318 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001319 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001320 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001321 if (isSizeof)
1322 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1323 return false;
1324 }
1325
Chris Lattner95933c12009-04-24 00:30:45 +00001326 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001327 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001328 Diag(OpLoc, diag::ext_sizeof_void_type)
1329 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001330 return false;
1331 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001332
Chris Lattner95933c12009-04-24 00:30:45 +00001333 if (RequireCompleteType(OpLoc, exprType,
1334 isSizeof ? diag::err_sizeof_incomplete_type :
1335 diag::err_alignof_incomplete_type,
1336 ExprRange))
1337 return true;
1338
1339 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001340 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001341 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001342 << exprType << isSizeof << ExprRange;
1343 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001344 }
1345
Chris Lattner95933c12009-04-24 00:30:45 +00001346 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001347}
1348
Chris Lattner8d9f7962009-01-24 20:17:12 +00001349bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1350 const SourceRange &ExprRange) {
1351 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001352
Chris Lattner8d9f7962009-01-24 20:17:12 +00001353 // alignof decl is always ok.
1354 if (isa<DeclRefExpr>(E))
1355 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001356
1357 // Cannot know anything else if the expression is dependent.
1358 if (E->isTypeDependent())
1359 return false;
1360
Douglas Gregor531434b2009-05-02 02:18:30 +00001361 if (E->getBitField()) {
1362 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1363 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001364 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001365
1366 // Alignment of a field access is always okay, so long as it isn't a
1367 // bit-field.
1368 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001369 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001370 return false;
1371
Chris Lattner8d9f7962009-01-24 20:17:12 +00001372 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1373}
1374
Douglas Gregor396f1142009-03-13 21:01:28 +00001375/// \brief Build a sizeof or alignof expression given a type operand.
1376Action::OwningExprResult
1377Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1378 bool isSizeOf, SourceRange R) {
1379 if (T.isNull())
1380 return ExprError();
1381
1382 if (!T->isDependentType() &&
1383 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1384 return ExprError();
1385
1386 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1387 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1388 Context.getSizeType(), OpLoc,
1389 R.getEnd()));
1390}
1391
1392/// \brief Build a sizeof or alignof expression given an expression
1393/// operand.
1394Action::OwningExprResult
1395Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1396 bool isSizeOf, SourceRange R) {
1397 // Verify that the operand is valid.
1398 bool isInvalid = false;
1399 if (E->isTypeDependent()) {
1400 // Delay type-checking for type-dependent expressions.
1401 } else if (!isSizeOf) {
1402 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001403 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001404 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1405 isInvalid = true;
1406 } else {
1407 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1408 }
1409
1410 if (isInvalid)
1411 return ExprError();
1412
1413 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1414 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1415 Context.getSizeType(), OpLoc,
1416 R.getEnd()));
1417}
1418
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001419/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1420/// the same for @c alignof and @c __alignof
1421/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001422Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001423Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1424 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001425 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001426 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001427
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001428 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001429 // FIXME: Preserve type source info.
1430 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001431 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1432 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001433
Douglas Gregor396f1142009-03-13 21:01:28 +00001434 // Get the end location.
1435 Expr *ArgEx = (Expr *)TyOrEx;
1436 Action::OwningExprResult Result
1437 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1438
1439 if (Result.isInvalid())
1440 DeleteExpr(ArgEx);
1441
1442 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001443}
1444
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001445QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001446 if (V->isTypeDependent())
1447 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001448
Chris Lattnera16e42d2007-08-26 05:39:26 +00001449 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001450 if (const ComplexType *CT = V->getType()->getAsComplexType())
1451 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001452
1453 // Otherwise they pass through real integer and floating point types here.
1454 if (V->getType()->isArithmeticType())
1455 return V->getType();
1456
1457 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001458 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1459 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001460 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001461}
1462
1463
Chris Lattner4b009652007-07-25 00:24:17 +00001464
Sebastian Redl8b769972009-01-19 00:08:26 +00001465Action::OwningExprResult
1466Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1467 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001468 // Since this might be a postfix expression, get rid of ParenListExprs.
1469 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001470 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001471
Chris Lattner4b009652007-07-25 00:24:17 +00001472 UnaryOperator::Opcode Opc;
1473 switch (Kind) {
1474 default: assert(0 && "Unknown unary op!");
1475 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1476 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1477 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001478
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001479 if (getLangOptions().CPlusPlus &&
1480 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1481 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001482 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001483 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1484
1485 // C++ [over.inc]p1:
1486 //
1487 // [...] If the function is a member function with one
1488 // parameter (which shall be of type int) or a non-member
1489 // function with two parameters (the second of which shall be
1490 // of type int), it defines the postfix increment operator ++
1491 // for objects of that type. When the postfix increment is
1492 // called as a result of using the ++ operator, the int
1493 // argument will have value zero.
1494 Expr *Args[2] = {
1495 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001496 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1497 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001498 };
1499
1500 // Build the candidate set for overloading
1501 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001502 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001503
1504 // Perform overload resolution.
1505 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001506 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001507 case OR_Success: {
1508 // We found a built-in operator or an overloaded operator.
1509 FunctionDecl *FnDecl = Best->Function;
1510
1511 if (FnDecl) {
1512 // We matched an overloaded operator. Build a call to that
1513 // operator.
1514
1515 // Convert the arguments.
1516 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1517 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001518 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001519 } else {
1520 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001521 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001522 FnDecl->getParamDecl(0)->getType(),
1523 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001524 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001525 }
1526
1527 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001528 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001529 = FnDecl->getType()->getAsFunctionType()->getResultType();
1530 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001531
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001532 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001533 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001534 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001535 UsualUnaryConversions(FnExpr);
1536
Sebastian Redl8b769972009-01-19 00:08:26 +00001537 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001538 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001539 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1540 Args, 2, ResultTy,
1541 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001542 } else {
1543 // We matched a built-in operator. Convert the arguments, then
1544 // break out so that we will build the appropriate built-in
1545 // operator node.
1546 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1547 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001548 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001549
1550 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001551 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001552 }
1553
1554 case OR_No_Viable_Function:
1555 // No viable function; fall through to handling this as a
1556 // built-in operator, which will produce an error message for us.
1557 break;
1558
1559 case OR_Ambiguous:
1560 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1561 << UnaryOperator::getOpcodeStr(Opc)
1562 << Arg->getSourceRange();
1563 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001564 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001565
1566 case OR_Deleted:
1567 Diag(OpLoc, diag::err_ovl_deleted_oper)
1568 << Best->Function->isDeleted()
1569 << UnaryOperator::getOpcodeStr(Opc)
1570 << Arg->getSourceRange();
1571 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1572 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001573 }
1574
1575 // Either we found no viable overloaded operator or we matched a
1576 // built-in operator. In either case, fall through to trying to
1577 // build a built-in operation.
1578 }
1579
Eli Friedman94d30952009-07-22 23:24:42 +00001580 Input.release();
1581 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001582 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001583}
1584
Sebastian Redl8b769972009-01-19 00:08:26 +00001585Action::OwningExprResult
1586Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1587 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001588 // Since this might be a postfix expression, get rid of ParenListExprs.
1589 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1590
Sebastian Redl8b769972009-01-19 00:08:26 +00001591 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1592 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001593
Douglas Gregor80723c52008-11-19 17:17:41 +00001594 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001595 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1596 Base.release();
1597 Idx.release();
1598 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1599 Context.DependentTy, RLoc));
1600 }
1601
1602 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001603 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001604 LHSExp->getType()->isEnumeralType() ||
1605 RHSExp->getType()->isRecordType() ||
1606 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001607 // Add the appropriate overloaded operators (C++ [over.match.oper])
1608 // to the candidate set.
1609 OverloadCandidateSet CandidateSet;
1610 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001611 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1612 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001613
Douglas Gregor80723c52008-11-19 17:17:41 +00001614 // Perform overload resolution.
1615 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001616 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001617 case OR_Success: {
1618 // We found a built-in operator or an overloaded operator.
1619 FunctionDecl *FnDecl = Best->Function;
1620
1621 if (FnDecl) {
1622 // We matched an overloaded operator. Build a call to that
1623 // operator.
1624
1625 // Convert the arguments.
1626 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1627 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1628 PerformCopyInitialization(RHSExp,
1629 FnDecl->getParamDecl(0)->getType(),
1630 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001631 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001632 } else {
1633 // Convert the arguments.
1634 if (PerformCopyInitialization(LHSExp,
1635 FnDecl->getParamDecl(0)->getType(),
1636 "passing") ||
1637 PerformCopyInitialization(RHSExp,
1638 FnDecl->getParamDecl(1)->getType(),
1639 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001640 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001641 }
1642
1643 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001644 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001645 = FnDecl->getType()->getAsFunctionType()->getResultType();
1646 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001647
Douglas Gregor80723c52008-11-19 17:17:41 +00001648 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001649 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1650 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001651 UsualUnaryConversions(FnExpr);
1652
Sebastian Redl8b769972009-01-19 00:08:26 +00001653 Base.release();
1654 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001655 Args[0] = LHSExp;
1656 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001657 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1658 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001659 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001660 } else {
1661 // We matched a built-in operator. Convert the arguments, then
1662 // break out so that we will build the appropriate built-in
1663 // operator node.
1664 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1665 "passing") ||
1666 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1667 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001668 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001669
1670 break;
1671 }
1672 }
1673
1674 case OR_No_Viable_Function:
1675 // No viable function; fall through to handling this as a
1676 // built-in operator, which will produce an error message for us.
1677 break;
1678
1679 case OR_Ambiguous:
1680 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1681 << "[]"
1682 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1683 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001684 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001685
1686 case OR_Deleted:
1687 Diag(LLoc, diag::err_ovl_deleted_oper)
1688 << Best->Function->isDeleted()
1689 << "[]"
1690 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1691 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1692 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001693 }
1694
1695 // Either we found no viable overloaded operator or we matched a
1696 // built-in operator. In either case, fall through to trying to
1697 // build a built-in operation.
1698 }
1699
Chris Lattner4b009652007-07-25 00:24:17 +00001700 // Perform default conversions.
1701 DefaultFunctionArrayConversion(LHSExp);
1702 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001703
Chris Lattner4b009652007-07-25 00:24:17 +00001704 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1705
1706 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001707 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001708 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001709 // and index from the expression types.
1710 Expr *BaseExpr, *IndexExpr;
1711 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001712 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1713 BaseExpr = LHSExp;
1714 IndexExpr = RHSExp;
1715 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001716 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001717 BaseExpr = LHSExp;
1718 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001719 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001720 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001721 // Handle the uncommon case of "123[Ptr]".
1722 BaseExpr = RHSExp;
1723 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001724 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001725 } else if (const ObjCObjectPointerType *PTy =
1726 LHSTy->getAsObjCObjectPointerType()) {
1727 BaseExpr = LHSExp;
1728 IndexExpr = RHSExp;
1729 ResultType = PTy->getPointeeType();
1730 } else if (const ObjCObjectPointerType *PTy =
1731 RHSTy->getAsObjCObjectPointerType()) {
1732 // Handle the uncommon case of "123[Ptr]".
1733 BaseExpr = RHSExp;
1734 IndexExpr = LHSExp;
1735 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001736 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1737 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001738 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001739
Chris Lattner4b009652007-07-25 00:24:17 +00001740 // FIXME: need to deal with const...
1741 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001742 } else if (LHSTy->isArrayType()) {
1743 // If we see an array that wasn't promoted by
1744 // DefaultFunctionArrayConversion, it must be an array that
1745 // wasn't promoted because of the C90 rule that doesn't
1746 // allow promoting non-lvalue arrays. Warn, then
1747 // force the promotion here.
1748 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1749 LHSExp->getSourceRange();
1750 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1751 LHSTy = LHSExp->getType();
1752
1753 BaseExpr = LHSExp;
1754 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001755 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001756 } else if (RHSTy->isArrayType()) {
1757 // Same as previous, except for 123[f().a] case
1758 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1759 RHSExp->getSourceRange();
1760 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1761 RHSTy = RHSExp->getType();
1762
1763 BaseExpr = RHSExp;
1764 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001765 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001766 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001767 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1768 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001769 }
Chris Lattner4b009652007-07-25 00:24:17 +00001770 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001771 if (!(IndexExpr->getType()->isIntegerType() &&
1772 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001773 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1774 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001775
Douglas Gregor05e28f62009-03-24 19:52:54 +00001776 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1777 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1778 // type. Note that Functions are not objects, and that (in C99 parlance)
1779 // incomplete types are not object types.
1780 if (ResultType->isFunctionType()) {
1781 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1782 << ResultType << BaseExpr->getSourceRange();
1783 return ExprError();
1784 }
Chris Lattner95933c12009-04-24 00:30:45 +00001785
Douglas Gregor05e28f62009-03-24 19:52:54 +00001786 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001787 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001788 BaseExpr->getSourceRange()))
1789 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001790
1791 // Diagnose bad cases where we step over interface counts.
1792 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1793 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1794 << ResultType << BaseExpr->getSourceRange();
1795 return ExprError();
1796 }
1797
Sebastian Redl8b769972009-01-19 00:08:26 +00001798 Base.release();
1799 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001800 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001801 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001802}
1803
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001804QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001805CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001806 const IdentifierInfo *CompName,
1807 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001808 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001809
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001810 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001811 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001812
Mike Stump9afab102009-02-19 03:04:26 +00001813 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001814 // special names that indicate a subset of exactly half the elements are
1815 // to be selected.
1816 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001817
Nate Begeman1486b502009-01-18 01:47:54 +00001818 // This flag determines whether or not CompName has an 's' char prefix,
1819 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001820 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001821
1822 // Check that we've found one of the special components, or that the component
1823 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001824 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001825 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1826 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001827 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001828 do
1829 compStr++;
1830 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001831 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001832 do
1833 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001834 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001835 }
Nate Begeman1486b502009-01-18 01:47:54 +00001836
Mike Stump9afab102009-02-19 03:04:26 +00001837 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001838 // We didn't get to the end of the string. This means the component names
1839 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001840 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1841 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001842 return QualType();
1843 }
Mike Stump9afab102009-02-19 03:04:26 +00001844
Nate Begeman1486b502009-01-18 01:47:54 +00001845 // Ensure no component accessor exceeds the width of the vector type it
1846 // operates on.
1847 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001848 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001849
1850 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001851 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001852
1853 while (*compStr) {
1854 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1855 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1856 << baseType << SourceRange(CompLoc);
1857 return QualType();
1858 }
1859 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001860 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001861
Nate Begeman1486b502009-01-18 01:47:54 +00001862 // If this is a halving swizzle, verify that the base type has an even
1863 // number of elements.
1864 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001865 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001866 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001867 return QualType();
1868 }
Mike Stump9afab102009-02-19 03:04:26 +00001869
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001870 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001871 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001872 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001873 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001874 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001875 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001876 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001877 if (HexSwizzle)
1878 CompSize--;
1879
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001880 if (CompSize == 1)
1881 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001882
Nate Begemanaf6ed502008-04-18 23:10:10 +00001883 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001884 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001885 // diagostics look bad. We want extended vector types to appear built-in.
1886 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1887 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1888 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001889 }
1890 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001891}
1892
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001893static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001894 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001895 const Selector &Sel,
1896 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001897
Anders Carlsson9935ab92009-08-26 18:25:21 +00001898 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001899 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001900 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001901 return OMD;
1902
1903 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1904 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001905 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1906 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001907 return D;
1908 }
1909 return 0;
1910}
1911
Steve Naroffc75c1a82009-06-17 22:40:22 +00001912static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001913 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001914 const Selector &Sel,
1915 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001916 // Check protocols on qualified interfaces.
1917 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001918 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001919 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001920 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001921 GDecl = PD;
1922 break;
1923 }
1924 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001925 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001926 GDecl = OMD;
1927 break;
1928 }
1929 }
1930 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001931 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001932 E = QIdTy->qual_end(); I != E; ++I) {
1933 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001934 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001935 if (GDecl)
1936 return GDecl;
1937 }
1938 }
1939 return GDecl;
1940}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001941
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001942/// FindMethodInNestedImplementations - Look up a method in current and
1943/// all base class implementations.
1944///
1945ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1946 const ObjCInterfaceDecl *IFace,
1947 const Selector &Sel) {
1948 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001949 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001950 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001951
1952 if (!Method && IFace->getSuperClass())
1953 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1954 return Method;
1955}
1956
Anders Carlsson9935ab92009-08-26 18:25:21 +00001957Action::OwningExprResult
1958Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001959 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001960 DeclarationName MemberName,
Douglas Gregorda61ad22009-08-06 03:17:00 +00001961 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001962 if (SS && SS->isInvalid())
1963 return ExprError();
1964
Nate Begemane85f43d2009-08-10 23:49:36 +00001965 // Since this might be a postfix expression, get rid of ParenListExprs.
1966 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1967
Anders Carlssonc154a722009-05-01 19:30:39 +00001968 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001969 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00001970
Steve Naroff137e11d2007-12-16 21:42:28 +00001971 // Perform default conversions.
1972 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001973
Steve Naroff2cb66382007-07-26 03:11:44 +00001974 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00001975 // If this is an Objective-C pseudo-builtin and a definition is provided then
1976 // use that.
1977 if (BaseType->isObjCIdType()) {
1978 // We have an 'id' type. Rather than fall through, we check if this
1979 // is a reference to 'isa'.
1980 if (BaseType != Context.ObjCIdRedefinitionType) {
1981 BaseType = Context.ObjCIdRedefinitionType;
1982 ImpCastExprToType(BaseExpr, BaseType);
1983 }
1984 } else if (BaseType->isObjCClassType() &&
1985 BaseType != Context.ObjCClassRedefinitionType) {
1986 BaseType = Context.ObjCClassRedefinitionType;
1987 ImpCastExprToType(BaseExpr, BaseType);
1988 }
Steve Naroff2cb66382007-07-26 03:11:44 +00001989 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001990
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001991 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1992 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001993 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00001994 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00001995 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
1996 BaseExpr, true,
1997 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001998 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00001999 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002000 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002001 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002002 else if (BaseType->isObjCObjectPointerType())
2003 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002004 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002005 return ExprError(Diag(MemberLoc,
2006 diag::err_typecheck_member_reference_arrow)
2007 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002008 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002009 if (BaseType->isDependentType()) {
2010 // Require that the base type isn't a pointer type
2011 // (so we'll report an error for)
2012 // T* t;
2013 // t.f;
2014 //
2015 // In Obj-C++, however, the above expression is valid, since it could be
2016 // accessing the 'f' property if T is an Obj-C interface. The extra check
2017 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002018 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002019
2020 if (!PT || (getLangOptions().ObjC1 &&
2021 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002022 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2023 BaseExpr, false,
2024 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002025 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002026 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002027 }
Chris Lattner4b009652007-07-25 00:24:17 +00002028 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002029
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002030 // Handle field access to simple records. This also handles access to fields
2031 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002032 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002033 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002034 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002035 diag::err_typecheck_incomplete_tag,
2036 BaseExpr->getSourceRange()))
2037 return ExprError();
2038
Douglas Gregorda61ad22009-08-06 03:17:00 +00002039 DeclContext *DC = RDecl;
2040 if (SS && SS->isSet()) {
2041 // If the member name was a qualified-id, look into the
2042 // nested-name-specifier.
2043 DC = computeDeclContext(*SS, false);
2044
2045 // FIXME: If DC is not computable, we should build a
2046 // CXXUnresolvedMemberExpr.
2047 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2048 }
2049
Steve Naroff2cb66382007-07-26 03:11:44 +00002050 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002051 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002052 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002053
Douglas Gregor12431cb2009-08-06 05:28:30 +00002054 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002055 QualType BaseTypeCanon
2056 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2057 QualType MemberTypeCanon
2058 = Context.getCanonicalType(
2059 Context.getTypeDeclType(
2060 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2061
2062 if (BaseTypeCanon != MemberTypeCanon &&
2063 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2064 return ExprError(Diag(SS->getBeginLoc(),
2065 diag::err_not_direct_base_or_virtual)
2066 << MemberTypeCanon << BaseTypeCanon);
2067 }
2068
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002069 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002070 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002071 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002072 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002073 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2074 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002075 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002076 }
2077
2078 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002079
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002080 // If the decl being referenced had an error, return an error for this
2081 // sub-expr without emitting another error, in order to avoid cascading
2082 // error cases.
2083 if (MemberDecl->isInvalidDecl())
2084 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002085
Douglas Gregoraa57e862009-02-18 21:56:37 +00002086 // Check the use of this field
2087 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2088 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002089
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002090 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002091 // We may have found a field within an anonymous union or struct
2092 // (C++ [class.union]).
2093 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002094 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002095 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002096
Douglas Gregor82d44772008-12-20 23:49:58 +00002097 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002098 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002099 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002100 MemberType = Ref->getPointeeType();
2101 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002102 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002103 unsigned combinedQualifiers =
2104 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002105 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002106 combinedQualifiers &= ~QualType::Const;
2107 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002108 if (BaseAddrSpace != MemberType.getAddressSpace())
2109 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002110 }
Eli Friedman76b49832008-02-06 22:48:16 +00002111
Douglas Gregorcad27f62009-06-22 23:06:13 +00002112 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002113 if (PerformObjectMemberConversion(BaseExpr, FD))
2114 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002115 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2116 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002117 }
2118
Douglas Gregorcad27f62009-06-22 23:06:13 +00002119 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2120 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Steve Naroff774e4152009-01-21 00:14:39 +00002121 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002122 Var, MemberLoc,
2123 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002124 }
2125 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2126 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002127 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002128 MemberFn, MemberLoc,
2129 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002130 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002131 if (FunctionTemplateDecl *FunTmpl
2132 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2133 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2134 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2135 FunTmpl, MemberLoc,
2136 Context.OverloadTy));
2137 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002138 if (OverloadedFunctionDecl *Ovl
2139 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002140 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002141 MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002142 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2143 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002144 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2145 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002146 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002147 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002148 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002149 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002150
Douglas Gregor82d44772008-12-20 23:49:58 +00002151 // We found a declaration kind that we didn't expect. This is a
2152 // generic error message that tells the user that she can't refer
2153 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002154 return ExprError(Diag(MemberLoc,
2155 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002156 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002157 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002158
Steve Naroff329ec222009-07-10 23:34:53 +00002159 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002160 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002161 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002162 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2163 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002164 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2165 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2166 ObjCMethodDecl *Getter;
2167 // FIXME: need to also look locally in the implementation.
2168 if ((Getter = IFace->lookupClassMethod(Sel))) {
2169 // Check the use of this method.
2170 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2171 return ExprError();
2172 }
2173 // If we found a getter then this may be a valid dot-reference, we
2174 // will look for the matching setter, in case it is needed.
2175 Selector SetterSel =
2176 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002177 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002178 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2179 if (!Setter) {
2180 // If this reference is in an @implementation, also check for 'private'
2181 // methods.
2182 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2183 }
2184 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002185 if (!Setter)
2186 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002187
2188 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2189 return ExprError();
2190
2191 if (Getter || Setter) {
2192 QualType PType;
2193
2194 if (Getter)
2195 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002196 else
2197 // Get the expression type from Setter's incoming parameter.
2198 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002199 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002200 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002201 Setter, MemberLoc, BaseExpr));
2202 }
2203 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002204 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002205 }
2206 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002207 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2208 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002209 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2210 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2211 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2212 const ObjCInterfaceType *IFaceT =
2213 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002214 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002215 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2216
Steve Naroff4e743962009-07-16 00:25:06 +00002217 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2218 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002219 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002220
2221 if (IV) {
2222 // If the decl being referenced had an error, return an error for this
2223 // sub-expr without emitting another error, in order to avoid cascading
2224 // error cases.
2225 if (IV->isInvalidDecl())
2226 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002227
Steve Naroff4e743962009-07-16 00:25:06 +00002228 // Check whether we can reference this field.
2229 if (DiagnoseUseOfDecl(IV, MemberLoc))
2230 return ExprError();
2231 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2232 IV->getAccessControl() != ObjCIvarDecl::Package) {
2233 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2234 if (ObjCMethodDecl *MD = getCurMethodDecl())
2235 ClassOfMethodDecl = MD->getClassInterface();
2236 else if (ObjCImpDecl && getCurFunctionDecl()) {
2237 // Case of a c-function declared inside an objc implementation.
2238 // FIXME: For a c-style function nested inside an objc implementation
2239 // class, there is no implementation context available, so we pass
2240 // down the context as argument to this routine. Ideally, this context
2241 // need be passed down in the AST node and somehow calculated from the
2242 // AST for a function decl.
2243 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2244 if (ObjCImplementationDecl *IMPD =
2245 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2246 ClassOfMethodDecl = IMPD->getClassInterface();
2247 else if (ObjCCategoryImplDecl* CatImplClass =
2248 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2249 ClassOfMethodDecl = CatImplClass->getClassInterface();
2250 }
2251
2252 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2253 if (ClassDeclared != IDecl ||
2254 ClassOfMethodDecl != ClassDeclared)
2255 Diag(MemberLoc, diag::error_private_ivar_access)
2256 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002257 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2258 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002259 Diag(MemberLoc, diag::error_protected_ivar_access)
2260 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002261 }
Steve Naroff4e743962009-07-16 00:25:06 +00002262
2263 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2264 MemberLoc, BaseExpr,
2265 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002266 }
Steve Naroff4e743962009-07-16 00:25:06 +00002267 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002268 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002269 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002270 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002271 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002272 // Handle properties on 'id' and qualified "id".
2273 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2274 BaseType->isObjCQualifiedIdType())) {
2275 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002276 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002277
Steve Naroff329ec222009-07-10 23:34:53 +00002278 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002279 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002280 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2281 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2282 // Check the use of this declaration
2283 if (DiagnoseUseOfDecl(PD, MemberLoc))
2284 return ExprError();
2285
2286 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2287 MemberLoc, BaseExpr));
2288 }
2289 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2290 // Check the use of this method.
2291 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2292 return ExprError();
2293
2294 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2295 OMD->getResultType(),
2296 OMD, OpLoc, MemberLoc,
2297 NULL, 0));
2298 }
2299 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002300
Steve Naroff329ec222009-07-10 23:34:53 +00002301 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002302 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002303 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002304 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2305 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002306 const ObjCObjectPointerType *OPT;
2307 if (OpKind == tok::period &&
2308 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2309 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2310 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002311 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002312
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002313 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002314 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002315 // Check whether we can reference this property.
2316 if (DiagnoseUseOfDecl(PD, MemberLoc))
2317 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002318 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002319 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002320 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002321 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2322 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002323 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002324 MemberLoc, BaseExpr));
2325 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002326 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002327 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2328 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002329 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002330 // Check whether we can reference this property.
2331 if (DiagnoseUseOfDecl(PD, MemberLoc))
2332 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002333
Steve Naroff774e4152009-01-21 00:14:39 +00002334 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002335 MemberLoc, BaseExpr));
2336 }
Steve Naroff329ec222009-07-10 23:34:53 +00002337 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2338 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002339 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002340 // Check whether we can reference this property.
2341 if (DiagnoseUseOfDecl(PD, MemberLoc))
2342 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002343
Steve Naroff329ec222009-07-10 23:34:53 +00002344 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2345 MemberLoc, BaseExpr));
2346 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002347 // If that failed, look for an "implicit" property by seeing if the nullary
2348 // selector is implemented.
2349
2350 // FIXME: The logic for looking up nullary and unary selectors should be
2351 // shared with the code in ActOnInstanceMessage.
2352
Anders Carlsson9935ab92009-08-26 18:25:21 +00002353 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002354 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002355
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002356 // If this reference is in an @implementation, check for 'private' methods.
2357 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002358 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002359
Steve Naroff04151f32008-10-22 19:16:27 +00002360 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002361 if (!Getter)
2362 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002363 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002364 // Check if we can reference this property.
2365 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2366 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002367 }
2368 // If we found a getter then this may be a valid dot-reference, we
2369 // will look for the matching setter, in case it is needed.
2370 Selector SetterSel =
2371 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002372 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002373 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002374 if (!Setter) {
2375 // If this reference is in an @implementation, also check for 'private'
2376 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002377 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002378 }
2379 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002380 if (!Setter)
2381 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002382
Steve Naroffdede0c92009-03-11 13:48:17 +00002383 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2384 return ExprError();
2385
2386 if (Getter || Setter) {
2387 QualType PType;
2388
2389 if (Getter)
2390 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002391 else
2392 // Get the expression type from Setter's incoming parameter.
2393 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002394 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002395 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002396 Setter, MemberLoc, BaseExpr));
2397 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002398 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002399 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002400 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002401
Steve Naroff29d293b2009-07-24 17:54:45 +00002402 // Handle the following exceptional case (*Obj).isa.
2403 if (OpKind == tok::period &&
2404 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002405 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002406 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2407 Context.getObjCIdType()));
2408
Chris Lattnera57cf472008-07-21 04:28:12 +00002409 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002410 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002411 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002412 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2413 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002414 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002415 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002416 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002417 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002418
Douglas Gregor762da552009-03-27 06:00:30 +00002419 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2420 << BaseType << BaseExpr->getSourceRange();
2421
2422 // If the user is trying to apply -> or . to a function or function
2423 // pointer, it's probably because they forgot parentheses to call
2424 // the function. Suggest the addition of those parentheses.
2425 if (BaseType == Context.OverloadTy ||
2426 BaseType->isFunctionType() ||
2427 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002428 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002429 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2430 Diag(Loc, diag::note_member_reference_needs_call)
2431 << CodeModificationHint::CreateInsertion(Loc, "()");
2432 }
2433
2434 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002435}
2436
Anders Carlsson9935ab92009-08-26 18:25:21 +00002437Action::OwningExprResult
2438Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2439 tok::TokenKind OpKind, SourceLocation MemberLoc,
2440 IdentifierInfo &Member,
2441 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2442 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2443 DeclarationName(&Member), ObjCImpDecl, SS);
2444}
2445
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002446Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2447 FunctionDecl *FD,
2448 ParmVarDecl *Param) {
2449 if (Param->hasUnparsedDefaultArg()) {
2450 Diag (CallLoc,
2451 diag::err_use_of_default_argument_to_function_declared_later) <<
2452 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2453 Diag(UnparsedDefaultArgLocs[Param],
2454 diag::note_default_argument_declared_here);
2455 } else {
2456 if (Param->hasUninstantiatedDefaultArg()) {
2457 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2458
2459 // Instantiate the expression.
2460 const TemplateArgumentList &ArgList = getTemplateInstantiationArgs(FD);
2461
2462 // FIXME: We should really make a new InstantiatingTemplate ctor
2463 // that has a better message - right now we're just piggy-backing
2464 // off the "default template argument" error message.
2465 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
2466 ArgList.getFlatArgumentList(),
2467 ArgList.flat_size());
2468
John McCall0ba26ee2009-08-25 22:02:44 +00002469 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002470 if (Result.isInvalid())
2471 return ExprError();
2472
2473 if (SetParamDefaultArgument(Param, move(Result),
2474 /*FIXME:EqualLoc*/
2475 UninstExpr->getSourceRange().getBegin()))
2476 return ExprError();
2477 }
2478
2479 Expr *DefaultExpr = Param->getDefaultArg();
2480
2481 // If the default expression creates temporaries, we need to
2482 // push them to the current stack of expression temporaries so they'll
2483 // be properly destroyed.
2484 if (CXXExprWithTemporaries *E
2485 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2486 assert(!E->shouldDestroyTemporaries() &&
2487 "Can't destroy temporaries in a default argument expr!");
2488 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2489 ExprTemporaries.push_back(E->getTemporary(I));
2490 }
2491 }
2492
2493 // We already type-checked the argument, so we know it works.
2494 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2495}
2496
Douglas Gregor3257fb52008-12-22 05:46:06 +00002497/// ConvertArgumentsForCall - Converts the arguments specified in
2498/// Args/NumArgs to the parameter types of the function FDecl with
2499/// function prototype Proto. Call is the call expression itself, and
2500/// Fn is the function expression. For a C++ member function, this
2501/// routine does not attempt to convert the object argument. Returns
2502/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002503bool
2504Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002505 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002506 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002507 Expr **Args, unsigned NumArgs,
2508 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002509 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002510 // assignment, to the types of the corresponding parameter, ...
2511 unsigned NumArgsInProto = Proto->getNumArgs();
2512 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002513 bool Invalid = false;
2514
Douglas Gregor3257fb52008-12-22 05:46:06 +00002515 // If too few arguments are available (and we don't have default
2516 // arguments for the remaining parameters), don't make the call.
2517 if (NumArgs < NumArgsInProto) {
2518 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2519 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2520 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2521 // Use default arguments for missing arguments
2522 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002523 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002524 }
2525
2526 // If too many are passed and not variadic, error on the extras and drop
2527 // them.
2528 if (NumArgs > NumArgsInProto) {
2529 if (!Proto->isVariadic()) {
2530 Diag(Args[NumArgsInProto]->getLocStart(),
2531 diag::err_typecheck_call_too_many_args)
2532 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2533 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2534 Args[NumArgs-1]->getLocEnd());
2535 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002536 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002537 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002538 }
2539 NumArgsToCheck = NumArgsInProto;
2540 }
Mike Stump9afab102009-02-19 03:04:26 +00002541
Douglas Gregor3257fb52008-12-22 05:46:06 +00002542 // Continue to check argument types (even if we have too few/many args).
2543 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2544 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002545
Douglas Gregor3257fb52008-12-22 05:46:06 +00002546 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002547 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002548 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002549
Eli Friedman83dec9e2009-03-22 22:00:50 +00002550 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2551 ProtoArgType,
2552 diag::err_call_incomplete_argument,
2553 Arg->getSourceRange()))
2554 return true;
2555
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002556 // Pass the argument.
2557 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2558 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002559 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002560 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002561
2562 OwningExprResult ArgExpr =
2563 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2564 FDecl, Param);
2565 if (ArgExpr.isInvalid())
2566 return true;
2567
2568 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002569 }
2570
Douglas Gregor3257fb52008-12-22 05:46:06 +00002571 Call->setArg(i, Arg);
2572 }
Mike Stump9afab102009-02-19 03:04:26 +00002573
Douglas Gregor3257fb52008-12-22 05:46:06 +00002574 // If this is a variadic call, handle args passed through "...".
2575 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002576 VariadicCallType CallType = VariadicFunction;
2577 if (Fn->getType()->isBlockPointerType())
2578 CallType = VariadicBlock; // Block
2579 else if (isa<MemberExpr>(Fn))
2580 CallType = VariadicMethod;
2581
Douglas Gregor3257fb52008-12-22 05:46:06 +00002582 // Promote the arguments (C99 6.5.2.2p7).
2583 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2584 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002585 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002586 Call->setArg(i, Arg);
2587 }
2588 }
2589
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002590 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002591}
2592
Steve Naroff87d58b42007-09-16 03:34:24 +00002593/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002594/// This provides the location of the left/right parens and a list of comma
2595/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002596Action::OwningExprResult
2597Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2598 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002599 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002600 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002601
2602 // Since this might be a postfix expression, get rid of ParenListExprs.
2603 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2604
Anders Carlssonc154a722009-05-01 19:30:39 +00002605 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002606 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002607 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002608 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002609 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002610 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002611
Douglas Gregor3257fb52008-12-22 05:46:06 +00002612 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002613 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002614 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002615 // FIXME: Will need to cache the results of name lookup (including ADL) in
2616 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002617 bool Dependent = false;
2618 if (Fn->isTypeDependent())
2619 Dependent = true;
2620 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2621 Dependent = true;
2622
2623 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002624 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002625 Context.DependentTy, RParenLoc));
2626
2627 // Determine whether this is a call to an object (C++ [over.call.object]).
2628 if (Fn->getType()->isRecordType())
2629 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2630 CommaLocs, RParenLoc));
2631
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002632 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002633 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2634 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2635 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2636 isa<CXXMethodDecl>(MemDecl) ||
2637 (isa<FunctionTemplateDecl>(MemDecl) &&
2638 isa<CXXMethodDecl>(
2639 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002640 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2641 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002642 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002643 }
2644
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002645 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002646 // Also, in C++, keep track of whether we should perform argument-dependent
2647 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002648 Expr *FnExpr = Fn;
2649 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002650 bool HasExplicitTemplateArgs = 0;
2651 const TemplateArgument *ExplicitTemplateArgs = 0;
2652 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002653 while (true) {
2654 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2655 FnExpr = IcExpr->getSubExpr();
2656 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002657 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002658 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002659 ADL = false;
2660 FnExpr = PExpr->getSubExpr();
2661 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002662 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002663 == UnaryOperator::AddrOf) {
2664 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002665 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002666 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2667 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002668 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002669 break;
Mike Stump9afab102009-02-19 03:04:26 +00002670 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002671 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2672 UnqualifiedName = DepName->getName();
2673 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002674 } else if (TemplateIdRefExpr *TemplateIdRef
2675 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2676 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002677 if (!NDecl)
2678 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002679 HasExplicitTemplateArgs = true;
2680 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2681 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2682
2683 // C++ [temp.arg.explicit]p6:
2684 // [Note: For simple function names, argument dependent lookup (3.4.2)
2685 // applies even when the function name is not visible within the
2686 // scope of the call. This is because the call still has the syntactic
2687 // form of a function call (3.4.1). But when a function template with
2688 // explicit template arguments is used, the call does not have the
2689 // correct syntactic form unless there is a function template with
2690 // that name visible at the point of the call. If no such name is
2691 // visible, the call is not syntactically well-formed and
2692 // argument-dependent lookup does not apply. If some such name is
2693 // visible, argument dependent lookup applies and additional function
2694 // templates may be found in other namespaces.
2695 //
2696 // The summary of this paragraph is that, if we get to this point and the
2697 // template-id was not a qualified name, then argument-dependent lookup
2698 // is still possible.
2699 if (TemplateIdRef->getQualifier())
2700 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002701 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002702 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002703 // Any kind of name that does not refer to a declaration (or
2704 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2705 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002706 break;
2707 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002708 }
Mike Stump9afab102009-02-19 03:04:26 +00002709
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002710 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002711 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002712 if (NDecl) {
2713 FDecl = dyn_cast<FunctionDecl>(NDecl);
2714 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002715 FDecl = FunctionTemplate->getTemplatedDecl();
2716 else
Douglas Gregor28857752009-06-30 22:34:41 +00002717 FDecl = dyn_cast<FunctionDecl>(NDecl);
2718 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002719 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002720
Douglas Gregorb60eb752009-06-25 22:08:12 +00002721 if (Ovl || FunctionTemplate ||
2722 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002723 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002724 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002725 ADL = false;
2726
Douglas Gregorfcb19192009-02-11 23:02:49 +00002727 // We don't perform ADL in C.
2728 if (!getLangOptions().CPlusPlus)
2729 ADL = false;
2730
Douglas Gregorb60eb752009-06-25 22:08:12 +00002731 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002732 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2733 HasExplicitTemplateArgs,
2734 ExplicitTemplateArgs,
2735 NumExplicitTemplateArgs,
2736 LParenLoc, Args, NumArgs, CommaLocs,
2737 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002738 if (!FDecl)
2739 return ExprError();
2740
2741 // Update Fn to refer to the actual function selected.
2742 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002743 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002744 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002745 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2746 QDRExpr->getLocation(),
2747 false, false,
2748 QDRExpr->getQualifierRange(),
2749 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002750 else
Mike Stump9afab102009-02-19 03:04:26 +00002751 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002752 Fn->getSourceRange().getBegin());
2753 Fn->Destroy(Context);
2754 Fn = NewFn;
2755 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002756 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002757
2758 // Promote the function operand.
2759 UsualUnaryConversions(Fn);
2760
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002761 // Make the call expr early, before semantic checks. This guarantees cleanup
2762 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002763 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2764 Args, NumArgs,
2765 Context.BoolTy,
2766 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002767
Steve Naroffd6163f32008-09-05 22:11:13 +00002768 const FunctionType *FuncT;
2769 if (!Fn->getType()->isBlockPointerType()) {
2770 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2771 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002772 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002773 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002774 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2775 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002776 FuncT = PT->getPointeeType()->getAsFunctionType();
2777 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002778 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002779 getAsFunctionType();
2780 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002781 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002782 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2783 << Fn->getType() << Fn->getSourceRange());
2784
Eli Friedman83dec9e2009-03-22 22:00:50 +00002785 // Check for a valid return type
2786 if (!FuncT->getResultType()->isVoidType() &&
2787 RequireCompleteType(Fn->getSourceRange().getBegin(),
2788 FuncT->getResultType(),
2789 diag::err_call_incomplete_return,
2790 TheCall->getSourceRange()))
2791 return ExprError();
2792
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002793 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002794 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002795
Douglas Gregor4fa58902009-02-26 23:50:07 +00002796 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002797 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002798 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002799 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002800 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002801 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002802
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002803 if (FDecl) {
2804 // Check if we have too few/too many template arguments, based
2805 // on our knowledge of the function definition.
2806 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002807 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002808 const FunctionProtoType *Proto =
2809 Def->getType()->getAsFunctionProtoType();
2810 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2811 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2812 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2813 }
2814 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002815 }
2816
Steve Naroffdb65e052007-08-28 23:30:39 +00002817 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002818 for (unsigned i = 0; i != NumArgs; i++) {
2819 Expr *Arg = Args[i];
2820 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002821 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2822 Arg->getType(),
2823 diag::err_call_incomplete_argument,
2824 Arg->getSourceRange()))
2825 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002826 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002827 }
Chris Lattner4b009652007-07-25 00:24:17 +00002828 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002829
Douglas Gregor3257fb52008-12-22 05:46:06 +00002830 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2831 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002832 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2833 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002834
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002835 // Check for sentinels
2836 if (NDecl)
2837 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002838
Chris Lattner2e64c072007-08-10 20:18:51 +00002839 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002840 if (FDecl) {
2841 if (CheckFunctionCall(FDecl, TheCall.get()))
2842 return ExprError();
2843
2844 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2845 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2846 } else if (NDecl) {
2847 if (CheckBlockCall(NDecl, TheCall.get()))
2848 return ExprError();
2849 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002850
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002851 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002852}
2853
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002854Action::OwningExprResult
2855Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2856 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002857 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002858 //FIXME: Preserve type source info.
2859 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002860 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002861 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002862 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002863
Eli Friedman8c2173d2008-05-20 05:22:08 +00002864 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002865 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002866 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2867 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002868 } else if (!literalType->isDependentType() &&
2869 RequireCompleteType(LParenLoc, literalType,
2870 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002871 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002872 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002873
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002874 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002875 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002876 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002877
Chris Lattnere5cb5862008-12-04 23:50:19 +00002878 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002879 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002880 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002881 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002882 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002883 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002884 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002885 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002886}
2887
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002888Action::OwningExprResult
2889Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002890 SourceLocation RBraceLoc) {
2891 unsigned NumInit = initlist.size();
2892 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002893
Steve Naroff0acc9c92007-09-15 18:49:24 +00002894 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002895 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002896
Mike Stump9afab102009-02-19 03:04:26 +00002897 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002898 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002899 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002900 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002901}
2902
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002903/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002904bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Anders Carlsson9583fa72009-08-07 22:21:05 +00002905 CastExpr::CastKind& Kind, bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002906 if (getLangOptions().CPlusPlus)
Anders Carlsson9583fa72009-08-07 22:21:05 +00002907 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002908
Eli Friedman01e0f652009-08-15 19:02:19 +00002909 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002910
2911 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2912 // type needs to be scalar.
2913 if (castType->isVoidType()) {
2914 // Cast to void allows any expr type.
2915 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002916 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2917 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2918 (castType->isStructureType() || castType->isUnionType())) {
2919 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002920 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002921 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2922 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002923 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002924 } else if (castType->isUnionType()) {
2925 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002926 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002927 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002928 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002929 Field != FieldEnd; ++Field) {
2930 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2931 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2932 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2933 << castExpr->getSourceRange();
2934 break;
2935 }
2936 }
2937 if (Field == FieldEnd)
2938 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2939 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002940 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002941 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002942 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002943 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002944 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002945 }
Mike Stump9afab102009-02-19 03:04:26 +00002946 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002947 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002948 return Diag(castExpr->getLocStart(),
2949 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002950 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00002951 } else if (castType->isExtVectorType()) {
2952 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002953 return true;
2954 } else if (castType->isVectorType()) {
2955 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2956 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00002957 } else if (castExpr->getType()->isVectorType()) {
2958 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2959 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002960 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002961 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002962 } else if (!castType->isArithmeticType()) {
2963 QualType castExprType = castExpr->getType();
2964 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2965 return Diag(castExpr->getLocStart(),
2966 diag::err_cast_pointer_from_non_pointer_int)
2967 << castExprType << castExpr->getSourceRange();
2968 } else if (!castExpr->getType()->isArithmeticType()) {
2969 if (!castType->isIntegralType() && castType->isArithmeticType())
2970 return Diag(castExpr->getLocStart(),
2971 diag::err_cast_pointer_to_non_pointer_int)
2972 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002973 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00002974 if (isa<ObjCSelectorExpr>(castExpr))
2975 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002976 return false;
2977}
2978
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002979bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002980 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002981
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002982 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002983 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002984 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002985 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002986 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002987 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002988 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002989 } else
2990 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002991 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002992 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002993
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002994 return false;
2995}
2996
Nate Begemanbd42e022009-06-26 00:50:28 +00002997bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
2998 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
2999
Nate Begeman9e063702009-06-27 22:05:55 +00003000 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3001 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003002 if (SrcTy->isVectorType()) {
3003 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3004 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3005 << DestTy << SrcTy << R;
3006 return false;
3007 }
3008
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003009 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003010 // conversion will take place first from scalar to elt type, and then
3011 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003012 if (SrcTy->isPointerType())
3013 return Diag(R.getBegin(),
3014 diag::err_invalid_conversion_between_vector_and_scalar)
3015 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003016 return false;
3017}
3018
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003019Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003020Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003021 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003022 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3023
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003024 assert((Ty != 0) && (Op.get() != 0) &&
3025 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003026
Nate Begemane85f43d2009-08-10 23:49:36 +00003027 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003028 //FIXME: Preserve type source info.
3029 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003030
3031 // If the Expr being casted is a ParenListExpr, handle it specially.
3032 if (isa<ParenListExpr>(castExpr))
3033 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Chris Lattner4b009652007-07-25 00:24:17 +00003034
Anders Carlsson9583fa72009-08-07 22:21:05 +00003035 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3036 Kind))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003037 return ExprError();
Nate Begemane85f43d2009-08-10 23:49:36 +00003038
3039 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003040 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003041 Kind, castExpr, castType,
3042 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003043}
3044
Nate Begemane85f43d2009-08-10 23:49:36 +00003045/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3046/// of comma binary operators.
3047Action::OwningExprResult
3048Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3049 Expr *expr = EA.takeAs<Expr>();
3050 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3051 if (!E)
3052 return Owned(expr);
3053
3054 OwningExprResult Result(*this, E->getExpr(0));
3055
3056 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3057 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3058 Owned(E->getExpr(i)));
3059
3060 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3061}
3062
3063Action::OwningExprResult
3064Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3065 SourceLocation RParenLoc, ExprArg Op,
3066 QualType Ty) {
3067 ParenListExpr *PE = (ParenListExpr *)Op.get();
3068
3069 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3070 // then handle it as such.
3071 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3072 if (PE->getNumExprs() == 0) {
3073 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3074 return ExprError();
3075 }
3076
3077 llvm::SmallVector<Expr *, 8> initExprs;
3078 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3079 initExprs.push_back(PE->getExpr(i));
3080
3081 // FIXME: This means that pretty-printing the final AST will produce curly
3082 // braces instead of the original commas.
3083 Op.release();
3084 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3085 initExprs.size(), RParenLoc);
3086 E->setType(Ty);
3087 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3088 Owned(E));
3089 } else {
3090 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3091 // sequence of BinOp comma operators.
3092 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3093 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3094 }
3095}
3096
3097Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3098 SourceLocation R,
3099 MultiExprArg Val) {
3100 unsigned nexprs = Val.size();
3101 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3102 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3103 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3104 return Owned(expr);
3105}
3106
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003107/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3108/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003109/// C99 6.5.15
3110QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3111 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003112 // C++ is sufficiently different to merit its own checker.
3113 if (getLangOptions().CPlusPlus)
3114 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3115
Chris Lattnere2897262009-02-18 04:28:32 +00003116 UsualUnaryConversions(Cond);
3117 UsualUnaryConversions(LHS);
3118 UsualUnaryConversions(RHS);
3119 QualType CondTy = Cond->getType();
3120 QualType LHSTy = LHS->getType();
3121 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003122
3123 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003124 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3125 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3126 << CondTy;
3127 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003128 }
Mike Stump9afab102009-02-19 03:04:26 +00003129
Chris Lattner992ae932008-01-06 22:42:25 +00003130 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003131 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3132 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003133
Chris Lattner992ae932008-01-06 22:42:25 +00003134 // If both operands have arithmetic type, do the usual arithmetic conversions
3135 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003136 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3137 UsualArithmeticConversions(LHS, RHS);
3138 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003139 }
Mike Stump9afab102009-02-19 03:04:26 +00003140
Chris Lattner992ae932008-01-06 22:42:25 +00003141 // If both operands are the same structure or union type, the result is that
3142 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003143 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3144 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003145 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003146 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003147 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003148 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003149 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003150 }
Mike Stump9afab102009-02-19 03:04:26 +00003151
Chris Lattner992ae932008-01-06 22:42:25 +00003152 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003153 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003154 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3155 if (!LHSTy->isVoidType())
3156 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3157 << RHS->getSourceRange();
3158 if (!RHSTy->isVoidType())
3159 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3160 << LHS->getSourceRange();
3161 ImpCastExprToType(LHS, Context.VoidTy);
3162 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003163 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003164 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003165 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3166 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003167 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003168 RHS->isNullPointerConstant(Context)) {
3169 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3170 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003171 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003172 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003173 LHS->isNullPointerConstant(Context)) {
3174 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3175 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003176 }
David Chisnall44663db2009-08-17 16:35:33 +00003177 // Handle things like Class and struct objc_class*. Here we case the result
3178 // to the pseudo-builtin, because that will be implicitly cast back to the
3179 // redefinition type if an attempt is made to access its fields.
3180 if (LHSTy->isObjCClassType() &&
3181 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3182 ImpCastExprToType(RHS, LHSTy);
3183 return LHSTy;
3184 }
3185 if (RHSTy->isObjCClassType() &&
3186 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3187 ImpCastExprToType(LHS, RHSTy);
3188 return RHSTy;
3189 }
3190 // And the same for struct objc_object* / id
3191 if (LHSTy->isObjCIdType() &&
3192 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3193 ImpCastExprToType(RHS, LHSTy);
3194 return LHSTy;
3195 }
3196 if (RHSTy->isObjCIdType() &&
3197 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3198 ImpCastExprToType(LHS, RHSTy);
3199 return RHSTy;
3200 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003201 // Handle block pointer types.
3202 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3203 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3204 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3205 QualType destType = Context.getPointerType(Context.VoidTy);
3206 ImpCastExprToType(LHS, destType);
3207 ImpCastExprToType(RHS, destType);
3208 return destType;
3209 }
3210 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3211 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3212 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003213 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003214 // We have 2 block pointer types.
3215 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3216 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003217 return LHSTy;
3218 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003219 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003220 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3221 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003222
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003223 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3224 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003225 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3226 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3227 // In this situation, we assume void* type. No especially good
3228 // reason, but this is what gcc does, and we do have to pick
3229 // to get a consistent AST.
3230 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3231 ImpCastExprToType(LHS, incompatTy);
3232 ImpCastExprToType(RHS, incompatTy);
3233 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003234 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003235 // The block pointer types are compatible.
3236 ImpCastExprToType(LHS, LHSTy);
3237 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003238 return LHSTy;
3239 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003240 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003241 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003242
3243 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3244 // Two identical object pointer types are always compatible.
3245 return LHSTy;
3246 }
Steve Naroff329ec222009-07-10 23:34:53 +00003247 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3248 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003249 QualType compositeType = LHSTy;
3250
3251 // If both operands are interfaces and either operand can be
3252 // assigned to the other, use that type as the composite
3253 // type. This allows
3254 // xxx ? (A*) a : (B*) b
3255 // where B is a subclass of A.
3256 //
3257 // Additionally, as for assignment, if either type is 'id'
3258 // allow silent coercion. Finally, if the types are
3259 // incompatible then make sure to use 'id' as the composite
3260 // type so the result is acceptable for sending messages to.
3261
3262 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3263 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003264 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003265 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003266 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003267 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003268 } else if ((LHSTy->isObjCQualifiedIdType() ||
3269 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003270 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003271 // Need to handle "id<xx>" explicitly.
3272 // GCC allows qualified id and any Objective-C type to devolve to
3273 // id. Currently localizing to here until clear this should be
3274 // part of ObjCQualifiedIdTypesAreCompatible.
3275 compositeType = Context.getObjCIdType();
3276 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003277 compositeType = Context.getObjCIdType();
3278 } else {
3279 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3280 << LHSTy << RHSTy
3281 << LHS->getSourceRange() << RHS->getSourceRange();
3282 QualType incompatTy = Context.getObjCIdType();
3283 ImpCastExprToType(LHS, incompatTy);
3284 ImpCastExprToType(RHS, incompatTy);
3285 return incompatTy;
3286 }
3287 // The object pointer types are compatible.
3288 ImpCastExprToType(LHS, compositeType);
3289 ImpCastExprToType(RHS, compositeType);
3290 return compositeType;
3291 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003292 // Check Objective-C object pointer types and 'void *'
3293 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003294 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003295 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3296 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3297 QualType destType = Context.getPointerType(destPointee);
3298 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3299 ImpCastExprToType(RHS, destType); // promote to void*
3300 return destType;
3301 }
3302 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3303 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003304 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003305 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3306 QualType destType = Context.getPointerType(destPointee);
3307 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3308 ImpCastExprToType(LHS, destType); // promote to void*
3309 return destType;
3310 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003311 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3312 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3313 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003314 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3315 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003316
3317 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3318 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3319 // Figure out necessary qualifiers (C99 6.5.15p6)
3320 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3321 QualType destType = Context.getPointerType(destPointee);
3322 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3323 ImpCastExprToType(RHS, destType); // promote to void*
3324 return destType;
3325 }
3326 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3327 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3328 QualType destType = Context.getPointerType(destPointee);
3329 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3330 ImpCastExprToType(RHS, destType); // promote to void*
3331 return destType;
3332 }
3333
3334 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3335 // Two identical pointer types are always compatible.
3336 return LHSTy;
3337 }
3338 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3339 rhptee.getUnqualifiedType())) {
3340 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3341 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3342 // In this situation, we assume void* type. No especially good
3343 // reason, but this is what gcc does, and we do have to pick
3344 // to get a consistent AST.
3345 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3346 ImpCastExprToType(LHS, incompatTy);
3347 ImpCastExprToType(RHS, incompatTy);
3348 return incompatTy;
3349 }
3350 // The pointer types are compatible.
3351 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3352 // differently qualified versions of compatible types, the result type is
3353 // a pointer to an appropriately qualified version of the *composite*
3354 // type.
3355 // FIXME: Need to calculate the composite type.
3356 // FIXME: Need to add qualifiers
3357 ImpCastExprToType(LHS, LHSTy);
3358 ImpCastExprToType(RHS, LHSTy);
3359 return LHSTy;
3360 }
3361
3362 // GCC compatibility: soften pointer/integer mismatch.
3363 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3364 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3365 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3366 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3367 return RHSTy;
3368 }
3369 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3370 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3371 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3372 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3373 return LHSTy;
3374 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003375
Chris Lattner992ae932008-01-06 22:42:25 +00003376 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003377 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3378 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003379 return QualType();
3380}
3381
Steve Naroff87d58b42007-09-16 03:34:24 +00003382/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003383/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003384Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3385 SourceLocation ColonLoc,
3386 ExprArg Cond, ExprArg LHS,
3387 ExprArg RHS) {
3388 Expr *CondExpr = (Expr *) Cond.get();
3389 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003390
3391 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3392 // was the condition.
3393 bool isLHSNull = LHSExpr == 0;
3394 if (isLHSNull)
3395 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003396
3397 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003398 RHSExpr, QuestionLoc);
3399 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003400 return ExprError();
3401
3402 Cond.release();
3403 LHS.release();
3404 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003405 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003406 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003407 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003408}
3409
Chris Lattner4b009652007-07-25 00:24:17 +00003410// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003411// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003412// routine is it effectively iqnores the qualifiers on the top level pointee.
3413// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3414// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003415Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003416Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3417 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003418
David Chisnall44663db2009-08-17 16:35:33 +00003419 if ((lhsType->isObjCClassType() &&
3420 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3421 (rhsType->isObjCClassType() &&
3422 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3423 return Compatible;
3424 }
3425
Chris Lattner4b009652007-07-25 00:24:17 +00003426 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003427 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3428 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003429
Chris Lattner4b009652007-07-25 00:24:17 +00003430 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003431 lhptee = Context.getCanonicalType(lhptee);
3432 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003433
Chris Lattner005ed752008-01-04 18:04:52 +00003434 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003435
3436 // C99 6.5.16.1p1: This following citation is common to constraints
3437 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3438 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003439 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003440 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003441 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003442
Mike Stump9afab102009-02-19 03:04:26 +00003443 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3444 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003445 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003446 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003447 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003448 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003449
Chris Lattner4ca3d772008-01-03 22:56:36 +00003450 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003451 assert(rhptee->isFunctionType());
3452 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003453 }
Mike Stump9afab102009-02-19 03:04:26 +00003454
Chris Lattner4ca3d772008-01-03 22:56:36 +00003455 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003456 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003457 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003458
3459 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003460 assert(lhptee->isFunctionType());
3461 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003462 }
Mike Stump9afab102009-02-19 03:04:26 +00003463 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003464 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003465 lhptee = lhptee.getUnqualifiedType();
3466 rhptee = rhptee.getUnqualifiedType();
3467 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3468 // Check if the pointee types are compatible ignoring the sign.
3469 // We explicitly check for char so that we catch "char" vs
3470 // "unsigned char" on systems where "char" is unsigned.
3471 if (lhptee->isCharType()) {
3472 lhptee = Context.UnsignedCharTy;
3473 } else if (lhptee->isSignedIntegerType()) {
3474 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3475 }
3476 if (rhptee->isCharType()) {
3477 rhptee = Context.UnsignedCharTy;
3478 } else if (rhptee->isSignedIntegerType()) {
3479 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3480 }
3481 if (lhptee == rhptee) {
3482 // Types are compatible ignoring the sign. Qualifier incompatibility
3483 // takes priority over sign incompatibility because the sign
3484 // warning can be disabled.
3485 if (ConvTy != Compatible)
3486 return ConvTy;
3487 return IncompatiblePointerSign;
3488 }
3489 // General pointer incompatibility takes priority over qualifiers.
3490 return IncompatiblePointer;
3491 }
Chris Lattner005ed752008-01-04 18:04:52 +00003492 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003493}
3494
Steve Naroff3454b6c2008-09-04 15:10:53 +00003495/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3496/// block pointer types are compatible or whether a block and normal pointer
3497/// are compatible. It is more restrict than comparing two function pointer
3498// types.
Mike Stump9afab102009-02-19 03:04:26 +00003499Sema::AssignConvertType
3500Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003501 QualType rhsType) {
3502 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003503
Steve Naroff3454b6c2008-09-04 15:10:53 +00003504 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003505 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3506 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003507
Steve Naroff3454b6c2008-09-04 15:10:53 +00003508 // make sure we operate on the canonical type
3509 lhptee = Context.getCanonicalType(lhptee);
3510 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003511
Steve Naroff3454b6c2008-09-04 15:10:53 +00003512 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003513
Steve Naroff3454b6c2008-09-04 15:10:53 +00003514 // For blocks we enforce that qualifiers are identical.
3515 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3516 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003517
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003518 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003519 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003520 return ConvTy;
3521}
3522
Mike Stump9afab102009-02-19 03:04:26 +00003523/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3524/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003525/// pointers. Here are some objectionable examples that GCC considers warnings:
3526///
3527/// int a, *pint;
3528/// short *pshort;
3529/// struct foo *pfoo;
3530///
3531/// pint = pshort; // warning: assignment from incompatible pointer type
3532/// a = pint; // warning: assignment makes integer from pointer without a cast
3533/// pint = a; // warning: assignment makes pointer from integer without a cast
3534/// pint = pfoo; // warning: assignment from incompatible pointer type
3535///
3536/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003537/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003538///
Chris Lattner005ed752008-01-04 18:04:52 +00003539Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003540Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003541 // Get canonical types. We're not formatting these types, just comparing
3542 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003543 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3544 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003545
3546 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003547 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003548
David Chisnall44663db2009-08-17 16:35:33 +00003549 if ((lhsType->isObjCClassType() &&
3550 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3551 (rhsType->isObjCClassType() &&
3552 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3553 return Compatible;
3554 }
3555
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003556 // If the left-hand side is a reference type, then we are in a
3557 // (rare!) case where we've allowed the use of references in C,
3558 // e.g., as a parameter type in a built-in function. In this case,
3559 // just make sure that the type referenced is compatible with the
3560 // right-hand side type. The caller is responsible for adjusting
3561 // lhsType so that the resulting expression does not have reference
3562 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003563 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003564 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003565 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003566 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003567 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003568 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3569 // to the same ExtVector type.
3570 if (lhsType->isExtVectorType()) {
3571 if (rhsType->isExtVectorType())
3572 return lhsType == rhsType ? Compatible : Incompatible;
3573 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3574 return Compatible;
3575 }
3576
Nate Begemanc5f0f652008-07-14 18:02:46 +00003577 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003578 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003579 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003580 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003581 if (getLangOptions().LaxVectorConversions &&
3582 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003583 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003584 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003585 }
3586 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003587 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003588
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003589 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003590 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003591
Chris Lattner390564e2008-04-07 06:49:41 +00003592 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003593 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003594 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003595
Chris Lattner390564e2008-04-07 06:49:41 +00003596 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003597 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003598
Steve Naroff8194a542009-07-20 17:56:53 +00003599 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003600 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003601 if (lhsType->isVoidPointerType()) // an exception to the rule.
3602 return Compatible;
3603 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003604 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003605 if (rhsType->getAs<BlockPointerType>()) {
3606 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003607 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003608
3609 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003610 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003611 return Compatible;
3612 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003613 return Incompatible;
3614 }
3615
3616 if (isa<BlockPointerType>(lhsType)) {
3617 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003618 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003619
Steve Naroffa982c712008-09-29 18:10:17 +00003620 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003621 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003622 return Compatible;
3623
Steve Naroff3454b6c2008-09-04 15:10:53 +00003624 if (rhsType->isBlockPointerType())
3625 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003626
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003627 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003628 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003629 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003630 }
Chris Lattner1853da22008-01-04 23:18:45 +00003631 return Incompatible;
3632 }
3633
Steve Naroff329ec222009-07-10 23:34:53 +00003634 if (isa<ObjCObjectPointerType>(lhsType)) {
3635 if (rhsType->isIntegerType())
3636 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003637
3638 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003639 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003640 if (rhsType->isVoidPointerType()) // an exception to the rule.
3641 return Compatible;
3642 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003643 }
3644 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003645 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3646 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003647 if (Context.typesAreCompatible(lhsType, rhsType))
3648 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003649 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3650 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003651 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003652 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003653 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003654 if (RHSPT->getPointeeType()->isVoidType())
3655 return Compatible;
3656 }
3657 // Treat block pointers as objects.
3658 if (rhsType->isBlockPointerType())
3659 return Compatible;
3660 return Incompatible;
3661 }
Chris Lattner390564e2008-04-07 06:49:41 +00003662 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003663 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003664 if (lhsType == Context.BoolTy)
3665 return Compatible;
3666
3667 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003668 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003669
Mike Stump9afab102009-02-19 03:04:26 +00003670 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003671 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003672
3673 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003674 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003675 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003676 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003677 }
Steve Naroff329ec222009-07-10 23:34:53 +00003678 if (isa<ObjCObjectPointerType>(rhsType)) {
3679 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3680 if (lhsType == Context.BoolTy)
3681 return Compatible;
3682
3683 if (lhsType->isIntegerType())
3684 return PointerToInt;
3685
Steve Naroff8194a542009-07-20 17:56:53 +00003686 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003687 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003688 if (lhsType->isVoidPointerType()) // an exception to the rule.
3689 return Compatible;
3690 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003691 }
3692 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003693 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003694 return Compatible;
3695 return Incompatible;
3696 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003697
Chris Lattner1853da22008-01-04 23:18:45 +00003698 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003699 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003700 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003701 }
3702 return Incompatible;
3703}
3704
Douglas Gregor144b06c2009-04-29 22:16:16 +00003705/// \brief Constructs a transparent union from an expression that is
3706/// used to initialize the transparent union.
3707static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3708 QualType UnionType, FieldDecl *Field) {
3709 // Build an initializer list that designates the appropriate member
3710 // of the transparent union.
3711 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3712 &E, 1,
3713 SourceLocation());
3714 Initializer->setType(UnionType);
3715 Initializer->setInitializedFieldInUnion(Field);
3716
3717 // Build a compound literal constructing a value of the transparent
3718 // union type from this initializer list.
3719 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3720 false);
3721}
3722
3723Sema::AssignConvertType
3724Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3725 QualType FromType = rExpr->getType();
3726
3727 // If the ArgType is a Union type, we want to handle a potential
3728 // transparent_union GCC extension.
3729 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003730 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003731 return Incompatible;
3732
3733 // The field to initialize within the transparent union.
3734 RecordDecl *UD = UT->getDecl();
3735 FieldDecl *InitField = 0;
3736 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003737 for (RecordDecl::field_iterator it = UD->field_begin(),
3738 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003739 it != itend; ++it) {
3740 if (it->getType()->isPointerType()) {
3741 // If the transparent union contains a pointer type, we allow:
3742 // 1) void pointer
3743 // 2) null pointer constant
3744 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003745 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003746 ImpCastExprToType(rExpr, it->getType());
3747 InitField = *it;
3748 break;
3749 }
3750
3751 if (rExpr->isNullPointerConstant(Context)) {
3752 ImpCastExprToType(rExpr, it->getType());
3753 InitField = *it;
3754 break;
3755 }
3756 }
3757
3758 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3759 == Compatible) {
3760 InitField = *it;
3761 break;
3762 }
3763 }
3764
3765 if (!InitField)
3766 return Incompatible;
3767
3768 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3769 return Compatible;
3770}
3771
Chris Lattner005ed752008-01-04 18:04:52 +00003772Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003773Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003774 if (getLangOptions().CPlusPlus) {
3775 if (!lhsType->isRecordType()) {
3776 // C++ 5.17p3: If the left operand is not of class type, the
3777 // expression is implicitly converted (C++ 4) to the
3778 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003779 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3780 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003781 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003782 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003783 }
3784
3785 // FIXME: Currently, we fall through and treat C++ classes like C
3786 // structures.
3787 }
3788
Steve Naroffcdee22d2007-11-27 17:58:44 +00003789 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3790 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003791 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003792 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003793 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003794 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003795 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003796 return Compatible;
3797 }
Mike Stump9afab102009-02-19 03:04:26 +00003798
Chris Lattner5f505bf2007-10-16 02:55:40 +00003799 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003800 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003801 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003802 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003803 //
Mike Stump9afab102009-02-19 03:04:26 +00003804 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003805 if (!lhsType->isReferenceType())
3806 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003807
Chris Lattner005ed752008-01-04 18:04:52 +00003808 Sema::AssignConvertType result =
3809 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003810
Steve Naroff0f32f432007-08-24 22:33:52 +00003811 // C99 6.5.16.1p2: The value of the right operand is converted to the
3812 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003813 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3814 // so that we can use references in built-in functions even in C.
3815 // The getNonReferenceType() call makes sure that the resulting expression
3816 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003817 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003818 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003819 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003820}
3821
Chris Lattner1eafdea2008-11-18 01:30:42 +00003822QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003823 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003824 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003825 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003826 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003827}
3828
Mike Stump9afab102009-02-19 03:04:26 +00003829inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003830 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003831 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003832 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003833 QualType lhsType =
3834 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3835 QualType rhsType =
3836 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003837
Nate Begemanc5f0f652008-07-14 18:02:46 +00003838 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003839 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003840 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003841
Nate Begemanc5f0f652008-07-14 18:02:46 +00003842 // Handle the case of a vector & extvector type of the same size and element
3843 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003844 if (getLangOptions().LaxVectorConversions) {
3845 // FIXME: Should we warn here?
3846 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003847 if (const VectorType *RV = rhsType->getAsVectorType())
3848 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003849 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003850 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003851 }
3852 }
3853 }
Mike Stump9afab102009-02-19 03:04:26 +00003854
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003855 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3856 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3857 bool swapped = false;
3858 if (rhsType->isExtVectorType()) {
3859 swapped = true;
3860 std::swap(rex, lex);
3861 std::swap(rhsType, lhsType);
3862 }
3863
Nate Begemanf1695892009-06-28 19:12:57 +00003864 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003865 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3866 QualType EltTy = LV->getElementType();
3867 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3868 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003869 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003870 if (swapped) std::swap(rex, lex);
3871 return lhsType;
3872 }
3873 }
3874 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3875 rhsType->isRealFloatingType()) {
3876 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003877 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003878 if (swapped) std::swap(rex, lex);
3879 return lhsType;
3880 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003881 }
3882 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003883
Nate Begemanf1695892009-06-28 19:12:57 +00003884 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003885 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003886 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003887 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003888 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003889}
3890
Chris Lattner4b009652007-07-25 00:24:17 +00003891inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003892 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003893{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003894 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003895 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003896
Steve Naroff8f708362007-08-24 19:07:16 +00003897 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003898
Chris Lattner4b009652007-07-25 00:24:17 +00003899 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003900 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003901 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003902}
3903
3904inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003905 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003906{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003907 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3908 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3909 return CheckVectorOperands(Loc, lex, rex);
3910 return InvalidOperands(Loc, lex, rex);
3911 }
Chris Lattner4b009652007-07-25 00:24:17 +00003912
Steve Naroff8f708362007-08-24 19:07:16 +00003913 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003914
Chris Lattner4b009652007-07-25 00:24:17 +00003915 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003916 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003917 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003918}
3919
3920inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003921 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003922{
Eli Friedman3cd92882009-03-28 01:22:36 +00003923 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3924 QualType compType = CheckVectorOperands(Loc, lex, rex);
3925 if (CompLHSTy) *CompLHSTy = compType;
3926 return compType;
3927 }
Chris Lattner4b009652007-07-25 00:24:17 +00003928
Eli Friedman3cd92882009-03-28 01:22:36 +00003929 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003930
Chris Lattner4b009652007-07-25 00:24:17 +00003931 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003932 if (lex->getType()->isArithmeticType() &&
3933 rex->getType()->isArithmeticType()) {
3934 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003935 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003936 }
Chris Lattner4b009652007-07-25 00:24:17 +00003937
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003938 // Put any potential pointer into PExp
3939 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00003940 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003941 std::swap(PExp, IExp);
3942
Steve Naroff79ae19a2009-07-14 18:25:06 +00003943 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003944
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003945 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00003946 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00003947
Chris Lattner184f92d2009-04-24 23:50:08 +00003948 // Check for arithmetic on pointers to incomplete types.
3949 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003950 if (getLangOptions().CPlusPlus) {
3951 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003952 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003953 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003954 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003955
3956 // GNU extension: arithmetic on pointer to void
3957 Diag(Loc, diag::ext_gnu_void_ptr)
3958 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003959 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003960 if (getLangOptions().CPlusPlus) {
3961 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3962 << lex->getType() << lex->getSourceRange();
3963 return QualType();
3964 }
3965
3966 // GNU extension: arithmetic on pointer to function
3967 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3968 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00003969 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00003970 // Check if we require a complete type.
3971 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00003972 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00003973 PExp->getType()->isObjCObjectPointerType()) &&
3974 RequireCompleteType(Loc, PointeeTy,
3975 diag::err_typecheck_arithmetic_incomplete_type,
3976 PExp->getSourceRange(), SourceRange(),
3977 PExp->getType()))
3978 return QualType();
3979 }
Chris Lattner184f92d2009-04-24 23:50:08 +00003980 // Diagnose bad cases where we step over interface counts.
3981 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3982 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3983 << PointeeTy << PExp->getSourceRange();
3984 return QualType();
3985 }
3986
Eli Friedman3cd92882009-03-28 01:22:36 +00003987 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00003988 QualType LHSTy = Context.isPromotableBitField(lex);
3989 if (LHSTy.isNull()) {
3990 LHSTy = lex->getType();
3991 if (LHSTy->isPromotableIntegerType())
3992 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003993 }
Eli Friedman3cd92882009-03-28 01:22:36 +00003994 *CompLHSTy = LHSTy;
3995 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003996 return PExp->getType();
3997 }
3998 }
3999
Chris Lattner1eafdea2008-11-18 01:30:42 +00004000 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004001}
4002
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004003// C99 6.5.6
4004QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004005 SourceLocation Loc, QualType* CompLHSTy) {
4006 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4007 QualType compType = CheckVectorOperands(Loc, lex, rex);
4008 if (CompLHSTy) *CompLHSTy = compType;
4009 return compType;
4010 }
Mike Stump9afab102009-02-19 03:04:26 +00004011
Eli Friedman3cd92882009-03-28 01:22:36 +00004012 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004013
Chris Lattnerf6da2912007-12-09 21:53:25 +00004014 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004015
Chris Lattnerf6da2912007-12-09 21:53:25 +00004016 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004017 if (lex->getType()->isArithmeticType()
4018 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004019 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004020 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004021 }
Steve Naroff329ec222009-07-10 23:34:53 +00004022
Chris Lattnerf6da2912007-12-09 21:53:25 +00004023 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004024 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004025 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004026
Douglas Gregor05e28f62009-03-24 19:52:54 +00004027 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004028
Douglas Gregor05e28f62009-03-24 19:52:54 +00004029 bool ComplainAboutVoid = false;
4030 Expr *ComplainAboutFunc = 0;
4031 if (lpointee->isVoidType()) {
4032 if (getLangOptions().CPlusPlus) {
4033 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4034 << lex->getSourceRange() << rex->getSourceRange();
4035 return QualType();
4036 }
4037
4038 // GNU C extension: arithmetic on pointer to void
4039 ComplainAboutVoid = true;
4040 } else if (lpointee->isFunctionType()) {
4041 if (getLangOptions().CPlusPlus) {
4042 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004043 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004044 return QualType();
4045 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004046
4047 // GNU C extension: arithmetic on pointer to function
4048 ComplainAboutFunc = lex;
4049 } else if (!lpointee->isDependentType() &&
4050 RequireCompleteType(Loc, lpointee,
4051 diag::err_typecheck_sub_ptr_object,
4052 lex->getSourceRange(),
4053 SourceRange(),
4054 lex->getType()))
4055 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004056
Chris Lattner184f92d2009-04-24 23:50:08 +00004057 // Diagnose bad cases where we step over interface counts.
4058 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4059 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4060 << lpointee << lex->getSourceRange();
4061 return QualType();
4062 }
4063
Chris Lattnerf6da2912007-12-09 21:53:25 +00004064 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004065 if (rex->getType()->isIntegerType()) {
4066 if (ComplainAboutVoid)
4067 Diag(Loc, diag::ext_gnu_void_ptr)
4068 << lex->getSourceRange() << rex->getSourceRange();
4069 if (ComplainAboutFunc)
4070 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4071 << ComplainAboutFunc->getType()
4072 << ComplainAboutFunc->getSourceRange();
4073
Eli Friedman3cd92882009-03-28 01:22:36 +00004074 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004075 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004076 }
Mike Stump9afab102009-02-19 03:04:26 +00004077
Chris Lattnerf6da2912007-12-09 21:53:25 +00004078 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004079 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004080 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004081
Douglas Gregor05e28f62009-03-24 19:52:54 +00004082 // RHS must be a completely-type object type.
4083 // Handle the GNU void* extension.
4084 if (rpointee->isVoidType()) {
4085 if (getLangOptions().CPlusPlus) {
4086 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4087 << lex->getSourceRange() << rex->getSourceRange();
4088 return QualType();
4089 }
Mike Stump9afab102009-02-19 03:04:26 +00004090
Douglas Gregor05e28f62009-03-24 19:52:54 +00004091 ComplainAboutVoid = true;
4092 } else if (rpointee->isFunctionType()) {
4093 if (getLangOptions().CPlusPlus) {
4094 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004095 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004096 return QualType();
4097 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004098
4099 // GNU extension: arithmetic on pointer to function
4100 if (!ComplainAboutFunc)
4101 ComplainAboutFunc = rex;
4102 } else if (!rpointee->isDependentType() &&
4103 RequireCompleteType(Loc, rpointee,
4104 diag::err_typecheck_sub_ptr_object,
4105 rex->getSourceRange(),
4106 SourceRange(),
4107 rex->getType()))
4108 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004109
Eli Friedman143ddc92009-05-16 13:54:38 +00004110 if (getLangOptions().CPlusPlus) {
4111 // Pointee types must be the same: C++ [expr.add]
4112 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4113 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4114 << lex->getType() << rex->getType()
4115 << lex->getSourceRange() << rex->getSourceRange();
4116 return QualType();
4117 }
4118 } else {
4119 // Pointee types must be compatible C99 6.5.6p3
4120 if (!Context.typesAreCompatible(
4121 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4122 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4123 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4124 << lex->getType() << rex->getType()
4125 << lex->getSourceRange() << rex->getSourceRange();
4126 return QualType();
4127 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004128 }
Mike Stump9afab102009-02-19 03:04:26 +00004129
Douglas Gregor05e28f62009-03-24 19:52:54 +00004130 if (ComplainAboutVoid)
4131 Diag(Loc, diag::ext_gnu_void_ptr)
4132 << lex->getSourceRange() << rex->getSourceRange();
4133 if (ComplainAboutFunc)
4134 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4135 << ComplainAboutFunc->getType()
4136 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004137
4138 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004139 return Context.getPointerDiffType();
4140 }
4141 }
Mike Stump9afab102009-02-19 03:04:26 +00004142
Chris Lattner1eafdea2008-11-18 01:30:42 +00004143 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004144}
4145
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004146// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004147QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004148 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004149 // C99 6.5.7p2: Each of the operands shall have integer type.
4150 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004151 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004152
Chris Lattner2c8bff72007-12-12 05:47:28 +00004153 // Shifts don't perform usual arithmetic conversions, they just do integer
4154 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004155 QualType LHSTy = Context.isPromotableBitField(lex);
4156 if (LHSTy.isNull()) {
4157 LHSTy = lex->getType();
4158 if (LHSTy->isPromotableIntegerType())
4159 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004160 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004161 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004162 ImpCastExprToType(lex, LHSTy);
4163
Chris Lattner2c8bff72007-12-12 05:47:28 +00004164 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004165
Ryan Flynnf109fff2009-08-07 16:20:20 +00004166 // Sanity-check shift operands
4167 llvm::APSInt Right;
4168 // Check right/shifter operand
4169 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004170 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004171 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4172 else {
4173 llvm::APInt LeftBits(Right.getBitWidth(),
4174 Context.getTypeSize(lex->getType()));
4175 if (Right.uge(LeftBits))
4176 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4177 }
4178 }
4179
Chris Lattner2c8bff72007-12-12 05:47:28 +00004180 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004181 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004182}
4183
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004184// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004185QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004186 unsigned OpaqueOpc, bool isRelational) {
4187 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4188
Nate Begemanc5f0f652008-07-14 18:02:46 +00004189 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004190 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004191
Chris Lattner254f3bc2007-08-26 01:18:55 +00004192 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004193 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4194 UsualArithmeticConversions(lex, rex);
4195 else {
4196 UsualUnaryConversions(lex);
4197 UsualUnaryConversions(rex);
4198 }
Chris Lattner4b009652007-07-25 00:24:17 +00004199 QualType lType = lex->getType();
4200 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004201
Mike Stumpea3d74e2009-05-07 18:43:07 +00004202 if (!lType->isFloatingType()
4203 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004204 // For non-floating point types, check for self-comparisons of the form
4205 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4206 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004207 // NOTE: Don't warn about comparisons of enum constants. These can arise
4208 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004209 Expr *LHSStripped = lex->IgnoreParens();
4210 Expr *RHSStripped = rex->IgnoreParens();
4211 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4212 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004213 if (DRL->getDecl() == DRR->getDecl() &&
4214 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004215 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004216
4217 if (isa<CastExpr>(LHSStripped))
4218 LHSStripped = LHSStripped->IgnoreParenCasts();
4219 if (isa<CastExpr>(RHSStripped))
4220 RHSStripped = RHSStripped->IgnoreParenCasts();
4221
4222 // Warn about comparisons against a string constant (unless the other
4223 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004224 Expr *literalString = 0;
4225 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004226 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004227 !RHSStripped->isNullPointerConstant(Context)) {
4228 literalString = lex;
4229 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004230 } else if ((isa<StringLiteral>(RHSStripped) ||
4231 isa<ObjCEncodeExpr>(RHSStripped)) &&
4232 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004233 literalString = rex;
4234 literalStringStripped = RHSStripped;
4235 }
4236
4237 if (literalString) {
4238 std::string resultComparison;
4239 switch (Opc) {
4240 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4241 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4242 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4243 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4244 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4245 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4246 default: assert(false && "Invalid comparison operator");
4247 }
4248 Diag(Loc, diag::warn_stringcompare)
4249 << isa<ObjCEncodeExpr>(literalStringStripped)
4250 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004251 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4252 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4253 "strcmp(")
4254 << CodeModificationHint::CreateInsertion(
4255 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004256 resultComparison);
4257 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004258 }
Mike Stump9afab102009-02-19 03:04:26 +00004259
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004260 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004261 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004262
Chris Lattner254f3bc2007-08-26 01:18:55 +00004263 if (isRelational) {
4264 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004265 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004266 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004267 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004268 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004269 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004270 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004271 }
Mike Stump9afab102009-02-19 03:04:26 +00004272
Chris Lattner254f3bc2007-08-26 01:18:55 +00004273 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004274 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004275 }
Mike Stump9afab102009-02-19 03:04:26 +00004276
Chris Lattner22be8422007-08-26 01:10:14 +00004277 bool LHSIsNull = lex->isNullPointerConstant(Context);
4278 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004279
Chris Lattner254f3bc2007-08-26 01:18:55 +00004280 // All of the following pointer related warnings are GCC extensions, except
4281 // when handling null pointer constants. One day, we can consider making them
4282 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004283 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004284 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004285 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004286 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004287 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004288
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004289 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004290 if (LCanPointeeTy == RCanPointeeTy)
4291 return ResultTy;
4292
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004293 // C++ [expr.rel]p2:
4294 // [...] Pointer conversions (4.10) and qualification
4295 // conversions (4.4) are performed on pointer operands (or on
4296 // a pointer operand and a null pointer constant) to bring
4297 // them to their composite pointer type. [...]
4298 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004299 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004300 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004301 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004302 if (T.isNull()) {
4303 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4304 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4305 return QualType();
4306 }
4307
4308 ImpCastExprToType(lex, T);
4309 ImpCastExprToType(rex, T);
4310 return ResultTy;
4311 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004312 // C99 6.5.9p2 and C99 6.5.8p2
4313 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4314 RCanPointeeTy.getUnqualifiedType())) {
4315 // Valid unless a relational comparison of function pointers
4316 if (isRelational && LCanPointeeTy->isFunctionType()) {
4317 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4318 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4319 }
4320 } else if (!isRelational &&
4321 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4322 // Valid unless comparison between non-null pointer and function pointer
4323 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4324 && !LHSIsNull && !RHSIsNull) {
4325 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4326 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4327 }
4328 } else {
4329 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004330 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004331 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004332 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004333 if (LCanPointeeTy != RCanPointeeTy)
4334 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004335 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004336 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004337
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004338 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004339 // Comparison of pointers with null pointer constants and equality
4340 // comparisons of member pointers to null pointer constants.
4341 if (RHSIsNull &&
4342 (lType->isPointerType() ||
4343 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004344 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004345 return ResultTy;
4346 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004347 if (LHSIsNull &&
4348 (rType->isPointerType() ||
4349 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004350 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004351 return ResultTy;
4352 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004353
4354 // Comparison of member pointers.
4355 if (!isRelational &&
4356 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4357 // C++ [expr.eq]p2:
4358 // In addition, pointers to members can be compared, or a pointer to
4359 // member and a null pointer constant. Pointer to member conversions
4360 // (4.11) and qualification conversions (4.4) are performed to bring
4361 // them to a common type. If one operand is a null pointer constant,
4362 // the common type is the type of the other operand. Otherwise, the
4363 // common type is a pointer to member type similar (4.4) to the type
4364 // of one of the operands, with a cv-qualification signature (4.4)
4365 // that is the union of the cv-qualification signatures of the operand
4366 // types.
4367 QualType T = FindCompositePointerType(lex, rex);
4368 if (T.isNull()) {
4369 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4370 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4371 return QualType();
4372 }
4373
4374 ImpCastExprToType(lex, T);
4375 ImpCastExprToType(rex, T);
4376 return ResultTy;
4377 }
4378
4379 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004380 if (lType->isNullPtrType() && rType->isNullPtrType())
4381 return ResultTy;
4382 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004383
Steve Naroff3454b6c2008-09-04 15:10:53 +00004384 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004385 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004386 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4387 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004388
Steve Naroff3454b6c2008-09-04 15:10:53 +00004389 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004390 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004391 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004392 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004393 }
4394 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004395 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004396 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004397 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004398 if (!isRelational
4399 && ((lType->isBlockPointerType() && rType->isPointerType())
4400 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004401 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004402 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004403 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004404 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004405 ->getPointeeType()->isVoidType())))
4406 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4407 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004408 }
4409 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004410 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004411 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004412
Steve Naroff329ec222009-07-10 23:34:53 +00004413 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004414 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004415 const PointerType *LPT = lType->getAs<PointerType>();
4416 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004417 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004418 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004419 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004420 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004421
Steve Naroff030fcda2008-11-17 19:49:16 +00004422 if (!LPtrToVoid && !RPtrToVoid &&
4423 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004424 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004425 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004426 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004427 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004428 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004429 }
Steve Naroff329ec222009-07-10 23:34:53 +00004430 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004431 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004432 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4433 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004434 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004435 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004436 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004437 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004438 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004439 unsigned DiagID = 0;
4440 if (RHSIsNull) {
4441 if (isRelational)
4442 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4443 } else if (isRelational)
4444 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4445 else
4446 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4447
4448 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004449 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004450 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004451 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004452 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004453 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004454 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004455 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004456 unsigned DiagID = 0;
4457 if (LHSIsNull) {
4458 if (isRelational)
4459 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4460 } else if (isRelational)
4461 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4462 else
4463 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004464
Chris Lattner124569f2009-08-23 00:03:44 +00004465 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004466 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004467 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004468 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004469 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004470 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004471 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004472 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004473 if (!isRelational && RHSIsNull
4474 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004475 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004476 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004477 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004478 if (!isRelational && LHSIsNull
4479 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004480 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004481 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004482 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004483 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004484}
4485
Nate Begemanc5f0f652008-07-14 18:02:46 +00004486/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004487/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004488/// like a scalar comparison, a vector comparison produces a vector of integer
4489/// types.
4490QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004491 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004492 bool isRelational) {
4493 // Check to make sure we're operating on vectors of the same type and width,
4494 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004495 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004496 if (vType.isNull())
4497 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004498
Nate Begemanc5f0f652008-07-14 18:02:46 +00004499 QualType lType = lex->getType();
4500 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004501
Nate Begemanc5f0f652008-07-14 18:02:46 +00004502 // For non-floating point types, check for self-comparisons of the form
4503 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4504 // often indicate logic errors in the program.
4505 if (!lType->isFloatingType()) {
4506 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4507 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4508 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004509 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004510 }
Mike Stump9afab102009-02-19 03:04:26 +00004511
Nate Begemanc5f0f652008-07-14 18:02:46 +00004512 // Check for comparisons of floating point operands using != and ==.
4513 if (!isRelational && lType->isFloatingType()) {
4514 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004515 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004516 }
Mike Stump9afab102009-02-19 03:04:26 +00004517
Nate Begemanc5f0f652008-07-14 18:02:46 +00004518 // Return the type for the comparison, which is the same as vector type for
4519 // integer vectors, or an integer type of identical size and number of
4520 // elements for floating point vectors.
4521 if (lType->isIntegerType())
4522 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004523
Nate Begemanc5f0f652008-07-14 18:02:46 +00004524 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004525 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004526 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004527 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004528 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004529 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4530
Mike Stump9afab102009-02-19 03:04:26 +00004531 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004532 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004533 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4534}
4535
Chris Lattner4b009652007-07-25 00:24:17 +00004536inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004537 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004538{
4539 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004540 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004541
Steve Naroff8f708362007-08-24 19:07:16 +00004542 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004543
Chris Lattner4b009652007-07-25 00:24:17 +00004544 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004545 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004546 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004547}
4548
4549inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004550 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004551{
4552 UsualUnaryConversions(lex);
4553 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004554
Eli Friedmanbea3f842008-05-13 20:16:47 +00004555 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004556 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004557 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004558}
4559
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004560/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4561/// is a read-only property; return true if so. A readonly property expression
4562/// depends on various declarations and thus must be treated specially.
4563///
Mike Stump9afab102009-02-19 03:04:26 +00004564static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004565{
4566 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4567 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4568 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4569 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004570 if (const ObjCObjectPointerType *OPT =
4571 BaseType->getAsObjCInterfacePointerType())
4572 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4573 if (S.isPropertyReadonly(PDecl, IFace))
4574 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004575 }
4576 }
4577 return false;
4578}
4579
Chris Lattner4c2642c2008-11-18 01:22:49 +00004580/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4581/// emit an error and return true. If so, return false.
4582static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004583 SourceLocation OrigLoc = Loc;
4584 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4585 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004586 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4587 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004588 if (IsLV == Expr::MLV_Valid)
4589 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004590
Chris Lattner4c2642c2008-11-18 01:22:49 +00004591 unsigned Diag = 0;
4592 bool NeedType = false;
4593 switch (IsLV) { // C99 6.5.16p2
4594 default: assert(0 && "Unknown result from isModifiableLvalue!");
4595 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004596 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004597 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4598 NeedType = true;
4599 break;
Mike Stump9afab102009-02-19 03:04:26 +00004600 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004601 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4602 NeedType = true;
4603 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004604 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004605 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4606 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004607 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004608 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4609 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004610 case Expr::MLV_IncompleteType:
4611 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004612 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004613 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4614 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004615 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004616 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4617 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004618 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004619 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4620 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004621 case Expr::MLV_ReadonlyProperty:
4622 Diag = diag::error_readonly_property_assignment;
4623 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004624 case Expr::MLV_NoSetterProperty:
4625 Diag = diag::error_nosetter_property_assignment;
4626 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004627 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004628
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004629 SourceRange Assign;
4630 if (Loc != OrigLoc)
4631 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004632 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004633 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004634 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004635 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004636 return true;
4637}
4638
4639
4640
4641// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004642QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4643 SourceLocation Loc,
4644 QualType CompoundType) {
4645 // Verify that LHS is a modifiable lvalue, and emit error if not.
4646 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004647 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004648
4649 QualType LHSType = LHS->getType();
4650 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004651
Chris Lattner005ed752008-01-04 18:04:52 +00004652 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004653 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004654 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004655 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004656 // Special case of NSObject attributes on c-style pointer types.
4657 if (ConvTy == IncompatiblePointer &&
4658 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004659 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004660 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004661 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004662 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004663
Chris Lattner34c85082008-08-21 18:04:13 +00004664 // If the RHS is a unary plus or minus, check to see if they = and + are
4665 // right next to each other. If so, the user may have typo'd "x =+ 4"
4666 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004667 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004668 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4669 RHSCheck = ICE->getSubExpr();
4670 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4671 if ((UO->getOpcode() == UnaryOperator::Plus ||
4672 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004673 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004674 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004675 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4676 // And there is a space or other character before the subexpr of the
4677 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004678 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4679 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004680 Diag(Loc, diag::warn_not_compound_assign)
4681 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4682 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004683 }
Chris Lattner34c85082008-08-21 18:04:13 +00004684 }
4685 } else {
4686 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004687 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004688 }
Chris Lattner005ed752008-01-04 18:04:52 +00004689
Chris Lattner1eafdea2008-11-18 01:30:42 +00004690 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4691 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004692 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004693
Chris Lattner4b009652007-07-25 00:24:17 +00004694 // C99 6.5.16p3: The type of an assignment expression is the type of the
4695 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004696 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004697 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4698 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004699 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004700 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004701 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004702}
4703
Chris Lattner1eafdea2008-11-18 01:30:42 +00004704// C99 6.5.17
4705QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004706 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004707 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004708
4709 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4710 // incomplete in C++).
4711
Chris Lattner1eafdea2008-11-18 01:30:42 +00004712 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004713}
4714
4715/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4716/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004717QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4718 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004719 if (Op->isTypeDependent())
4720 return Context.DependentTy;
4721
Chris Lattnere65182c2008-11-21 07:05:48 +00004722 QualType ResType = Op->getType();
4723 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004724
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004725 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4726 // Decrement of bool is not allowed.
4727 if (!isInc) {
4728 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4729 return QualType();
4730 }
4731 // Increment of bool sets it to true, but is deprecated.
4732 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4733 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004734 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004735 } else if (ResType->isAnyPointerType()) {
4736 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004737
Chris Lattnere65182c2008-11-21 07:05:48 +00004738 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004739 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004740 if (getLangOptions().CPlusPlus) {
4741 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4742 << Op->getSourceRange();
4743 return QualType();
4744 }
4745
4746 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004747 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004748 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004749 if (getLangOptions().CPlusPlus) {
4750 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4751 << Op->getType() << Op->getSourceRange();
4752 return QualType();
4753 }
4754
4755 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004756 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004757 } else if (RequireCompleteType(OpLoc, PointeeTy,
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004758 diag::err_typecheck_arithmetic_incomplete_type,
4759 Op->getSourceRange(), SourceRange(),
4760 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004761 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004762 // Diagnose bad cases where we step over interface counts.
4763 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4764 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4765 << PointeeTy << Op->getSourceRange();
4766 return QualType();
4767 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004768 } else if (ResType->isComplexType()) {
4769 // C99 does not support ++/-- on complex types, we allow as an extension.
4770 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004771 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004772 } else {
4773 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004774 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004775 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004776 }
Mike Stump9afab102009-02-19 03:04:26 +00004777 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004778 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004779 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004780 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004781 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004782}
4783
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004784/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004785/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004786/// where the declaration is needed for type checking. We only need to
4787/// handle cases when the expression references a function designator
4788/// or is an lvalue. Here are some examples:
4789/// - &(x) => x
4790/// - &*****f => f for f a function designator.
4791/// - &s.xx => s
4792/// - &s.zz[1].yy -> s, if zz is an array
4793/// - *(x + 1) -> x, if x is an array
4794/// - &"123"[2] -> 0
4795/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004796static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004797 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004798 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004799 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004800 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004801 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004802 // If this is an arrow operator, the address is an offset from
4803 // the base's value, so the object the base refers to is
4804 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004805 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004806 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004807 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004808 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004809 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004810 // FIXME: This code shouldn't be necessary! We should catch the implicit
4811 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004812 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4813 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4814 if (ICE->getSubExpr()->getType()->isArrayType())
4815 return getPrimaryDecl(ICE->getSubExpr());
4816 }
4817 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004818 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004819 case Stmt::UnaryOperatorClass: {
4820 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004821
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004822 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004823 case UnaryOperator::Real:
4824 case UnaryOperator::Imag:
4825 case UnaryOperator::Extension:
4826 return getPrimaryDecl(UO->getSubExpr());
4827 default:
4828 return 0;
4829 }
4830 }
Chris Lattner4b009652007-07-25 00:24:17 +00004831 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004832 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004833 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004834 // If the result of an implicit cast is an l-value, we care about
4835 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004836 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004837 default:
4838 return 0;
4839 }
4840}
4841
4842/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004843/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004844/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004845/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004846/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004847/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004848/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004849QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004850 // Make sure to ignore parentheses in subsequent checks
4851 op = op->IgnoreParens();
4852
Douglas Gregore6be68a2008-12-17 22:52:20 +00004853 if (op->isTypeDependent())
4854 return Context.DependentTy;
4855
Steve Naroff9c6c3592008-01-13 17:10:08 +00004856 if (getLangOptions().C99) {
4857 // Implement C99-only parts of addressof rules.
4858 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4859 if (uOp->getOpcode() == UnaryOperator::Deref)
4860 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4861 // (assuming the deref expression is valid).
4862 return uOp->getSubExpr()->getType();
4863 }
4864 // Technically, there should be a check for array subscript
4865 // expressions here, but the result of one is always an lvalue anyway.
4866 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004867 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004868 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004869
Eli Friedman14ab4c42009-05-16 23:27:50 +00004870 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4871 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004872 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004873 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004874 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004875 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4876 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004877 return QualType();
4878 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004879 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004880 // The operand cannot be a bit-field
4881 Diag(OpLoc, diag::err_typecheck_address_of)
4882 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004883 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004884 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4885 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004886 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004887 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004888 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004889 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004890 } else if (isa<ObjCPropertyRefExpr>(op)) {
4891 // cannot take address of a property expression.
4892 Diag(OpLoc, diag::err_typecheck_address_of)
4893 << "property expression" << op->getSourceRange();
4894 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004895 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004896 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004897 // with the register storage-class specifier.
4898 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4899 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004900 Diag(OpLoc, diag::err_typecheck_address_of)
4901 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004902 return QualType();
4903 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004904 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4905 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004906 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004907 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004908 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004909 // Could be a pointer to member, though, if there is an explicit
4910 // scope qualifier for the class.
4911 if (isa<QualifiedDeclRefExpr>(op)) {
4912 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004913 if (Ctx && Ctx->isRecord()) {
4914 if (FD->getType()->isReferenceType()) {
4915 Diag(OpLoc,
4916 diag::err_cannot_form_pointer_to_member_of_reference_type)
4917 << FD->getDeclName() << FD->getType();
4918 return QualType();
4919 }
4920
Sebastian Redl0c9da212009-02-03 20:19:35 +00004921 return Context.getMemberPointerType(op->getType(),
4922 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004923 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004924 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004925 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004926 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004927 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004928 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4929 return Context.getMemberPointerType(op->getType(),
4930 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4931 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004932 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004933 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004934
Eli Friedman14ab4c42009-05-16 23:27:50 +00004935 if (lval == Expr::LV_IncompleteVoidType) {
4936 // Taking the address of a void variable is technically illegal, but we
4937 // allow it in cases which are otherwise valid.
4938 // Example: "extern void x; void* y = &x;".
4939 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4940 }
4941
Chris Lattner4b009652007-07-25 00:24:17 +00004942 // If the operand has type "type", the result has type "pointer to type".
4943 return Context.getPointerType(op->getType());
4944}
4945
Chris Lattnerda5c0872008-11-23 09:13:29 +00004946QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004947 if (Op->isTypeDependent())
4948 return Context.DependentTy;
4949
Chris Lattnerda5c0872008-11-23 09:13:29 +00004950 UsualUnaryConversions(Op);
4951 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004952
Chris Lattnerda5c0872008-11-23 09:13:29 +00004953 // Note that per both C89 and C99, this is always legal, even if ptype is an
4954 // incomplete type or void. It would be possible to warn about dereferencing
4955 // a void pointer, but it's completely well-defined, and such a warning is
4956 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004957 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004958 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004959
Steve Naroff329ec222009-07-10 23:34:53 +00004960 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4961 return OPT->getPointeeType();
4962
Chris Lattner77d52da2008-11-20 06:06:08 +00004963 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004964 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004965 return QualType();
4966}
4967
4968static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4969 tok::TokenKind Kind) {
4970 BinaryOperator::Opcode Opc;
4971 switch (Kind) {
4972 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004973 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4974 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004975 case tok::star: Opc = BinaryOperator::Mul; break;
4976 case tok::slash: Opc = BinaryOperator::Div; break;
4977 case tok::percent: Opc = BinaryOperator::Rem; break;
4978 case tok::plus: Opc = BinaryOperator::Add; break;
4979 case tok::minus: Opc = BinaryOperator::Sub; break;
4980 case tok::lessless: Opc = BinaryOperator::Shl; break;
4981 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4982 case tok::lessequal: Opc = BinaryOperator::LE; break;
4983 case tok::less: Opc = BinaryOperator::LT; break;
4984 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4985 case tok::greater: Opc = BinaryOperator::GT; break;
4986 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4987 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4988 case tok::amp: Opc = BinaryOperator::And; break;
4989 case tok::caret: Opc = BinaryOperator::Xor; break;
4990 case tok::pipe: Opc = BinaryOperator::Or; break;
4991 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4992 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4993 case tok::equal: Opc = BinaryOperator::Assign; break;
4994 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4995 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4996 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4997 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4998 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4999 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5000 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5001 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5002 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5003 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5004 case tok::comma: Opc = BinaryOperator::Comma; break;
5005 }
5006 return Opc;
5007}
5008
5009static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5010 tok::TokenKind Kind) {
5011 UnaryOperator::Opcode Opc;
5012 switch (Kind) {
5013 default: assert(0 && "Unknown unary op!");
5014 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5015 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5016 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5017 case tok::star: Opc = UnaryOperator::Deref; break;
5018 case tok::plus: Opc = UnaryOperator::Plus; break;
5019 case tok::minus: Opc = UnaryOperator::Minus; break;
5020 case tok::tilde: Opc = UnaryOperator::Not; break;
5021 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005022 case tok::kw___real: Opc = UnaryOperator::Real; break;
5023 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5024 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5025 }
5026 return Opc;
5027}
5028
Douglas Gregord7f915e2008-11-06 23:29:22 +00005029/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5030/// operator @p Opc at location @c TokLoc. This routine only supports
5031/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005032Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5033 unsigned Op,
5034 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005035 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005036 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005037 // The following two variables are used for compound assignment operators
5038 QualType CompLHSTy; // Type of LHS after promotions for computation
5039 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005040
5041 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005042 case BinaryOperator::Assign:
5043 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5044 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005045 case BinaryOperator::PtrMemD:
5046 case BinaryOperator::PtrMemI:
5047 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5048 Opc == BinaryOperator::PtrMemI);
5049 break;
5050 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005051 case BinaryOperator::Div:
5052 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5053 break;
5054 case BinaryOperator::Rem:
5055 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5056 break;
5057 case BinaryOperator::Add:
5058 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5059 break;
5060 case BinaryOperator::Sub:
5061 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5062 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005063 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005064 case BinaryOperator::Shr:
5065 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5066 break;
5067 case BinaryOperator::LE:
5068 case BinaryOperator::LT:
5069 case BinaryOperator::GE:
5070 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005071 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005072 break;
5073 case BinaryOperator::EQ:
5074 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005075 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005076 break;
5077 case BinaryOperator::And:
5078 case BinaryOperator::Xor:
5079 case BinaryOperator::Or:
5080 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5081 break;
5082 case BinaryOperator::LAnd:
5083 case BinaryOperator::LOr:
5084 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5085 break;
5086 case BinaryOperator::MulAssign:
5087 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005088 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5089 CompLHSTy = CompResultTy;
5090 if (!CompResultTy.isNull())
5091 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005092 break;
5093 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005094 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5095 CompLHSTy = CompResultTy;
5096 if (!CompResultTy.isNull())
5097 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005098 break;
5099 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005100 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5101 if (!CompResultTy.isNull())
5102 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005103 break;
5104 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005105 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5106 if (!CompResultTy.isNull())
5107 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005108 break;
5109 case BinaryOperator::ShlAssign:
5110 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005111 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5112 CompLHSTy = CompResultTy;
5113 if (!CompResultTy.isNull())
5114 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005115 break;
5116 case BinaryOperator::AndAssign:
5117 case BinaryOperator::XorAssign:
5118 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005119 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5120 CompLHSTy = CompResultTy;
5121 if (!CompResultTy.isNull())
5122 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005123 break;
5124 case BinaryOperator::Comma:
5125 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5126 break;
5127 }
5128 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005129 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005130 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005131 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5132 else
5133 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005134 CompLHSTy, CompResultTy,
5135 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005136}
5137
Chris Lattner4b009652007-07-25 00:24:17 +00005138// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005139Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5140 tok::TokenKind Kind,
5141 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005142 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005143 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005144
Steve Naroff87d58b42007-09-16 03:34:24 +00005145 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5146 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005147
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005148 if (getLangOptions().CPlusPlus &&
5149 (lhs->getType()->isOverloadableType() ||
5150 rhs->getType()->isOverloadableType())) {
5151 // Find all of the overloaded operators visible from this
5152 // point. We perform both an operator-name lookup from the local
5153 // scope and an argument-dependent lookup based on the types of
5154 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005155 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005156 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5157 if (OverOp != OO_None) {
5158 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5159 Functions);
5160 Expr *Args[2] = { lhs, rhs };
5161 DeclarationName OpName
5162 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5163 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005164 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005165
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005166 // Build the (potentially-overloaded, potentially-dependent)
5167 // binary operation.
5168 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005169 }
5170
Douglas Gregord7f915e2008-11-06 23:29:22 +00005171 // Build a built-in binary operation.
5172 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005173}
5174
Douglas Gregorc78182d2009-03-13 23:49:33 +00005175Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5176 unsigned OpcIn,
5177 ExprArg InputArg) {
5178 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005179
Mike Stumpe127ae32009-05-16 07:39:55 +00005180 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005181 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005182 QualType resultType;
5183 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005184 case UnaryOperator::OffsetOf:
5185 assert(false && "Invalid unary operator");
5186 break;
5187
Chris Lattner4b009652007-07-25 00:24:17 +00005188 case UnaryOperator::PreInc:
5189 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005190 case UnaryOperator::PostInc:
5191 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005192 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005193 Opc == UnaryOperator::PreInc ||
5194 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005195 break;
Mike Stump9afab102009-02-19 03:04:26 +00005196 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005197 resultType = CheckAddressOfOperand(Input, OpLoc);
5198 break;
Mike Stump9afab102009-02-19 03:04:26 +00005199 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005200 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005201 resultType = CheckIndirectionOperand(Input, OpLoc);
5202 break;
5203 case UnaryOperator::Plus:
5204 case UnaryOperator::Minus:
5205 UsualUnaryConversions(Input);
5206 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005207 if (resultType->isDependentType())
5208 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005209 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5210 break;
5211 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5212 resultType->isEnumeralType())
5213 break;
5214 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5215 Opc == UnaryOperator::Plus &&
5216 resultType->isPointerType())
5217 break;
5218
Sebastian Redl8b769972009-01-19 00:08:26 +00005219 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5220 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005221 case UnaryOperator::Not: // bitwise complement
5222 UsualUnaryConversions(Input);
5223 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005224 if (resultType->isDependentType())
5225 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005226 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5227 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5228 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005229 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005230 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005231 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005232 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5233 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005234 break;
5235 case UnaryOperator::LNot: // logical negation
5236 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5237 DefaultFunctionArrayConversion(Input);
5238 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005239 if (resultType->isDependentType())
5240 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005241 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005242 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5243 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005244 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005245 // In C++, it's bool. C++ 5.3.1p8
5246 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005247 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005248 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005249 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005250 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005251 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005252 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005253 resultType = Input->getType();
5254 break;
5255 }
5256 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005257 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005258
5259 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005260 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005261}
5262
Douglas Gregorc78182d2009-03-13 23:49:33 +00005263// Unary Operators. 'Tok' is the token for the operator.
5264Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5265 tok::TokenKind Op, ExprArg input) {
5266 Expr *Input = (Expr*)input.get();
5267 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5268
5269 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5270 // Find all of the overloaded operators visible from this
5271 // point. We perform both an operator-name lookup from the local
5272 // scope and an argument-dependent lookup based on the types of
5273 // the arguments.
5274 FunctionSet Functions;
5275 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5276 if (OverOp != OO_None) {
5277 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5278 Functions);
5279 DeclarationName OpName
5280 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5281 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5282 }
5283
5284 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5285 }
5286
5287 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5288}
5289
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005290/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005291Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5292 SourceLocation LabLoc,
5293 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005294 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005295 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005296
Daniel Dunbar879788d2008-08-04 16:51:22 +00005297 // If we haven't seen this label yet, create a forward reference. It
5298 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005299 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005300 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005301
Chris Lattner4b009652007-07-25 00:24:17 +00005302 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005303 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5304 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005305}
5306
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005307Sema::OwningExprResult
5308Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5309 SourceLocation RPLoc) { // "({..})"
5310 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005311 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5312 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5313
Eli Friedmanbc941e12009-01-24 23:09:00 +00005314 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005315 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005316 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005317
Chris Lattner4b009652007-07-25 00:24:17 +00005318 // FIXME: there are a variety of strange constraints to enforce here, for
5319 // example, it is not possible to goto into a stmt expression apparently.
5320 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005321
Chris Lattner4b009652007-07-25 00:24:17 +00005322 // If there are sub stmts in the compound stmt, take the type of the last one
5323 // as the type of the stmtexpr.
5324 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005325
Chris Lattner200964f2008-07-26 19:51:01 +00005326 if (!Compound->body_empty()) {
5327 Stmt *LastStmt = Compound->body_back();
5328 // If LastStmt is a label, skip down through into the body.
5329 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5330 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005331
Chris Lattner200964f2008-07-26 19:51:01 +00005332 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005333 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005334 }
Mike Stump9afab102009-02-19 03:04:26 +00005335
Eli Friedman2b128322009-03-23 00:24:07 +00005336 // FIXME: Check that expression type is complete/non-abstract; statement
5337 // expressions are not lvalues.
5338
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005339 substmt.release();
5340 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005341}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005342
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005343Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5344 SourceLocation BuiltinLoc,
5345 SourceLocation TypeLoc,
5346 TypeTy *argty,
5347 OffsetOfComponent *CompPtr,
5348 unsigned NumComponents,
5349 SourceLocation RPLoc) {
5350 // FIXME: This function leaks all expressions in the offset components on
5351 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005352 // FIXME: Preserve type source info.
5353 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005354 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005355
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005356 bool Dependent = ArgTy->isDependentType();
5357
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005358 // We must have at least one component that refers to the type, and the first
5359 // one is known to be a field designator. Verify that the ArgTy represents
5360 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005361 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005362 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005363
Eli Friedman2b128322009-03-23 00:24:07 +00005364 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5365 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005366
Eli Friedman342d9432009-02-27 06:44:11 +00005367 // Otherwise, create a null pointer as the base, and iteratively process
5368 // the offsetof designators.
5369 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5370 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005371 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005372 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005373
Chris Lattnerb37522e2007-08-31 21:49:13 +00005374 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5375 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005376 // FIXME: This diagnostic isn't actually visible because the location is in
5377 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005378 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005379 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5380 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005381
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005382 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005383 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005384
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005385 // FIXME: Dependent case loses a lot of information here. And probably
5386 // leaks like a sieve.
5387 for (unsigned i = 0; i != NumComponents; ++i) {
5388 const OffsetOfComponent &OC = CompPtr[i];
5389 if (OC.isBrackets) {
5390 // Offset of an array sub-field. TODO: Should we allow vector elements?
5391 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5392 if (!AT) {
5393 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005394 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5395 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005396 }
5397
5398 // FIXME: C++: Verify that operator[] isn't overloaded.
5399
Eli Friedman342d9432009-02-27 06:44:11 +00005400 // Promote the array so it looks more like a normal array subscript
5401 // expression.
5402 DefaultFunctionArrayConversion(Res);
5403
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005404 // C99 6.5.2.1p1
5405 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005406 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005407 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005408 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005409 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005410 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005411
5412 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5413 OC.LocEnd);
5414 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005415 }
Mike Stump9afab102009-02-19 03:04:26 +00005416
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005417 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005418 if (!RC) {
5419 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005420 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5421 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005422 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005423
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005424 // Get the decl corresponding to this.
5425 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005426 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005427 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005428 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5429 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5430 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005431 DidWarnAboutNonPOD = true;
5432 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005433 }
5434
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005435 FieldDecl *MemberDecl
5436 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5437 LookupMemberName)
5438 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005439 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005440 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005441 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5442 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005443
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005444 // FIXME: C++: Verify that MemberDecl isn't a static field.
5445 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005446 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005447 Res = BuildAnonymousStructUnionMemberReference(
5448 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005449 } else {
5450 // MemberDecl->getType() doesn't get the right qualifiers, but it
5451 // doesn't matter here.
5452 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5453 MemberDecl->getType().getNonReferenceType());
5454 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005455 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005456 }
Mike Stump9afab102009-02-19 03:04:26 +00005457
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005458 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5459 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005460}
5461
5462
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005463Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5464 TypeTy *arg1,TypeTy *arg2,
5465 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005466 // FIXME: Preserve type source info.
5467 QualType argT1 = GetTypeFromParser(arg1);
5468 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005469
Steve Naroff63bad2d2007-08-01 22:05:33 +00005470 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005471
Douglas Gregore6211502009-05-19 22:28:02 +00005472 if (getLangOptions().CPlusPlus) {
5473 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5474 << SourceRange(BuiltinLoc, RPLoc);
5475 return ExprError();
5476 }
5477
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005478 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5479 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005480}
5481
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005482Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5483 ExprArg cond,
5484 ExprArg expr1, ExprArg expr2,
5485 SourceLocation RPLoc) {
5486 Expr *CondExpr = static_cast<Expr*>(cond.get());
5487 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5488 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005489
Steve Naroff93c53012007-08-03 21:21:27 +00005490 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5491
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005492 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005493 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005494 resType = Context.DependentTy;
5495 } else {
5496 // The conditional expression is required to be a constant expression.
5497 llvm::APSInt condEval(32);
5498 SourceLocation ExpLoc;
5499 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005500 return ExprError(Diag(ExpLoc,
5501 diag::err_typecheck_choose_expr_requires_constant)
5502 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005503
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005504 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5505 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5506 }
5507
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005508 cond.release(); expr1.release(); expr2.release();
5509 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5510 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005511}
5512
Steve Naroff52a81c02008-09-03 18:15:37 +00005513//===----------------------------------------------------------------------===//
5514// Clang Extensions.
5515//===----------------------------------------------------------------------===//
5516
5517/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005518void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005519 // Analyze block parameters.
5520 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005521
Steve Naroff52a81c02008-09-03 18:15:37 +00005522 // Add BSI to CurBlock.
5523 BSI->PrevBlockInfo = CurBlock;
5524 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005525
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005526 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005527 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005528 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005529 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005530 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5531 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005532
Steve Naroff52059382008-10-10 01:28:17 +00005533 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005534 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005535}
5536
Mike Stumpc1fddff2009-02-04 22:31:32 +00005537void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005538 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005539
5540 if (ParamInfo.getNumTypeObjects() == 0
5541 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005542 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005543 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5544
Mike Stump458287d2009-04-28 01:10:27 +00005545 if (T->isArrayType()) {
5546 Diag(ParamInfo.getSourceRange().getBegin(),
5547 diag::err_block_returns_array);
5548 return;
5549 }
5550
Mike Stumpc1fddff2009-02-04 22:31:32 +00005551 // The parameter list is optional, if there was none, assume ().
5552 if (!T->isFunctionType())
5553 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5554
5555 CurBlock->hasPrototype = true;
5556 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005557 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005558 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005559 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005560 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005561 // FIXME: remove the attribute.
5562 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005563 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5564
5565 // Do not allow returning a objc interface by-value.
5566 if (RetTy->isObjCInterfaceType()) {
5567 Diag(ParamInfo.getSourceRange().getBegin(),
5568 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5569 return;
5570 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005571 return;
5572 }
5573
Steve Naroff52a81c02008-09-03 18:15:37 +00005574 // Analyze arguments to block.
5575 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5576 "Not a function declarator!");
5577 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005578
Steve Naroff52059382008-10-10 01:28:17 +00005579 CurBlock->hasPrototype = FTI.hasPrototype;
5580 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005581
Steve Naroff52a81c02008-09-03 18:15:37 +00005582 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5583 // no arguments, not a function that takes a single void argument.
5584 if (FTI.hasPrototype &&
5585 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005586 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5587 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005588 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005589 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005590 } else if (FTI.hasPrototype) {
5591 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005592 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005593 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005594 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005595 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005596 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005597 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005598 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005599 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5600 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5601 // If this has an identifier, add it to the scope stack.
5602 if ((*AI)->getIdentifier())
5603 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005604
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005605 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005606 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005607 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005608 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005609 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005610 // FIXME: remove the attribute.
5611 }
5612
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005613 // Analyze the return type.
5614 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5615 QualType RetTy = T->getAsFunctionType()->getResultType();
5616
5617 // Do not allow returning a objc interface by-value.
5618 if (RetTy->isObjCInterfaceType()) {
5619 Diag(ParamInfo.getSourceRange().getBegin(),
5620 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5621 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005622 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005623}
5624
5625/// ActOnBlockError - If there is an error parsing a block, this callback
5626/// is invoked to pop the information about the block from the action impl.
5627void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5628 // Ensure that CurBlock is deleted.
5629 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005630
Chris Lattnere7765e12009-04-19 05:28:12 +00005631 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5632
Steve Naroff52a81c02008-09-03 18:15:37 +00005633 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005634 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005635 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005636 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005637}
5638
5639/// ActOnBlockStmtExpr - This is called when the body of a block statement
5640/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005641Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5642 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005643 // If blocks are disabled, emit an error.
5644 if (!LangOpts.Blocks)
5645 Diag(CaretLoc, diag::err_blocks_disable);
5646
Steve Naroff52a81c02008-09-03 18:15:37 +00005647 // Ensure that CurBlock is deleted.
5648 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005649
Steve Naroff52059382008-10-10 01:28:17 +00005650 PopDeclContext();
5651
Steve Naroff52a81c02008-09-03 18:15:37 +00005652 // Pop off CurBlock, handle nested blocks.
5653 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005654
Steve Naroff52a81c02008-09-03 18:15:37 +00005655 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005656 if (!BSI->ReturnType.isNull())
5657 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005658
Steve Naroff52a81c02008-09-03 18:15:37 +00005659 llvm::SmallVector<QualType, 8> ArgTypes;
5660 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5661 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005662
Mike Stump8e288f42009-07-28 22:04:01 +00005663 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005664 QualType BlockTy;
5665 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005666 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5667 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005668 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005669 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005670 BSI->isVariadic, 0, false, false, 0, 0,
5671 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005672
Eli Friedman2b128322009-03-23 00:24:07 +00005673 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005674 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005675 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005676
Chris Lattnere7765e12009-04-19 05:28:12 +00005677 // If needed, diagnose invalid gotos and switches in the block.
5678 if (CurFunctionNeedsScopeChecking)
5679 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5680 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5681
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005682 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005683 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005684 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5685 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005686}
5687
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005688Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5689 ExprArg expr, TypeTy *type,
5690 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005691 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005692 Expr *E = static_cast<Expr*>(expr.get());
5693 Expr *OrigExpr = E;
5694
Anders Carlsson36760332007-10-15 20:28:48 +00005695 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005696
5697 // Get the va_list type
5698 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005699 if (VaListType->isArrayType()) {
5700 // Deal with implicit array decay; for example, on x86-64,
5701 // va_list is an array, but it's supposed to decay to
5702 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005703 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005704 // Make sure the input expression also decays appropriately.
5705 UsualUnaryConversions(E);
5706 } else {
5707 // Otherwise, the va_list argument must be an l-value because
5708 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005709 if (!E->isTypeDependent() &&
5710 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005711 return ExprError();
5712 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005713
Douglas Gregor25990972009-05-19 23:10:31 +00005714 if (!E->isTypeDependent() &&
5715 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005716 return ExprError(Diag(E->getLocStart(),
5717 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005718 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005719 }
Mike Stump9afab102009-02-19 03:04:26 +00005720
Eli Friedman2b128322009-03-23 00:24:07 +00005721 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005722 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005723
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005724 expr.release();
5725 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5726 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005727}
5728
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005729Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005730 // The type of __null will be int or long, depending on the size of
5731 // pointers on the target.
5732 QualType Ty;
5733 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5734 Ty = Context.IntTy;
5735 else
5736 Ty = Context.LongTy;
5737
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005738 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005739}
5740
Chris Lattner005ed752008-01-04 18:04:52 +00005741bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5742 SourceLocation Loc,
5743 QualType DstType, QualType SrcType,
5744 Expr *SrcExpr, const char *Flavor) {
5745 // Decode the result (notice that AST's are still created for extensions).
5746 bool isInvalid = false;
5747 unsigned DiagKind;
5748 switch (ConvTy) {
5749 default: assert(0 && "Unknown conversion type");
5750 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005751 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005752 DiagKind = diag::ext_typecheck_convert_pointer_int;
5753 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005754 case IntToPointer:
5755 DiagKind = diag::ext_typecheck_convert_int_pointer;
5756 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005757 case IncompatiblePointer:
5758 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5759 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005760 case IncompatiblePointerSign:
5761 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5762 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005763 case FunctionVoidPointer:
5764 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5765 break;
5766 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005767 // If the qualifiers lost were because we were applying the
5768 // (deprecated) C++ conversion from a string literal to a char*
5769 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5770 // Ideally, this check would be performed in
5771 // CheckPointerTypesForAssignment. However, that would require a
5772 // bit of refactoring (so that the second argument is an
5773 // expression, rather than a type), which should be done as part
5774 // of a larger effort to fix CheckPointerTypesForAssignment for
5775 // C++ semantics.
5776 if (getLangOptions().CPlusPlus &&
5777 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5778 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005779 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5780 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005781 case IntToBlockPointer:
5782 DiagKind = diag::err_int_to_block_pointer;
5783 break;
5784 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005785 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005786 break;
Steve Naroff19608432008-10-14 22:18:38 +00005787 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005788 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005789 // it can give a more specific diagnostic.
5790 DiagKind = diag::warn_incompatible_qualified_id;
5791 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005792 case IncompatibleVectors:
5793 DiagKind = diag::warn_incompatible_vectors;
5794 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005795 case Incompatible:
5796 DiagKind = diag::err_typecheck_convert_incompatible;
5797 isInvalid = true;
5798 break;
5799 }
Mike Stump9afab102009-02-19 03:04:26 +00005800
Chris Lattner271d4c22008-11-24 05:29:24 +00005801 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5802 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005803 return isInvalid;
5804}
Anders Carlssond5201b92008-11-30 19:50:32 +00005805
Chris Lattnereec8ae22009-04-25 21:59:05 +00005806bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005807 llvm::APSInt ICEResult;
5808 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5809 if (Result)
5810 *Result = ICEResult;
5811 return false;
5812 }
5813
Anders Carlssond5201b92008-11-30 19:50:32 +00005814 Expr::EvalResult EvalResult;
5815
Mike Stump9afab102009-02-19 03:04:26 +00005816 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005817 EvalResult.HasSideEffects) {
5818 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5819
5820 if (EvalResult.Diag) {
5821 // We only show the note if it's not the usual "invalid subexpression"
5822 // or if it's actually in a subexpression.
5823 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5824 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5825 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5826 }
Mike Stump9afab102009-02-19 03:04:26 +00005827
Anders Carlssond5201b92008-11-30 19:50:32 +00005828 return true;
5829 }
5830
Eli Friedmance329412009-04-25 22:26:58 +00005831 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5832 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005833
Eli Friedmance329412009-04-25 22:26:58 +00005834 if (EvalResult.Diag &&
5835 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5836 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005837
Anders Carlssond5201b92008-11-30 19:50:32 +00005838 if (Result)
5839 *Result = EvalResult.Val.getInt();
5840 return false;
5841}
Douglas Gregor98189262009-06-19 23:52:42 +00005842
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005843Sema::ExpressionEvaluationContext
5844Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5845 // Introduce a new set of potentially referenced declarations to the stack.
5846 if (NewContext == PotentiallyPotentiallyEvaluated)
5847 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5848
5849 std::swap(ExprEvalContext, NewContext);
5850 return NewContext;
5851}
5852
5853void
5854Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5855 ExpressionEvaluationContext NewContext) {
5856 ExprEvalContext = NewContext;
5857
5858 if (OldContext == PotentiallyPotentiallyEvaluated) {
5859 // Mark any remaining declarations in the current position of the stack
5860 // as "referenced". If they were not meant to be referenced, semantic
5861 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5862 PotentiallyReferencedDecls RemainingDecls;
5863 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5864 PotentiallyReferencedDeclStack.pop_back();
5865
5866 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5867 IEnd = RemainingDecls.end();
5868 I != IEnd; ++I)
5869 MarkDeclarationReferenced(I->first, I->second);
5870 }
5871}
Douglas Gregor98189262009-06-19 23:52:42 +00005872
5873/// \brief Note that the given declaration was referenced in the source code.
5874///
5875/// This routine should be invoke whenever a given declaration is referenced
5876/// in the source code, and where that reference occurred. If this declaration
5877/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5878/// C99 6.9p3), then the declaration will be marked as used.
5879///
5880/// \param Loc the location where the declaration was referenced.
5881///
5882/// \param D the declaration that has been referenced by the source code.
5883void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5884 assert(D && "No declaration?");
5885
Douglas Gregorcad27f62009-06-22 23:06:13 +00005886 if (D->isUsed())
5887 return;
5888
Douglas Gregor98189262009-06-19 23:52:42 +00005889 // Mark a parameter declaration "used", regardless of whether we're in a
5890 // template or not.
5891 if (isa<ParmVarDecl>(D))
5892 D->setUsed(true);
5893
5894 // Do not mark anything as "used" within a dependent context; wait for
5895 // an instantiation.
5896 if (CurContext->isDependentContext())
5897 return;
5898
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005899 switch (ExprEvalContext) {
5900 case Unevaluated:
5901 // We are in an expression that is not potentially evaluated; do nothing.
5902 return;
5903
5904 case PotentiallyEvaluated:
5905 // We are in a potentially-evaluated expression, so this declaration is
5906 // "used"; handle this below.
5907 break;
5908
5909 case PotentiallyPotentiallyEvaluated:
5910 // We are in an expression that may be potentially evaluated; queue this
5911 // declaration reference until we know whether the expression is
5912 // potentially evaluated.
5913 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5914 return;
5915 }
5916
Douglas Gregor98189262009-06-19 23:52:42 +00005917 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005918 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005919 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005920 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5921 if (!Constructor->isUsed())
5922 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005923 } else if (Constructor->isImplicit() &&
5924 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005925 if (!Constructor->isUsed())
5926 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5927 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005928 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5929 if (Destructor->isImplicit() && !Destructor->isUsed())
5930 DefineImplicitDestructor(Loc, Destructor);
5931
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005932 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5933 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5934 MethodDecl->getOverloadedOperator() == OO_Equal) {
5935 if (!MethodDecl->isUsed())
5936 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5937 }
5938 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00005939 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005940 // Implicit instantiation of function templates and member functions of
5941 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00005942 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005943 // FIXME: distinguish between implicit instantiations of function
5944 // templates and explicit specializations (the latter don't get
5945 // instantiated, naturally).
5946 if (Function->getInstantiatedFromMemberFunction() ||
5947 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00005948 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00005949 }
5950
5951
Douglas Gregor98189262009-06-19 23:52:42 +00005952 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00005953 Function->setUsed(true);
5954 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00005955 }
Douglas Gregor98189262009-06-19 23:52:42 +00005956
5957 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00005958 // Implicit instantiation of static data members of class templates.
5959 // FIXME: distinguish between implicit instantiations (which we need to
5960 // actually instantiate) and explicit specializations.
5961 if (Var->isStaticDataMember() &&
5962 Var->getInstantiatedFromStaticDataMember())
5963 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
5964
Douglas Gregor98189262009-06-19 23:52:42 +00005965 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00005966
Douglas Gregor98189262009-06-19 23:52:42 +00005967 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00005968 return;
5969}
Douglas Gregor98189262009-06-19 23:52:42 +00005970}
5971