blob: 2644c1d6f754629abba984daa13d9bb563f2c611 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000020#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
David Chisnall44663db2009-08-17 16:35:33 +000030
Douglas Gregoraa57e862009-02-18 21:56:37 +000031/// \brief Determine whether the use of this declaration is valid, and
32/// emit any corresponding diagnostics.
33///
34/// This routine diagnoses various problems with referencing
35/// declarations that can occur when using a declaration. For example,
36/// it might warn if a deprecated or unavailable declaration is being
37/// used, or produce an error (and return true) if a C++0x deleted
38/// function is being used.
39///
40/// \returns true if there was an error (this declaration cannot be
41/// referenced), false otherwise.
42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000043 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000044 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000045 // Implementing deprecated stuff requires referencing deprecated
46 // stuff. Don't warn if we are implementing a deprecated
47 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000048 bool isSilenced = false;
49
50 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
51 // If this reference happens *in* a deprecated function or method, don't
52 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000053 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000054
55 // If this is an Objective-C method implementation, check to see if the
56 // method was deprecated on the declaration, not the definition.
57 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
58 // The semantic decl context of a ObjCMethodDecl is the
59 // ObjCImplementationDecl.
60 if (ObjCImplementationDecl *Impl
61 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
62
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000063 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000064 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000065 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000066 }
67 }
68 }
69
70 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000071 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
72 }
73
Douglas Gregoraa57e862009-02-18 21:56:37 +000074 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000075 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000076 if (FD->isDeleted()) {
77 Diag(Loc, diag::err_deleted_function_use);
78 Diag(D->getLocation(), diag::note_unavailable_here) << true;
79 return true;
80 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000081 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000082
83 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000084 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000085 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000086 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
87 }
88
Douglas Gregoraa57e862009-02-18 21:56:37 +000089 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000090}
91
Fariborz Jahanian180f3412009-05-13 18:09:35 +000092/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
93/// (and other functions in future), which have been declared with sentinel
94/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
97 Expr **Args, unsigned NumArgs)
98{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000099 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000100 if (!attr)
101 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000102 int sentinelPos = attr->getSentinel();
103 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000104
Mike Stumpe127ae32009-05-16 07:39:55 +0000105 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
106 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000107 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000108 bool warnNotEnoughArgs = false;
109 int isMethod = 0;
110 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
111 // skip over named parameters.
112 ObjCMethodDecl::param_iterator P, E = MD->param_end();
113 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
114 if (nullPos)
115 --nullPos;
116 else
117 ++i;
118 }
119 warnNotEnoughArgs = (P != E || i >= NumArgs);
120 isMethod = 1;
Mike Stump90fc78e2009-08-04 21:02:39 +0000121 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000122 // skip over named parameters.
123 ObjCMethodDecl::param_iterator P, E = FD->param_end();
124 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
125 if (nullPos)
126 --nullPos;
127 else
128 ++i;
129 }
130 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump90fc78e2009-08-04 21:02:39 +0000131 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000132 // block or function pointer call.
133 QualType Ty = V->getType();
134 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
135 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000136 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
137 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000138 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
139 unsigned NumArgsInProto = Proto->getNumArgs();
140 unsigned k;
141 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
142 if (nullPos)
143 --nullPos;
144 else
145 ++i;
146 }
147 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
148 }
149 if (Ty->isBlockPointerType())
150 isMethod = 2;
Mike Stump90fc78e2009-08-04 21:02:39 +0000151 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000152 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000153 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000154 return;
155
156 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000157 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000158 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000159 return;
160 }
161 int sentinel = i;
162 while (sentinelPos > 0 && i < NumArgs-1) {
163 --sentinelPos;
164 ++i;
165 }
166 if (sentinelPos > 0) {
167 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000168 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000169 return;
170 }
171 while (i < NumArgs-1) {
172 ++i;
173 ++sentinel;
174 }
175 Expr *sentinelExpr = Args[sentinel];
176 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
177 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000178 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000179 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000180 }
181 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000182}
183
Douglas Gregor3bb30002009-02-26 21:00:50 +0000184SourceRange Sema::getExprRange(ExprTy *E) const {
185 Expr *Ex = (Expr *)E;
186 return Ex? Ex->getSourceRange() : SourceRange();
187}
188
Chris Lattner299b8842008-07-25 21:10:04 +0000189//===----------------------------------------------------------------------===//
190// Standard Promotions and Conversions
191//===----------------------------------------------------------------------===//
192
Chris Lattner299b8842008-07-25 21:10:04 +0000193/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
194void Sema::DefaultFunctionArrayConversion(Expr *&E) {
195 QualType Ty = E->getType();
196 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
197
Chris Lattner299b8842008-07-25 21:10:04 +0000198 if (Ty->isFunctionType())
Anders Carlssonb6feaf32009-09-01 20:37:18 +0000199 ImpCastExprToType(E, Context.getPointerType(Ty),
200 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000201 else if (Ty->isArrayType()) {
202 // In C90 mode, arrays only promote to pointers if the array expression is
203 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
204 // type 'array of type' is converted to an expression that has type 'pointer
205 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
206 // that has type 'array of type' ...". The relevant change is "an lvalue"
207 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000208 //
209 // C++ 4.2p1:
210 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
211 // T" can be converted to an rvalue of type "pointer to T".
212 //
213 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
214 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000215 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
216 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000217 }
Chris Lattner299b8842008-07-25 21:10:04 +0000218}
219
220/// UsualUnaryConversions - Performs various conversions that are common to most
221/// operators (C99 6.3). The conversions of array and function types are
222/// sometimes surpressed. For example, the array->pointer conversion doesn't
223/// apply if the array is an argument to the sizeof or address (&) operators.
224/// In these instances, this routine should *not* be called.
225Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
226 QualType Ty = Expr->getType();
227 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
228
Douglas Gregor70b307e2009-05-01 20:41:21 +0000229 // C99 6.3.1.1p2:
230 //
231 // The following may be used in an expression wherever an int or
232 // unsigned int may be used:
233 // - an object or expression with an integer type whose integer
234 // conversion rank is less than or equal to the rank of int
235 // and unsigned int.
236 // - A bit-field of type _Bool, int, signed int, or unsigned int.
237 //
238 // If an int can represent all values of the original type, the
239 // value is converted to an int; otherwise, it is converted to an
240 // unsigned int. These are called the integer promotions. All
241 // other types are unchanged by the integer promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000242 QualType PTy = Context.isPromotableBitField(Expr);
243 if (!PTy.isNull()) {
244 ImpCastExprToType(Expr, PTy);
245 return Expr;
246 }
Douglas Gregor70b307e2009-05-01 20:41:21 +0000247 if (Ty->isPromotableIntegerType()) {
Eli Friedman6ae7d112009-08-19 07:44:53 +0000248 QualType PT = Context.getPromotedIntegerType(Ty);
249 ImpCastExprToType(Expr, PT);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000250 return Expr;
Eli Friedman1931cc82009-08-20 04:21:42 +0000251 }
252
Douglas Gregor70b307e2009-05-01 20:41:21 +0000253 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000254 return Expr;
255}
256
Chris Lattner9305c3d2008-07-25 22:25:12 +0000257/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
258/// do not have a prototype. Arguments that have type float are promoted to
259/// double. All other argument types are converted by UsualUnaryConversions().
260void Sema::DefaultArgumentPromotion(Expr *&Expr) {
261 QualType Ty = Expr->getType();
262 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
263
264 // If this is a 'float' (CVR qualified or typedef) promote to double.
265 if (const BuiltinType *BT = Ty->getAsBuiltinType())
266 if (BT->getKind() == BuiltinType::Float)
267 return ImpCastExprToType(Expr, Context.DoubleTy);
268
269 UsualUnaryConversions(Expr);
270}
271
Chris Lattner81f00ed2009-04-12 08:11:20 +0000272/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
273/// will warn if the resulting type is not a POD type, and rejects ObjC
274/// interfaces passed by value. This returns true if the argument type is
275/// completely illegal.
276bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000277 DefaultArgumentPromotion(Expr);
278
Chris Lattner81f00ed2009-04-12 08:11:20 +0000279 if (Expr->getType()->isObjCInterfaceType()) {
280 Diag(Expr->getLocStart(),
281 diag::err_cannot_pass_objc_interface_to_vararg)
282 << Expr->getType() << CT;
283 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000284 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000285
286 if (!Expr->getType()->isPODType())
287 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
288 << Expr->getType() << CT;
289
290 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000291}
292
293
Chris Lattner299b8842008-07-25 21:10:04 +0000294/// UsualArithmeticConversions - Performs various conversions that are common to
295/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
296/// routine returns the first non-arithmetic type found. The client is
297/// responsible for emitting appropriate error diagnostics.
298/// FIXME: verify the conversion rules for "complex int" are consistent with
299/// GCC.
300QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
301 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000302 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000303 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000304
305 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000306
Chris Lattner299b8842008-07-25 21:10:04 +0000307 // For conversion purposes, we ignore any qualifiers.
308 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000309 QualType lhs =
310 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
311 QualType rhs =
312 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000313
314 // If both types are identical, no conversion is needed.
315 if (lhs == rhs)
316 return lhs;
317
318 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
319 // The caller can deal with this (e.g. pointer + int).
320 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
321 return lhs;
322
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000323 // Perform bitfield promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000324 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000325 if (!LHSBitfieldPromoteTy.isNull())
326 lhs = LHSBitfieldPromoteTy;
Eli Friedman1931cc82009-08-20 04:21:42 +0000327 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000328 if (!RHSBitfieldPromoteTy.isNull())
329 rhs = RHSBitfieldPromoteTy;
330
Eli Friedman6ae7d112009-08-19 07:44:53 +0000331 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000332 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000333 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000334 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000335 return destType;
336}
337
Chris Lattner299b8842008-07-25 21:10:04 +0000338//===----------------------------------------------------------------------===//
339// Semantic Analysis for various Expression Types
340//===----------------------------------------------------------------------===//
341
342
Steve Naroff87d58b42007-09-16 03:34:24 +0000343/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000344/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
345/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
346/// multiple tokens. However, the common case is that StringToks points to one
347/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000348///
349Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000350Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000351 assert(NumStringToks && "Must have at least one string!");
352
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000353 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000354 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000355 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000356
357 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
358 for (unsigned i = 0; i != NumStringToks; ++i)
359 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000360
Chris Lattnera6dcce32008-02-11 00:02:17 +0000361 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000362 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000363 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000364
365 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
366 if (getLangOptions().CPlusPlus)
367 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000368
Chris Lattnera6dcce32008-02-11 00:02:17 +0000369 // Get an array type for the string, according to C99 6.4.5. This includes
370 // the nul terminator character as well as the string length for pascal
371 // strings.
372 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000373 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000374 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000375
Chris Lattner4b009652007-07-25 00:24:17 +0000376 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000377 return Owned(StringLiteral::Create(Context, Literal.GetString(),
378 Literal.GetStringLength(),
379 Literal.AnyWide, StrTy,
380 &StringTokLocs[0],
381 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000382}
383
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000384/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
385/// CurBlock to VD should cause it to be snapshotted (as we do for auto
386/// variables defined outside the block) or false if this is not needed (e.g.
387/// for values inside the block or for globals).
388///
Chris Lattner0b464252009-04-21 22:26:47 +0000389/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
390/// up-to-date.
391///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000392static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
393 ValueDecl *VD) {
394 // If the value is defined inside the block, we couldn't snapshot it even if
395 // we wanted to.
396 if (CurBlock->TheDecl == VD->getDeclContext())
397 return false;
398
399 // If this is an enum constant or function, it is constant, don't snapshot.
400 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
401 return false;
402
403 // If this is a reference to an extern, static, or global variable, no need to
404 // snapshot it.
405 // FIXME: What about 'const' variables in C++?
406 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000407 if (!Var->hasLocalStorage())
408 return false;
409
410 // Blocks that have these can't be constant.
411 CurBlock->hasBlockDeclRefExprs = true;
412
413 // If we have nested blocks, the decl may be declared in an outer block (in
414 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
415 // be defined outside all of the current blocks (in which case the blocks do
416 // all get the bit). Walk the nesting chain.
417 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
418 NextBlock = NextBlock->PrevBlockInfo) {
419 // If we found the defining block for the variable, don't mark the block as
420 // having a reference outside it.
421 if (NextBlock->TheDecl == VD->getDeclContext())
422 break;
423
424 // Otherwise, the DeclRef from the inner block causes the outer one to need
425 // a snapshot as well.
426 NextBlock->hasBlockDeclRefExprs = true;
427 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000428
429 return true;
430}
431
432
433
Steve Naroff0acc9c92007-09-15 18:49:24 +0000434/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000435/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000436/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000437/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000438/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000439Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
440 IdentifierInfo &II,
441 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000442 const CXXScopeSpec *SS,
443 bool isAddressOfOperand) {
444 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000445 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000446}
447
Douglas Gregor566782a2009-01-06 05:10:23 +0000448/// BuildDeclRefExpr - Build either a DeclRefExpr or a
449/// QualifiedDeclRefExpr based on whether or not SS is a
450/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000451Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000452Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
453 bool TypeDependent, bool ValueDependent,
454 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000455 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
456 Diag(Loc,
457 diag::err_auto_variable_cannot_appear_in_own_initializer)
458 << D->getDeclName();
459 return ExprError();
460 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000461
462 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
463 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
464 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
465 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
466 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
467 << D->getIdentifier() << FD->getDeclName();
468 Diag(D->getLocation(), diag::note_local_variable_declared_here)
469 << D->getIdentifier();
470 return ExprError();
471 }
472 }
473 }
474 }
475
Douglas Gregor98189262009-06-19 23:52:42 +0000476 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000477
478 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000479 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000480 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
481 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000482 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000483 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000484 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
485
486 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000487}
488
Douglas Gregor723d3332009-01-07 00:43:41 +0000489/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
490/// variable corresponding to the anonymous union or struct whose type
491/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000492static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
493 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000494 assert(Record->isAnonymousStructOrUnion() &&
495 "Record must be an anonymous struct or union!");
496
Mike Stumpe127ae32009-05-16 07:39:55 +0000497 // FIXME: Once Decls are directly linked together, this will be an O(1)
498 // operation rather than a slow walk through DeclContext's vector (which
499 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000500 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000501 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
502 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000503 D != DEnd; ++D) {
504 if (*D == Record) {
505 // The object for the anonymous struct/union directly
506 // follows its type in the list of declarations.
507 ++D;
508 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000509 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000510 return *D;
511 }
512 }
513
514 assert(false && "Missing object for anonymous record");
515 return 0;
516}
517
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000518/// \brief Given a field that represents a member of an anonymous
519/// struct/union, build the path from that field's context to the
520/// actual member.
521///
522/// Construct the sequence of field member references we'll have to
523/// perform to get to the field in the anonymous union/struct. The
524/// list of members is built from the field outward, so traverse it
525/// backwards to go from an object in the current context to the field
526/// we found.
527///
528/// \returns The variable from which the field access should begin,
529/// for an anonymous struct/union that is not a member of another
530/// class. Otherwise, returns NULL.
531VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
532 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000533 assert(Field->getDeclContext()->isRecord() &&
534 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
535 && "Field must be stored inside an anonymous struct or union");
536
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000537 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000538 VarDecl *BaseObject = 0;
539 DeclContext *Ctx = Field->getDeclContext();
540 do {
541 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000542 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000543 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000544 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000545 else {
546 BaseObject = cast<VarDecl>(AnonObject);
547 break;
548 }
549 Ctx = Ctx->getParent();
550 } while (Ctx->isRecord() &&
551 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000552
553 return BaseObject;
554}
555
556Sema::OwningExprResult
557Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
558 FieldDecl *Field,
559 Expr *BaseObjectExpr,
560 SourceLocation OpLoc) {
561 llvm::SmallVector<FieldDecl *, 4> AnonFields;
562 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
563 AnonFields);
564
Douglas Gregor723d3332009-01-07 00:43:41 +0000565 // Build the expression that refers to the base object, from
566 // which we will build a sequence of member references to each
567 // of the anonymous union objects and, eventually, the field we
568 // found via name lookup.
569 bool BaseObjectIsPointer = false;
570 unsigned ExtraQuals = 0;
571 if (BaseObject) {
572 // BaseObject is an anonymous struct/union variable (and is,
573 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000574 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000575 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000576 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000577 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000578 ExtraQuals
579 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
580 } else if (BaseObjectExpr) {
581 // The caller provided the base object expression. Determine
582 // whether its a pointer and whether it adds any qualifiers to the
583 // anonymous struct/union fields we're looking into.
584 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000585 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000586 BaseObjectIsPointer = true;
587 ObjectType = ObjectPtr->getPointeeType();
588 }
589 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
590 } else {
591 // We've found a member of an anonymous struct/union that is
592 // inside a non-anonymous struct/union, so in a well-formed
593 // program our base object expression is "this".
594 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
595 if (!MD->isStatic()) {
596 QualType AnonFieldType
597 = Context.getTagDeclType(
598 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
599 QualType ThisType = Context.getTagDeclType(MD->getParent());
600 if ((Context.getCanonicalType(AnonFieldType)
601 == Context.getCanonicalType(ThisType)) ||
602 IsDerivedFrom(ThisType, AnonFieldType)) {
603 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000604 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000605 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000606 BaseObjectIsPointer = true;
607 }
608 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000609 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
610 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000611 }
612 ExtraQuals = MD->getTypeQualifiers();
613 }
614
615 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
617 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000618 }
619
620 // Build the implicit member references to the field of the
621 // anonymous struct/union.
622 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000623 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000624 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
625 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
626 FI != FIEnd; ++FI) {
627 QualType MemberType = (*FI)->getType();
628 if (!(*FI)->isMutable()) {
629 unsigned combinedQualifiers
630 = MemberType.getCVRQualifiers() | ExtraQuals;
631 MemberType = MemberType.getQualifiedType(combinedQualifiers);
632 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000633 if (BaseAddrSpace != MemberType.getAddressSpace())
634 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000635 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregore399ad42009-08-26 22:36:53 +0000636 // FIXME: Might this end up being a qualified name?
Steve Naroff774e4152009-01-21 00:14:39 +0000637 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
638 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000639 BaseObjectIsPointer = false;
640 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000641 }
642
Sebastian Redlcd883f72009-01-18 18:53:16 +0000643 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000644}
645
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000646/// ActOnDeclarationNameExpr - The parser has read some kind of name
647/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
648/// performs lookup on that name and returns an expression that refers
649/// to that name. This routine isn't directly called from the parser,
650/// because the parser doesn't know about DeclarationName. Rather,
651/// this routine is called by ActOnIdentifierExpr,
652/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
653/// which form the DeclarationName from the corresponding syntactic
654/// forms.
655///
656/// HasTrailingLParen indicates whether this identifier is used in a
657/// function call context. LookupCtx is only used for a C++
658/// qualified-id (foo::bar) to indicate the class or namespace that
659/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000660///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000661/// isAddressOfOperand means that this expression is the direct operand
662/// of an address-of operator. This matters because this is the only
663/// situation where a qualified name referencing a non-static member may
664/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000665Sema::OwningExprResult
666Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
667 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000668 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000669 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000670 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000671 if (SS && SS->isInvalid())
672 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000673
674 // C++ [temp.dep.expr]p3:
675 // An id-expression is type-dependent if it contains:
676 // -- a nested-name-specifier that contains a class-name that
677 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000678 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000679 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000680 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
681 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000682 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
683 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000684 }
685
Douglas Gregor411889e2009-02-13 23:20:09 +0000686 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
687 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000688
Sebastian Redlcd883f72009-01-18 18:53:16 +0000689 if (Lookup.isAmbiguous()) {
690 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
691 SS && SS->isSet() ? SS->getRange()
692 : SourceRange());
693 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000694 }
695
696 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000697
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000698 // If this reference is in an Objective-C method, then ivar lookup happens as
699 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000700 IdentifierInfo *II = Name.getAsIdentifierInfo();
701 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000702 // There are two cases to handle here. 1) scoped lookup could have failed,
703 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000704 // found a decl, but that decl is outside the current instance method (i.e.
705 // a global variable). In these two cases, we do a lookup for an ivar with
706 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000707 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000708 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000709 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000710 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000711 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000712 if (DiagnoseUseOfDecl(IV, Loc))
713 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000714
715 // If we're referencing an invalid decl, just return this as a silent
716 // error node. The error diagnostic was already emitted on the decl.
717 if (IV->isInvalidDecl())
718 return ExprError();
719
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000720 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
721 // If a class method attemps to use a free standing ivar, this is
722 // an error.
723 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
724 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
725 << IV->getDeclName());
726 // If a class method uses a global variable, even if an ivar with
727 // same name exists, use the global.
728 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000729 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
730 ClassDeclared != IFace)
731 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000732 // FIXME: This should use a new expr for a direct reference, don't
733 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000734 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000735 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
736 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000737 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000738 return Owned(new (Context)
739 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000740 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000741 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000742 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000743 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000744 // We should warn if a local variable hides an ivar.
745 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000746 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000747 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000748 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
749 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000750 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000751 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000752 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000753 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000754 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000755 QualType T;
756
757 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000758 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
759 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000760 else
761 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000762 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000763 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000764 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000765
Douglas Gregoraa57e862009-02-18 21:56:37 +0000766 // Determine whether this name might be a candidate for
767 // argument-dependent lookup.
768 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
769 HasTrailingLParen;
770
771 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000772 // We've seen something of the form
773 //
774 // identifier(
775 //
776 // and we did not find any entity by the name
777 // "identifier". However, this identifier is still subject to
778 // argument-dependent lookup, so keep track of the name.
779 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
780 Context.OverloadTy,
781 Loc));
782 }
783
Chris Lattner4b009652007-07-25 00:24:17 +0000784 if (D == 0) {
785 // Otherwise, this could be an implicitly declared function reference (legal
786 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000787 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000788 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000789 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000790 else {
791 // If this name wasn't predeclared and if this is not a function call,
792 // diagnose the problem.
Anders Carlsson4355a392009-08-30 00:54:35 +0000793 if (SS && !SS->isEmpty()) {
794 DiagnoseMissingMember(Loc, Name,
795 (NestedNameSpecifier *)SS->getScopeRep(),
796 SS->getRange());
797 return ExprError();
798 } else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000799 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000800 return ExprError(Diag(Loc, diag::err_undeclared_use)
801 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000802 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000803 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000804 }
805 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000806
807 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
808 // Warn about constructs like:
809 // if (void *X = foo()) { ... } else { X }.
810 // In the else block, the pointer is always false.
811
812 // FIXME: In a template instantiation, we don't have scope
813 // information to check this property.
814 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
815 Scope *CheckS = S;
816 while (CheckS) {
817 if (CheckS->isWithinElse() &&
818 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
819 if (Var->getType()->isBooleanType())
820 ExprError(Diag(Loc, diag::warn_value_always_false)
821 << Var->getDeclName());
822 else
823 ExprError(Diag(Loc, diag::warn_value_always_zero)
824 << Var->getDeclName());
825 break;
826 }
827
828 // Move up one more control parent to check again.
829 CheckS = CheckS->getControlParent();
830 if (CheckS)
831 CheckS = CheckS->getParent();
832 }
833 }
834 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
835 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
836 // C99 DR 316 says that, if a function type comes from a
837 // function definition (without a prototype), that type is only
838 // used for checking compatibility. Therefore, when referencing
839 // the function, we pretend that we don't have the full function
840 // type.
841 if (DiagnoseUseOfDecl(Func, Loc))
842 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000843
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000844 QualType T = Func->getType();
845 QualType NoProtoType = T;
846 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
847 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
848 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
849 }
850 }
851
852 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
853}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000854/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000855bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000856Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
857 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
858 if (CXXRecordDecl *RD =
859 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
860 QualType DestType =
861 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000862 if (DestType->isDependentType() || From->getType()->isDependentType())
863 return false;
864 QualType FromRecordType = From->getType();
865 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000866 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000867 DestType = Context.getPointerType(DestType);
868 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000869 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000870 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
871 CheckDerivedToBaseConversion(FromRecordType,
872 DestRecordType,
873 From->getSourceRange().getBegin(),
874 From->getSourceRange()))
875 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000876 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
877 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000878 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000879 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000880}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000881
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000882/// \brief Build a MemberExpr AST node.
Douglas Gregore399ad42009-08-26 22:36:53 +0000883static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
884 const CXXScopeSpec *SS, NamedDecl *Member,
885 SourceLocation Loc, QualType Ty) {
886 if (SS && SS->isSet())
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000887 return MemberExpr::Create(C, Base, isArrow,
888 (NestedNameSpecifier *)SS->getScopeRep(),
Douglas Gregord33e3282009-09-01 00:37:14 +0000889 SS->getRange(), Member, Loc,
890 // FIXME: Explicit template argument lists
891 false, SourceLocation(), 0, 0, SourceLocation(),
892 Ty);
Douglas Gregore399ad42009-08-26 22:36:53 +0000893
894 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
895}
896
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000897/// \brief Complete semantic analysis for a reference to the given declaration.
898Sema::OwningExprResult
899Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
900 bool HasTrailingLParen,
901 const CXXScopeSpec *SS,
902 bool isAddressOfOperand) {
903 assert(D && "Cannot refer to a NULL declaration");
904 DeclarationName Name = D->getDeclName();
905
Sebastian Redl0c9da212009-02-03 20:19:35 +0000906 // If this is an expression of the form &Class::member, don't build an
907 // implicit member ref, because we want a pointer to the member in general,
908 // not any specific instance's member.
909 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000910 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000911 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000912 QualType DType;
913 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
914 DType = FD->getType().getNonReferenceType();
915 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
916 DType = Method->getType();
917 } else if (isa<OverloadedFunctionDecl>(D)) {
918 DType = Context.OverloadTy;
919 }
920 // Could be an inner type. That's diagnosed below, so ignore it here.
921 if (!DType.isNull()) {
922 // The pointer is type- and value-dependent if it points into something
923 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000924 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000925 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000926 }
927 }
928 }
929
Douglas Gregor723d3332009-01-07 00:43:41 +0000930 // We may have found a field within an anonymous union or struct
931 // (C++ [class.union]).
932 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
933 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
934 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000935
Douglas Gregor3257fb52008-12-22 05:46:06 +0000936 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
937 if (!MD->isStatic()) {
938 // C++ [class.mfct.nonstatic]p2:
939 // [...] if name lookup (3.4.1) resolves the name in the
940 // id-expression to a nonstatic nontype member of class X or of
941 // a base class of X, the id-expression is transformed into a
942 // class member access expression (5.2.5) using (*this) (9.3.2)
943 // as the postfix-expression to the left of the '.' operator.
944 DeclContext *Ctx = 0;
945 QualType MemberType;
946 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
947 Ctx = FD->getDeclContext();
948 MemberType = FD->getType();
949
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000950 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000951 MemberType = RefType->getPointeeType();
952 else if (!FD->isMutable()) {
953 unsigned combinedQualifiers
954 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
955 MemberType = MemberType.getQualifiedType(combinedQualifiers);
956 }
957 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
958 if (!Method->isStatic()) {
959 Ctx = Method->getParent();
960 MemberType = Method->getType();
961 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000962 } else if (FunctionTemplateDecl *FunTmpl
963 = dyn_cast<FunctionTemplateDecl>(D)) {
964 if (CXXMethodDecl *Method
965 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
966 if (!Method->isStatic()) {
967 Ctx = Method->getParent();
968 MemberType = Context.OverloadTy;
969 }
970 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000971 } else if (OverloadedFunctionDecl *Ovl
972 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000973 // FIXME: We need an abstraction for iterating over one or more function
974 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000975 for (OverloadedFunctionDecl::function_iterator
976 Func = Ovl->function_begin(),
977 FuncEnd = Ovl->function_end();
978 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000979 CXXMethodDecl *DMethod = 0;
980 if (FunctionTemplateDecl *FunTmpl
981 = dyn_cast<FunctionTemplateDecl>(*Func))
982 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
983 else
984 DMethod = dyn_cast<CXXMethodDecl>(*Func);
985
986 if (DMethod && !DMethod->isStatic()) {
987 Ctx = DMethod->getDeclContext();
988 MemberType = Context.OverloadTy;
989 break;
990 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000991 }
992 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000993
994 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000995 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
996 QualType ThisType = Context.getTagDeclType(MD->getParent());
997 if ((Context.getCanonicalType(CtxType)
998 == Context.getCanonicalType(ThisType)) ||
999 IsDerivedFrom(ThisType, CtxType)) {
1000 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001001 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001002 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001003 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001004 if (PerformObjectMemberConversion(This, D))
1005 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001006 if (DiagnoseUseOfDecl(D, Loc))
1007 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00001008 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1009 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001010 }
1011 }
1012 }
1013 }
1014
Douglas Gregor8acb7272008-12-11 16:49:14 +00001015 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001016 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1017 if (MD->isStatic())
1018 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001019 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1020 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001021 }
1022
Douglas Gregor3257fb52008-12-22 05:46:06 +00001023 // Any other ways we could have found the field in a well-formed
1024 // program would have been turned into implicit member expressions
1025 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001026 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1027 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001028 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001029
Chris Lattner4b009652007-07-25 00:24:17 +00001030 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001031 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001032 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001034 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001035 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001036
Steve Naroffd6163f32008-09-05 22:11:13 +00001037 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001038 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001039 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1040 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001041 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001042 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1043 false, false, SS);
Anders Carlsson89908542009-08-29 01:06:32 +00001044 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
1045 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1046 /*TypeDependent=*/true,
1047 /*ValueDependent=*/true, SS);
1048
Steve Naroffd6163f32008-09-05 22:11:13 +00001049 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001050
Douglas Gregoraa57e862009-02-18 21:56:37 +00001051 // Check whether this declaration can be used. Note that we suppress
1052 // this check when we're going to perform argument-dependent lookup
1053 // on this function name, because this might not be the function
1054 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001055 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1056 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001057 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1058 return ExprError();
1059
Steve Naroffd6163f32008-09-05 22:11:13 +00001060 // Only create DeclRefExpr's for valid Decl's.
1061 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001062 return ExprError();
1063
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001064 // If the identifier reference is inside a block, and it refers to a value
1065 // that is outside the block, create a BlockDeclRefExpr instead of a
1066 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1067 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001068 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001069 // We do not do this for things like enum constants, global variables, etc,
1070 // as they do not get snapshotted.
1071 //
1072 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001073 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001074 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001075 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001076 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001077 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001078 // This is to record that a 'const' was actually synthesize and added.
1079 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001080 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001081
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001082 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001083 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1084 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001085 }
1086 // If this reference is not in a block or if the referenced variable is
1087 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001088
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001089 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001090 bool ValueDependent = false;
1091 if (getLangOptions().CPlusPlus) {
1092 // C++ [temp.dep.expr]p3:
1093 // An id-expression is type-dependent if it contains:
1094 // - an identifier that was declared with a dependent type,
1095 if (VD->getType()->isDependentType())
1096 TypeDependent = true;
1097 // - FIXME: a template-id that is dependent,
1098 // - a conversion-function-id that specifies a dependent type,
1099 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1100 Name.getCXXNameType()->isDependentType())
1101 TypeDependent = true;
1102 // - a nested-name-specifier that contains a class-name that
1103 // names a dependent type.
1104 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001105 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001106 DC; DC = DC->getParent()) {
1107 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001108 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001109 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1110 if (Context.getTypeDeclType(Record)->isDependentType()) {
1111 TypeDependent = true;
1112 break;
1113 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001114 }
1115 }
1116 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001117
Douglas Gregora5d84612008-12-10 20:57:37 +00001118 // C++ [temp.dep.constexpr]p2:
1119 //
1120 // An identifier is value-dependent if it is:
1121 // - a name declared with a dependent type,
1122 if (TypeDependent)
1123 ValueDependent = true;
1124 // - the name of a non-type template parameter,
1125 else if (isa<NonTypeTemplateParmDecl>(VD))
1126 ValueDependent = true;
1127 // - a constant with integral or enumeration type and is
1128 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001129 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1130 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1131 Dcl->getInit()) {
1132 ValueDependent = Dcl->getInit()->isValueDependent();
1133 }
1134 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001135 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001136
Anders Carlsson4571d812009-06-24 00:10:43 +00001137 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1138 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001139}
1140
Sebastian Redlcd883f72009-01-18 18:53:16 +00001141Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1142 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001143 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001144
Chris Lattner4b009652007-07-25 00:24:17 +00001145 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001146 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001147 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1148 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1149 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001150 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001151
Chris Lattner7e637512008-01-12 08:14:25 +00001152 // Pre-defined identifiers are of type char[x], where x is the length of the
1153 // string.
Anders Carlsson2c087d52009-09-08 18:24:21 +00001154
1155 Decl *currentDecl = getCurFunctionOrMethodDecl();
1156 if (!currentDecl) {
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001157 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2c087d52009-09-08 18:24:21 +00001158 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001159 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001160
Anders Carlsson2c087d52009-09-08 18:24:21 +00001161 unsigned Length =
1162 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001163
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001164 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001165 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001166 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001167 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001168}
1169
Sebastian Redlcd883f72009-01-18 18:53:16 +00001170Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001171 llvm::SmallString<16> CharBuffer;
1172 CharBuffer.resize(Tok.getLength());
1173 const char *ThisTokBegin = &CharBuffer[0];
1174 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001175
Chris Lattner4b009652007-07-25 00:24:17 +00001176 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1177 Tok.getLocation(), PP);
1178 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001179 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001180
1181 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1182
Sebastian Redl75324932009-01-20 22:23:13 +00001183 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1184 Literal.isWide(),
1185 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001186}
1187
Sebastian Redlcd883f72009-01-18 18:53:16 +00001188Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1189 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001190 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1191 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001192 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001193 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001194 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001195 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001196 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001197
Chris Lattner4b009652007-07-25 00:24:17 +00001198 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001199 // Add padding so that NumericLiteralParser can overread by one character.
1200 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001201 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001202
Chris Lattner4b009652007-07-25 00:24:17 +00001203 // Get the spelling of the token, which eliminates trigraphs, etc.
1204 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001205
Chris Lattner4b009652007-07-25 00:24:17 +00001206 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1207 Tok.getLocation(), PP);
1208 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001209 return ExprError();
1210
Chris Lattner1de66eb2007-08-26 03:42:43 +00001211 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001212
Chris Lattner1de66eb2007-08-26 03:42:43 +00001213 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001214 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001215 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001216 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001217 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001218 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001219 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001220 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001221
1222 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1223
Ted Kremenekddedbe22007-11-29 00:56:49 +00001224 // isExact will be set by GetFloatValue().
1225 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001226 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1227 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001228
Chris Lattner1de66eb2007-08-26 03:42:43 +00001229 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001230 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001231 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001232 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001233
Neil Booth7421e9c2007-08-29 22:00:19 +00001234 // long long is a C99 feature.
1235 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001236 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001237 Diag(Tok.getLocation(), diag::ext_longlong);
1238
Chris Lattner4b009652007-07-25 00:24:17 +00001239 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001240 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001241
Chris Lattner4b009652007-07-25 00:24:17 +00001242 if (Literal.GetIntegerValue(ResultVal)) {
1243 // If this value didn't fit into uintmax_t, warn and force to ull.
1244 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001245 Ty = Context.UnsignedLongLongTy;
1246 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001247 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001248 } else {
1249 // If this value fits into a ULL, try to figure out what else it fits into
1250 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001251
Chris Lattner4b009652007-07-25 00:24:17 +00001252 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1253 // be an unsigned int.
1254 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1255
1256 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001257 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001258 if (!Literal.isLong && !Literal.isLongLong) {
1259 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001260 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001261
Chris Lattner4b009652007-07-25 00:24:17 +00001262 // Does it fit in a unsigned int?
1263 if (ResultVal.isIntN(IntSize)) {
1264 // Does it fit in a signed int?
1265 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001266 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001267 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001268 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001269 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001270 }
Chris Lattner4b009652007-07-25 00:24:17 +00001271 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001272
Chris Lattner4b009652007-07-25 00:24:17 +00001273 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001274 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001275 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001276
Chris Lattner4b009652007-07-25 00:24:17 +00001277 // Does it fit in a unsigned long?
1278 if (ResultVal.isIntN(LongSize)) {
1279 // Does it fit in a signed long?
1280 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001281 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001282 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001283 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001284 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001285 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001286 }
1287
Chris Lattner4b009652007-07-25 00:24:17 +00001288 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001289 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001290 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001291
Chris Lattner4b009652007-07-25 00:24:17 +00001292 // Does it fit in a unsigned long long?
1293 if (ResultVal.isIntN(LongLongSize)) {
1294 // Does it fit in a signed long long?
1295 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001296 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001297 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001298 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001299 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001300 }
1301 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001302
Chris Lattner4b009652007-07-25 00:24:17 +00001303 // If we still couldn't decide a type, we probably have something that
1304 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001305 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001306 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001307 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001308 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001309 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001310
Chris Lattnere4068872008-05-09 05:59:00 +00001311 if (ResultVal.getBitWidth() != Width)
1312 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001313 }
Sebastian Redl75324932009-01-20 22:23:13 +00001314 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001315 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001316
Chris Lattner1de66eb2007-08-26 03:42:43 +00001317 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1318 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001319 Res = new (Context) ImaginaryLiteral(Res,
1320 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001321
1322 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001323}
1324
Sebastian Redlcd883f72009-01-18 18:53:16 +00001325Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1326 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001327 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001328 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001329 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001330}
1331
1332/// The UsualUnaryConversions() function is *not* called by this routine.
1333/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001334bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001335 SourceLocation OpLoc,
1336 const SourceRange &ExprRange,
1337 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001338 if (exprType->isDependentType())
1339 return false;
1340
Chris Lattner4b009652007-07-25 00:24:17 +00001341 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001342 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001343 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001344 if (isSizeof)
1345 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1346 return false;
1347 }
1348
Chris Lattner95933c12009-04-24 00:30:45 +00001349 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001350 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001351 Diag(OpLoc, diag::ext_sizeof_void_type)
1352 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001353 return false;
1354 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001355
Chris Lattner95933c12009-04-24 00:30:45 +00001356 if (RequireCompleteType(OpLoc, exprType,
1357 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssona21e7872009-08-26 23:45:07 +00001358 PDiag(diag::err_alignof_incomplete_type)
1359 << ExprRange))
Chris Lattner95933c12009-04-24 00:30:45 +00001360 return true;
1361
1362 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001363 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001364 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001365 << exprType << isSizeof << ExprRange;
1366 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001367 }
1368
Chris Lattner95933c12009-04-24 00:30:45 +00001369 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001370}
1371
Chris Lattner8d9f7962009-01-24 20:17:12 +00001372bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1373 const SourceRange &ExprRange) {
1374 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001375
Chris Lattner8d9f7962009-01-24 20:17:12 +00001376 // alignof decl is always ok.
1377 if (isa<DeclRefExpr>(E))
1378 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001379
1380 // Cannot know anything else if the expression is dependent.
1381 if (E->isTypeDependent())
1382 return false;
1383
Douglas Gregor531434b2009-05-02 02:18:30 +00001384 if (E->getBitField()) {
1385 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1386 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001387 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001388
1389 // Alignment of a field access is always okay, so long as it isn't a
1390 // bit-field.
1391 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001392 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001393 return false;
1394
Chris Lattner8d9f7962009-01-24 20:17:12 +00001395 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1396}
1397
Douglas Gregor396f1142009-03-13 21:01:28 +00001398/// \brief Build a sizeof or alignof expression given a type operand.
1399Action::OwningExprResult
1400Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1401 bool isSizeOf, SourceRange R) {
1402 if (T.isNull())
1403 return ExprError();
1404
1405 if (!T->isDependentType() &&
1406 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1407 return ExprError();
1408
1409 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1410 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1411 Context.getSizeType(), OpLoc,
1412 R.getEnd()));
1413}
1414
1415/// \brief Build a sizeof or alignof expression given an expression
1416/// operand.
1417Action::OwningExprResult
1418Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1419 bool isSizeOf, SourceRange R) {
1420 // Verify that the operand is valid.
1421 bool isInvalid = false;
1422 if (E->isTypeDependent()) {
1423 // Delay type-checking for type-dependent expressions.
1424 } else if (!isSizeOf) {
1425 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001426 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001427 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1428 isInvalid = true;
1429 } else {
1430 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1431 }
1432
1433 if (isInvalid)
1434 return ExprError();
1435
1436 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1437 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1438 Context.getSizeType(), OpLoc,
1439 R.getEnd()));
1440}
1441
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001442/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1443/// the same for @c alignof and @c __alignof
1444/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001445Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001446Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1447 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001448 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001449 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001450
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001451 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001452 // FIXME: Preserve type source info.
1453 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001454 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1455 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001456
Douglas Gregor396f1142009-03-13 21:01:28 +00001457 // Get the end location.
1458 Expr *ArgEx = (Expr *)TyOrEx;
1459 Action::OwningExprResult Result
1460 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1461
1462 if (Result.isInvalid())
1463 DeleteExpr(ArgEx);
1464
1465 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001466}
1467
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001468QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001469 if (V->isTypeDependent())
1470 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001471
Chris Lattnera16e42d2007-08-26 05:39:26 +00001472 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001473 if (const ComplexType *CT = V->getType()->getAsComplexType())
1474 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001475
1476 // Otherwise they pass through real integer and floating point types here.
1477 if (V->getType()->isArithmeticType())
1478 return V->getType();
1479
1480 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001481 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1482 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001483 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001484}
1485
1486
Chris Lattner4b009652007-07-25 00:24:17 +00001487
Sebastian Redl8b769972009-01-19 00:08:26 +00001488Action::OwningExprResult
1489Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1490 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001491 // Since this might be a postfix expression, get rid of ParenListExprs.
1492 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001493 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001494
Chris Lattner4b009652007-07-25 00:24:17 +00001495 UnaryOperator::Opcode Opc;
1496 switch (Kind) {
1497 default: assert(0 && "Unknown unary op!");
1498 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1499 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1500 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001501
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001502 if (getLangOptions().CPlusPlus &&
1503 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1504 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001505 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001506 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1507
1508 // C++ [over.inc]p1:
1509 //
1510 // [...] If the function is a member function with one
1511 // parameter (which shall be of type int) or a non-member
1512 // function with two parameters (the second of which shall be
1513 // of type int), it defines the postfix increment operator ++
1514 // for objects of that type. When the postfix increment is
1515 // called as a result of using the ++ operator, the int
1516 // argument will have value zero.
1517 Expr *Args[2] = {
1518 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001519 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1520 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001521 };
1522
1523 // Build the candidate set for overloading
1524 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001525 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001526
1527 // Perform overload resolution.
1528 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001529 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001530 case OR_Success: {
1531 // We found a built-in operator or an overloaded operator.
1532 FunctionDecl *FnDecl = Best->Function;
1533
1534 if (FnDecl) {
1535 // We matched an overloaded operator. Build a call to that
1536 // operator.
1537
1538 // Convert the arguments.
1539 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1540 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001541 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001542 } else {
1543 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001544 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001545 FnDecl->getParamDecl(0)->getType(),
1546 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001547 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001548 }
1549
1550 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001551 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001552 = FnDecl->getType()->getAsFunctionType()->getResultType();
1553 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001554
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001555 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001556 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001557 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001558 UsualUnaryConversions(FnExpr);
1559
Sebastian Redl8b769972009-01-19 00:08:26 +00001560 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001561 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001562 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1563 Args, 2, ResultTy,
1564 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001565 } else {
1566 // We matched a built-in operator. Convert the arguments, then
1567 // break out so that we will build the appropriate built-in
1568 // operator node.
1569 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1570 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001571 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001572
1573 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001574 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001575 }
1576
1577 case OR_No_Viable_Function:
1578 // No viable function; fall through to handling this as a
1579 // built-in operator, which will produce an error message for us.
1580 break;
1581
1582 case OR_Ambiguous:
1583 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1584 << UnaryOperator::getOpcodeStr(Opc)
1585 << Arg->getSourceRange();
1586 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001587 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001588
1589 case OR_Deleted:
1590 Diag(OpLoc, diag::err_ovl_deleted_oper)
1591 << Best->Function->isDeleted()
1592 << UnaryOperator::getOpcodeStr(Opc)
1593 << Arg->getSourceRange();
1594 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1595 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001596 }
1597
1598 // Either we found no viable overloaded operator or we matched a
1599 // built-in operator. In either case, fall through to trying to
1600 // build a built-in operation.
1601 }
1602
Eli Friedman94d30952009-07-22 23:24:42 +00001603 Input.release();
1604 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001605 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001606}
1607
Sebastian Redl8b769972009-01-19 00:08:26 +00001608Action::OwningExprResult
1609Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1610 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001611 // Since this might be a postfix expression, get rid of ParenListExprs.
1612 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1613
Sebastian Redl8b769972009-01-19 00:08:26 +00001614 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1615 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001616
Douglas Gregor80723c52008-11-19 17:17:41 +00001617 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001618 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1619 Base.release();
1620 Idx.release();
1621 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1622 Context.DependentTy, RLoc));
1623 }
1624
1625 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001626 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001627 LHSExp->getType()->isEnumeralType() ||
1628 RHSExp->getType()->isRecordType() ||
1629 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001630 // Add the appropriate overloaded operators (C++ [over.match.oper])
1631 // to the candidate set.
1632 OverloadCandidateSet CandidateSet;
1633 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001634 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1635 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001636
Douglas Gregor80723c52008-11-19 17:17:41 +00001637 // Perform overload resolution.
1638 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001639 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001640 case OR_Success: {
1641 // We found a built-in operator or an overloaded operator.
1642 FunctionDecl *FnDecl = Best->Function;
1643
1644 if (FnDecl) {
1645 // We matched an overloaded operator. Build a call to that
1646 // operator.
1647
1648 // Convert the arguments.
1649 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1650 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1651 PerformCopyInitialization(RHSExp,
1652 FnDecl->getParamDecl(0)->getType(),
1653 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001654 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001655 } else {
1656 // Convert the arguments.
1657 if (PerformCopyInitialization(LHSExp,
1658 FnDecl->getParamDecl(0)->getType(),
1659 "passing") ||
1660 PerformCopyInitialization(RHSExp,
1661 FnDecl->getParamDecl(1)->getType(),
1662 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001663 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001664 }
1665
1666 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001667 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001668 = FnDecl->getType()->getAsFunctionType()->getResultType();
1669 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001670
Douglas Gregor80723c52008-11-19 17:17:41 +00001671 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001672 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1673 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001674 UsualUnaryConversions(FnExpr);
1675
Sebastian Redl8b769972009-01-19 00:08:26 +00001676 Base.release();
1677 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001678 Args[0] = LHSExp;
1679 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001680 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1681 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001682 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001683 } else {
1684 // We matched a built-in operator. Convert the arguments, then
1685 // break out so that we will build the appropriate built-in
1686 // operator node.
1687 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1688 "passing") ||
1689 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1690 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001691 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001692
1693 break;
1694 }
1695 }
1696
1697 case OR_No_Viable_Function:
1698 // No viable function; fall through to handling this as a
1699 // built-in operator, which will produce an error message for us.
1700 break;
1701
1702 case OR_Ambiguous:
1703 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1704 << "[]"
1705 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1706 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001707 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001708
1709 case OR_Deleted:
1710 Diag(LLoc, diag::err_ovl_deleted_oper)
1711 << Best->Function->isDeleted()
1712 << "[]"
1713 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1714 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1715 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001716 }
1717
1718 // Either we found no viable overloaded operator or we matched a
1719 // built-in operator. In either case, fall through to trying to
1720 // build a built-in operation.
1721 }
1722
Chris Lattner4b009652007-07-25 00:24:17 +00001723 // Perform default conversions.
1724 DefaultFunctionArrayConversion(LHSExp);
1725 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001726
Chris Lattner4b009652007-07-25 00:24:17 +00001727 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1728
1729 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001730 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001731 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001732 // and index from the expression types.
1733 Expr *BaseExpr, *IndexExpr;
1734 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001735 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1736 BaseExpr = LHSExp;
1737 IndexExpr = RHSExp;
1738 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001739 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001740 BaseExpr = LHSExp;
1741 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001742 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001743 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001744 // Handle the uncommon case of "123[Ptr]".
1745 BaseExpr = RHSExp;
1746 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001747 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001748 } else if (const ObjCObjectPointerType *PTy =
1749 LHSTy->getAsObjCObjectPointerType()) {
1750 BaseExpr = LHSExp;
1751 IndexExpr = RHSExp;
1752 ResultType = PTy->getPointeeType();
1753 } else if (const ObjCObjectPointerType *PTy =
1754 RHSTy->getAsObjCObjectPointerType()) {
1755 // Handle the uncommon case of "123[Ptr]".
1756 BaseExpr = RHSExp;
1757 IndexExpr = LHSExp;
1758 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001759 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1760 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001761 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001762
Chris Lattner4b009652007-07-25 00:24:17 +00001763 // FIXME: need to deal with const...
1764 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001765 } else if (LHSTy->isArrayType()) {
1766 // If we see an array that wasn't promoted by
1767 // DefaultFunctionArrayConversion, it must be an array that
1768 // wasn't promoted because of the C90 rule that doesn't
1769 // allow promoting non-lvalue arrays. Warn, then
1770 // force the promotion here.
1771 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1772 LHSExp->getSourceRange();
1773 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1774 LHSTy = LHSExp->getType();
1775
1776 BaseExpr = LHSExp;
1777 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001778 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001779 } else if (RHSTy->isArrayType()) {
1780 // Same as previous, except for 123[f().a] case
1781 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1782 RHSExp->getSourceRange();
1783 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1784 RHSTy = RHSExp->getType();
1785
1786 BaseExpr = RHSExp;
1787 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001788 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001789 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001790 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1791 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001792 }
Chris Lattner4b009652007-07-25 00:24:17 +00001793 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001794 if (!(IndexExpr->getType()->isIntegerType() &&
1795 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001796 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1797 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001798
Douglas Gregor05e28f62009-03-24 19:52:54 +00001799 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1800 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1801 // type. Note that Functions are not objects, and that (in C99 parlance)
1802 // incomplete types are not object types.
1803 if (ResultType->isFunctionType()) {
1804 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1805 << ResultType << BaseExpr->getSourceRange();
1806 return ExprError();
1807 }
Chris Lattner95933c12009-04-24 00:30:45 +00001808
Douglas Gregor05e28f62009-03-24 19:52:54 +00001809 if (!ResultType->isDependentType() &&
Anders Carlssona21e7872009-08-26 23:45:07 +00001810 RequireCompleteType(LLoc, ResultType,
1811 PDiag(diag::err_subscript_incomplete_type)
1812 << BaseExpr->getSourceRange()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00001813 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001814
1815 // Diagnose bad cases where we step over interface counts.
1816 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1817 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1818 << ResultType << BaseExpr->getSourceRange();
1819 return ExprError();
1820 }
1821
Sebastian Redl8b769972009-01-19 00:08:26 +00001822 Base.release();
1823 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001824 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001825 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001826}
1827
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001828QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001829CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001830 const IdentifierInfo *CompName,
1831 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001832 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001833
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001834 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001835 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001836
Mike Stump9afab102009-02-19 03:04:26 +00001837 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001838 // special names that indicate a subset of exactly half the elements are
1839 // to be selected.
1840 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001841
Nate Begeman1486b502009-01-18 01:47:54 +00001842 // This flag determines whether or not CompName has an 's' char prefix,
1843 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001844 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001845
1846 // Check that we've found one of the special components, or that the component
1847 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001848 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001849 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1850 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001851 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001852 do
1853 compStr++;
1854 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001855 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001856 do
1857 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001858 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001859 }
Nate Begeman1486b502009-01-18 01:47:54 +00001860
Mike Stump9afab102009-02-19 03:04:26 +00001861 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001862 // We didn't get to the end of the string. This means the component names
1863 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001864 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1865 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001866 return QualType();
1867 }
Mike Stump9afab102009-02-19 03:04:26 +00001868
Nate Begeman1486b502009-01-18 01:47:54 +00001869 // Ensure no component accessor exceeds the width of the vector type it
1870 // operates on.
1871 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001872 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001873
1874 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001875 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001876
1877 while (*compStr) {
1878 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1879 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1880 << baseType << SourceRange(CompLoc);
1881 return QualType();
1882 }
1883 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001884 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001885
Nate Begeman1486b502009-01-18 01:47:54 +00001886 // If this is a halving swizzle, verify that the base type has an even
1887 // number of elements.
1888 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001889 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001890 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001891 return QualType();
1892 }
Mike Stump9afab102009-02-19 03:04:26 +00001893
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001894 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001895 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001896 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001897 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001898 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001899 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001900 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001901 if (HexSwizzle)
1902 CompSize--;
1903
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001904 if (CompSize == 1)
1905 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001906
Nate Begemanaf6ed502008-04-18 23:10:10 +00001907 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001908 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001909 // diagostics look bad. We want extended vector types to appear built-in.
1910 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1911 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1912 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001913 }
1914 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001915}
1916
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001917static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001918 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001919 const Selector &Sel,
1920 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001921
Anders Carlsson9935ab92009-08-26 18:25:21 +00001922 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001923 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001924 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001925 return OMD;
1926
1927 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1928 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001929 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1930 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001931 return D;
1932 }
1933 return 0;
1934}
1935
Steve Naroffc75c1a82009-06-17 22:40:22 +00001936static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001937 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001938 const Selector &Sel,
1939 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001940 // Check protocols on qualified interfaces.
1941 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001942 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001943 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001944 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001945 GDecl = PD;
1946 break;
1947 }
1948 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001949 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001950 GDecl = OMD;
1951 break;
1952 }
1953 }
1954 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001955 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001956 E = QIdTy->qual_end(); I != E; ++I) {
1957 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001958 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001959 if (GDecl)
1960 return GDecl;
1961 }
1962 }
1963 return GDecl;
1964}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001965
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001966/// FindMethodInNestedImplementations - Look up a method in current and
1967/// all base class implementations.
1968///
1969ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1970 const ObjCInterfaceDecl *IFace,
1971 const Selector &Sel) {
1972 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001973 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001974 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001975
1976 if (!Method && IFace->getSuperClass())
1977 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1978 return Method;
1979}
Douglas Gregore399ad42009-08-26 22:36:53 +00001980
Anders Carlsson9935ab92009-08-26 18:25:21 +00001981Action::OwningExprResult
1982Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001983 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001984 DeclarationName MemberName,
Douglas Gregord33e3282009-09-01 00:37:14 +00001985 bool HasExplicitTemplateArgs,
1986 SourceLocation LAngleLoc,
1987 const TemplateArgument *ExplicitTemplateArgs,
1988 unsigned NumExplicitTemplateArgs,
1989 SourceLocation RAngleLoc,
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00001990 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1991 NamedDecl *FirstQualifierInScope) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001992 if (SS && SS->isInvalid())
1993 return ExprError();
1994
Nate Begemane85f43d2009-08-10 23:49:36 +00001995 // Since this might be a postfix expression, get rid of ParenListExprs.
1996 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1997
Anders Carlssonc154a722009-05-01 19:30:39 +00001998 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregor3e368512009-09-04 17:36:40 +00001999 assert(BaseExpr && "no base expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00002000
Steve Naroff137e11d2007-12-16 21:42:28 +00002001 // Perform default conversions.
2002 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002003
Steve Naroff2cb66382007-07-26 03:11:44 +00002004 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00002005 // If this is an Objective-C pseudo-builtin and a definition is provided then
2006 // use that.
2007 if (BaseType->isObjCIdType()) {
2008 // We have an 'id' type. Rather than fall through, we check if this
2009 // is a reference to 'isa'.
2010 if (BaseType != Context.ObjCIdRedefinitionType) {
2011 BaseType = Context.ObjCIdRedefinitionType;
2012 ImpCastExprToType(BaseExpr, BaseType);
2013 }
2014 } else if (BaseType->isObjCClassType() &&
Douglas Gregorcfa0a632009-08-31 21:16:32 +00002015 BaseType != Context.ObjCClassRedefinitionType) {
David Chisnall44663db2009-08-17 16:35:33 +00002016 BaseType = Context.ObjCClassRedefinitionType;
2017 ImpCastExprToType(BaseExpr, BaseType);
2018 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002019 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002020
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002021 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2022 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002023 if (OpKind == tok::arrow) {
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002024 if (BaseType->isDependentType()) {
2025 NestedNameSpecifier *Qualifier = 0;
2026 if (SS) {
2027 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2028 if (!FirstQualifierInScope)
2029 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2030 }
2031
Douglas Gregorcc00fc02009-09-09 00:23:06 +00002032 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
2033 OpLoc, Qualifier,
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002034 SS? SS->getRange() : SourceRange(),
Douglas Gregorcc00fc02009-09-09 00:23:06 +00002035 FirstQualifierInScope,
2036 MemberName,
2037 MemberLoc,
2038 HasExplicitTemplateArgs,
2039 LAngleLoc,
2040 ExplicitTemplateArgs,
2041 NumExplicitTemplateArgs,
2042 RAngleLoc));
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002043 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002044 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002045 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002046 else if (BaseType->isObjCObjectPointerType())
2047 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002048 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002049 return ExprError(Diag(MemberLoc,
2050 diag::err_typecheck_member_reference_arrow)
2051 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002052 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002053 if (BaseType->isDependentType()) {
2054 // Require that the base type isn't a pointer type
2055 // (so we'll report an error for)
2056 // T* t;
2057 // t.f;
2058 //
2059 // In Obj-C++, however, the above expression is valid, since it could be
2060 // accessing the 'f' property if T is an Obj-C interface. The extra check
2061 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002062 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002063
2064 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002065 !PT->getPointeeType()->isRecordType())) {
2066 NestedNameSpecifier *Qualifier = 0;
2067 if (SS) {
2068 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2069 if (!FirstQualifierInScope)
2070 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2071 }
2072
Douglas Gregorcc00fc02009-09-09 00:23:06 +00002073 return Owned(CXXUnresolvedMemberExpr::Create(Context,
2074 BaseExpr, false,
2075 OpLoc,
2076 Qualifier,
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002077 SS? SS->getRange() : SourceRange(),
Douglas Gregorcc00fc02009-09-09 00:23:06 +00002078 FirstQualifierInScope,
2079 MemberName,
2080 MemberLoc,
2081 HasExplicitTemplateArgs,
2082 LAngleLoc,
2083 ExplicitTemplateArgs,
2084 NumExplicitTemplateArgs,
2085 RAngleLoc));
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002086 }
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002087 }
Chris Lattner4b009652007-07-25 00:24:17 +00002088 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002089
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002090 // Handle field access to simple records. This also handles access to fields
2091 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002092 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002093 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002094 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002095 PDiag(diag::err_typecheck_incomplete_tag)
2096 << BaseExpr->getSourceRange()))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002097 return ExprError();
2098
Douglas Gregorda61ad22009-08-06 03:17:00 +00002099 DeclContext *DC = RDecl;
2100 if (SS && SS->isSet()) {
2101 // If the member name was a qualified-id, look into the
2102 // nested-name-specifier.
2103 DC = computeDeclContext(*SS, false);
2104
2105 // FIXME: If DC is not computable, we should build a
2106 // CXXUnresolvedMemberExpr.
2107 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2108 }
2109
Steve Naroff2cb66382007-07-26 03:11:44 +00002110 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002111 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002112 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002113
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002114 if (!Result)
Anders Carlsson4355a392009-08-30 00:54:35 +00002115 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002116 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002117 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002118 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2119 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002120 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002121 }
2122
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002123 if (SS && SS->isSet()) {
2124 QualType BaseTypeCanon
2125 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2126 QualType MemberTypeCanon
2127 = Context.getCanonicalType(
2128 Context.getTypeDeclType(
2129 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2130
2131 if (BaseTypeCanon != MemberTypeCanon &&
2132 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2133 return ExprError(Diag(SS->getBeginLoc(),
2134 diag::err_not_direct_base_or_virtual)
2135 << MemberTypeCanon << BaseTypeCanon);
2136 }
2137
Chris Lattner84ad8332009-03-31 08:18:48 +00002138 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002139
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002140 // If the decl being referenced had an error, return an error for this
2141 // sub-expr without emitting another error, in order to avoid cascading
2142 // error cases.
2143 if (MemberDecl->isInvalidDecl())
2144 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002145
Douglas Gregoraa57e862009-02-18 21:56:37 +00002146 // Check the use of this field
2147 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2148 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002149
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002150 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002151 // We may have found a field within an anonymous union or struct
2152 // (C++ [class.union]).
2153 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002154 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002155 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002156
Douglas Gregor82d44772008-12-20 23:49:58 +00002157 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002158 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002159 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002160 MemberType = Ref->getPointeeType();
2161 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002162 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002163 unsigned combinedQualifiers =
2164 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002165 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002166 combinedQualifiers &= ~QualType::Const;
2167 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002168 if (BaseAddrSpace != MemberType.getAddressSpace())
2169 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002170 }
Eli Friedman76b49832008-02-06 22:48:16 +00002171
Douglas Gregorcad27f62009-06-22 23:06:13 +00002172 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002173 if (PerformObjectMemberConversion(BaseExpr, FD))
2174 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002175 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2176 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002177 }
2178
Douglas Gregorcad27f62009-06-22 23:06:13 +00002179 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2180 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002181 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2182 Var, MemberLoc,
2183 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002184 }
2185 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2186 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002187 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2188 MemberFn, MemberLoc,
2189 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002190 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002191 if (FunctionTemplateDecl *FunTmpl
2192 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2193 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregord33e3282009-09-01 00:37:14 +00002194
2195 if (HasExplicitTemplateArgs)
2196 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2197 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2198 SS? SS->getRange() : SourceRange(),
2199 FunTmpl, MemberLoc, true,
2200 LAngleLoc, ExplicitTemplateArgs,
2201 NumExplicitTemplateArgs, RAngleLoc,
2202 Context.OverloadTy));
2203
Douglas Gregore399ad42009-08-26 22:36:53 +00002204 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2205 FunTmpl, MemberLoc,
2206 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002207 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002208 if (OverloadedFunctionDecl *Ovl
Douglas Gregord33e3282009-09-01 00:37:14 +00002209 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2210 if (HasExplicitTemplateArgs)
2211 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2212 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2213 SS? SS->getRange() : SourceRange(),
2214 Ovl, MemberLoc, true,
2215 LAngleLoc, ExplicitTemplateArgs,
2216 NumExplicitTemplateArgs, RAngleLoc,
2217 Context.OverloadTy));
2218
Douglas Gregore399ad42009-08-26 22:36:53 +00002219 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2220 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregord33e3282009-09-01 00:37:14 +00002221 }
Douglas Gregorcad27f62009-06-22 23:06:13 +00002222 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2223 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002224 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2225 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002226 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002227 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002228 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002229 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002230
Douglas Gregor82d44772008-12-20 23:49:58 +00002231 // We found a declaration kind that we didn't expect. This is a
2232 // generic error message that tells the user that she can't refer
2233 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002234 return ExprError(Diag(MemberLoc,
2235 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002236 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002237 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002238
Douglas Gregor3e368512009-09-04 17:36:40 +00002239 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2240 // into a record type was handled above, any destructor we see here is a
2241 // pseudo-destructor.
2242 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2243 // C++ [expr.pseudo]p2:
2244 // The left hand side of the dot operator shall be of scalar type. The
2245 // left hand side of the arrow operator shall be of pointer to scalar
2246 // type.
2247 if (!BaseType->isScalarType())
2248 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2249 << BaseType << BaseExpr->getSourceRange());
2250
2251 // [...] The type designated by the pseudo-destructor-name shall be the
2252 // same as the object type.
2253 if (!MemberName.getCXXNameType()->isDependentType() &&
2254 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2255 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2256 << BaseType << MemberName.getCXXNameType()
2257 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
2258
2259 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
2260 // the form
2261 //
2262 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2263 //
2264 // shall designate the same scalar type.
2265 //
2266 // FIXME: DPG can't see any way to trigger this particular clause, so it
2267 // isn't checked here.
2268
2269 // FIXME: We've lost the precise spelling of the type by going through
2270 // DeclarationName. Can we do better?
2271 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
2272 OpKind == tok::arrow,
2273 OpLoc,
2274 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2275 SS? SS->getRange() : SourceRange(),
2276 MemberName.getCXXNameType(),
2277 MemberLoc));
2278 }
2279
Steve Naroff329ec222009-07-10 23:34:53 +00002280 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002281 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002282 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002283 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2284 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002285 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2286 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2287 ObjCMethodDecl *Getter;
2288 // FIXME: need to also look locally in the implementation.
2289 if ((Getter = IFace->lookupClassMethod(Sel))) {
2290 // Check the use of this method.
2291 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2292 return ExprError();
2293 }
2294 // If we found a getter then this may be a valid dot-reference, we
2295 // will look for the matching setter, in case it is needed.
2296 Selector SetterSel =
2297 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002298 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002299 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2300 if (!Setter) {
2301 // If this reference is in an @implementation, also check for 'private'
2302 // methods.
2303 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2304 }
2305 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002306 if (!Setter)
2307 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002308
2309 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2310 return ExprError();
2311
2312 if (Getter || Setter) {
2313 QualType PType;
2314
2315 if (Getter)
2316 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002317 else
2318 // Get the expression type from Setter's incoming parameter.
2319 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002320 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002321 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002322 Setter, MemberLoc, BaseExpr));
2323 }
2324 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002325 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002326 }
2327 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002328 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2329 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002330 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2331 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2332 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2333 const ObjCInterfaceType *IFaceT =
2334 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002335 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002336 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2337
Steve Naroff4e743962009-07-16 00:25:06 +00002338 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2339 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002340 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002341
2342 if (IV) {
2343 // If the decl being referenced had an error, return an error for this
2344 // sub-expr without emitting another error, in order to avoid cascading
2345 // error cases.
2346 if (IV->isInvalidDecl())
2347 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002348
Steve Naroff4e743962009-07-16 00:25:06 +00002349 // Check whether we can reference this field.
2350 if (DiagnoseUseOfDecl(IV, MemberLoc))
2351 return ExprError();
2352 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2353 IV->getAccessControl() != ObjCIvarDecl::Package) {
2354 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2355 if (ObjCMethodDecl *MD = getCurMethodDecl())
2356 ClassOfMethodDecl = MD->getClassInterface();
2357 else if (ObjCImpDecl && getCurFunctionDecl()) {
2358 // Case of a c-function declared inside an objc implementation.
2359 // FIXME: For a c-style function nested inside an objc implementation
2360 // class, there is no implementation context available, so we pass
2361 // down the context as argument to this routine. Ideally, this context
2362 // need be passed down in the AST node and somehow calculated from the
2363 // AST for a function decl.
2364 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2365 if (ObjCImplementationDecl *IMPD =
2366 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2367 ClassOfMethodDecl = IMPD->getClassInterface();
2368 else if (ObjCCategoryImplDecl* CatImplClass =
2369 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2370 ClassOfMethodDecl = CatImplClass->getClassInterface();
2371 }
2372
2373 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2374 if (ClassDeclared != IDecl ||
2375 ClassOfMethodDecl != ClassDeclared)
2376 Diag(MemberLoc, diag::error_private_ivar_access)
2377 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002378 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2379 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002380 Diag(MemberLoc, diag::error_protected_ivar_access)
2381 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002382 }
Steve Naroff4e743962009-07-16 00:25:06 +00002383
2384 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2385 MemberLoc, BaseExpr,
2386 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002387 }
Steve Naroff4e743962009-07-16 00:25:06 +00002388 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002389 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002390 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002391 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002392 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002393 // Handle properties on 'id' and qualified "id".
2394 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2395 BaseType->isObjCQualifiedIdType())) {
2396 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002397 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002398
Steve Naroff329ec222009-07-10 23:34:53 +00002399 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002400 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002401 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2402 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2403 // Check the use of this declaration
2404 if (DiagnoseUseOfDecl(PD, MemberLoc))
2405 return ExprError();
2406
2407 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2408 MemberLoc, BaseExpr));
2409 }
2410 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2411 // Check the use of this method.
2412 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2413 return ExprError();
2414
2415 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2416 OMD->getResultType(),
2417 OMD, OpLoc, MemberLoc,
2418 NULL, 0));
2419 }
2420 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002421
Steve Naroff329ec222009-07-10 23:34:53 +00002422 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002423 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002424 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002425 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2426 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002427 const ObjCObjectPointerType *OPT;
2428 if (OpKind == tok::period &&
2429 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2430 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2431 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002432 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002433
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002434 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002435 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002436 // Check whether we can reference this property.
2437 if (DiagnoseUseOfDecl(PD, MemberLoc))
2438 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002439 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002440 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002441 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002442 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2443 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002444 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002445 MemberLoc, BaseExpr));
2446 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002447 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002448 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2449 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002450 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002451 // Check whether we can reference this property.
2452 if (DiagnoseUseOfDecl(PD, MemberLoc))
2453 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002454
Steve Naroff774e4152009-01-21 00:14:39 +00002455 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002456 MemberLoc, BaseExpr));
2457 }
Steve Naroff329ec222009-07-10 23:34:53 +00002458 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2459 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002460 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002461 // Check whether we can reference this property.
2462 if (DiagnoseUseOfDecl(PD, MemberLoc))
2463 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002464
Steve Naroff329ec222009-07-10 23:34:53 +00002465 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2466 MemberLoc, BaseExpr));
2467 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002468 // If that failed, look for an "implicit" property by seeing if the nullary
2469 // selector is implemented.
2470
2471 // FIXME: The logic for looking up nullary and unary selectors should be
2472 // shared with the code in ActOnInstanceMessage.
2473
Anders Carlsson9935ab92009-08-26 18:25:21 +00002474 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002475 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002476
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002477 // If this reference is in an @implementation, check for 'private' methods.
2478 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002479 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002480
Steve Naroff04151f32008-10-22 19:16:27 +00002481 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002482 if (!Getter)
2483 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002484 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002485 // Check if we can reference this property.
2486 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2487 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002488 }
2489 // If we found a getter then this may be a valid dot-reference, we
2490 // will look for the matching setter, in case it is needed.
2491 Selector SetterSel =
2492 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002493 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002494 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002495 if (!Setter) {
2496 // If this reference is in an @implementation, also check for 'private'
2497 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002498 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002499 }
2500 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002501 if (!Setter)
2502 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002503
Steve Naroffdede0c92009-03-11 13:48:17 +00002504 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2505 return ExprError();
2506
2507 if (Getter || Setter) {
2508 QualType PType;
2509
2510 if (Getter)
2511 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002512 else
2513 // Get the expression type from Setter's incoming parameter.
2514 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002515 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002516 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002517 Setter, MemberLoc, BaseExpr));
2518 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002519 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002520 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002521 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002522
Steve Naroff29d293b2009-07-24 17:54:45 +00002523 // Handle the following exceptional case (*Obj).isa.
2524 if (OpKind == tok::period &&
2525 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002526 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002527 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2528 Context.getObjCIdType()));
2529
Chris Lattnera57cf472008-07-21 04:28:12 +00002530 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002531 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002532 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002533 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2534 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002535 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002536 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002537 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002538 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002539
Douglas Gregor762da552009-03-27 06:00:30 +00002540 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2541 << BaseType << BaseExpr->getSourceRange();
2542
2543 // If the user is trying to apply -> or . to a function or function
2544 // pointer, it's probably because they forgot parentheses to call
2545 // the function. Suggest the addition of those parentheses.
2546 if (BaseType == Context.OverloadTy ||
2547 BaseType->isFunctionType() ||
2548 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002549 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002550 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2551 Diag(Loc, diag::note_member_reference_needs_call)
2552 << CodeModificationHint::CreateInsertion(Loc, "()");
2553 }
2554
2555 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002556}
2557
Anders Carlsson9935ab92009-08-26 18:25:21 +00002558Action::OwningExprResult
2559Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2560 tok::TokenKind OpKind, SourceLocation MemberLoc,
2561 IdentifierInfo &Member,
2562 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2563 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2564 DeclarationName(&Member), ObjCImpDecl, SS);
2565}
2566
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002567Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2568 FunctionDecl *FD,
2569 ParmVarDecl *Param) {
2570 if (Param->hasUnparsedDefaultArg()) {
2571 Diag (CallLoc,
2572 diag::err_use_of_default_argument_to_function_declared_later) <<
2573 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2574 Diag(UnparsedDefaultArgLocs[Param],
2575 diag::note_default_argument_declared_here);
2576 } else {
2577 if (Param->hasUninstantiatedDefaultArg()) {
2578 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2579
2580 // Instantiate the expression.
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002581 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson21d18f22009-09-05 05:14:19 +00002582
2583 InstantiatingTemplate Inst(*this, CallLoc, Param,
2584 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002585 ArgList.getInnermost().flat_size());
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002586
John McCall0ba26ee2009-08-25 22:02:44 +00002587 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002588 if (Result.isInvalid())
2589 return ExprError();
2590
2591 if (SetParamDefaultArgument(Param, move(Result),
2592 /*FIXME:EqualLoc*/
2593 UninstExpr->getSourceRange().getBegin()))
2594 return ExprError();
2595 }
2596
2597 Expr *DefaultExpr = Param->getDefaultArg();
2598
2599 // If the default expression creates temporaries, we need to
2600 // push them to the current stack of expression temporaries so they'll
2601 // be properly destroyed.
2602 if (CXXExprWithTemporaries *E
2603 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2604 assert(!E->shouldDestroyTemporaries() &&
2605 "Can't destroy temporaries in a default argument expr!");
2606 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2607 ExprTemporaries.push_back(E->getTemporary(I));
2608 }
2609 }
2610
2611 // We already type-checked the argument, so we know it works.
2612 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2613}
2614
Douglas Gregor3257fb52008-12-22 05:46:06 +00002615/// ConvertArgumentsForCall - Converts the arguments specified in
2616/// Args/NumArgs to the parameter types of the function FDecl with
2617/// function prototype Proto. Call is the call expression itself, and
2618/// Fn is the function expression. For a C++ member function, this
2619/// routine does not attempt to convert the object argument. Returns
2620/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002621bool
2622Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002623 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002624 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002625 Expr **Args, unsigned NumArgs,
2626 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002627 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002628 // assignment, to the types of the corresponding parameter, ...
2629 unsigned NumArgsInProto = Proto->getNumArgs();
2630 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002631 bool Invalid = false;
2632
Douglas Gregor3257fb52008-12-22 05:46:06 +00002633 // If too few arguments are available (and we don't have default
2634 // arguments for the remaining parameters), don't make the call.
2635 if (NumArgs < NumArgsInProto) {
2636 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2637 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2638 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2639 // Use default arguments for missing arguments
2640 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002641 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002642 }
2643
2644 // If too many are passed and not variadic, error on the extras and drop
2645 // them.
2646 if (NumArgs > NumArgsInProto) {
2647 if (!Proto->isVariadic()) {
2648 Diag(Args[NumArgsInProto]->getLocStart(),
2649 diag::err_typecheck_call_too_many_args)
2650 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2651 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2652 Args[NumArgs-1]->getLocEnd());
2653 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002654 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002655 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002656 }
2657 NumArgsToCheck = NumArgsInProto;
2658 }
Mike Stump9afab102009-02-19 03:04:26 +00002659
Douglas Gregor3257fb52008-12-22 05:46:06 +00002660 // Continue to check argument types (even if we have too few/many args).
2661 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2662 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002663
Douglas Gregor3257fb52008-12-22 05:46:06 +00002664 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002665 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002666 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002667
Eli Friedman83dec9e2009-03-22 22:00:50 +00002668 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2669 ProtoArgType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002670 PDiag(diag::err_call_incomplete_argument)
2671 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002672 return true;
2673
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002674 // Pass the argument.
2675 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2676 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002677 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002678 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002679
2680 OwningExprResult ArgExpr =
2681 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2682 FDecl, Param);
2683 if (ArgExpr.isInvalid())
2684 return true;
2685
2686 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002687 }
2688
Douglas Gregor3257fb52008-12-22 05:46:06 +00002689 Call->setArg(i, Arg);
2690 }
Mike Stump9afab102009-02-19 03:04:26 +00002691
Douglas Gregor3257fb52008-12-22 05:46:06 +00002692 // If this is a variadic call, handle args passed through "...".
2693 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002694 VariadicCallType CallType = VariadicFunction;
2695 if (Fn->getType()->isBlockPointerType())
2696 CallType = VariadicBlock; // Block
2697 else if (isa<MemberExpr>(Fn))
2698 CallType = VariadicMethod;
2699
Douglas Gregor3257fb52008-12-22 05:46:06 +00002700 // Promote the arguments (C99 6.5.2.2p7).
2701 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2702 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002703 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002704 Call->setArg(i, Arg);
2705 }
2706 }
2707
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002708 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002709}
2710
Steve Naroff87d58b42007-09-16 03:34:24 +00002711/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002712/// This provides the location of the left/right parens and a list of comma
2713/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002714Action::OwningExprResult
2715Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2716 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002717 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002718 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002719
2720 // Since this might be a postfix expression, get rid of ParenListExprs.
2721 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2722
Anders Carlssonc154a722009-05-01 19:30:39 +00002723 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002724 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002725 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002726 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002727 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002728 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002729
Douglas Gregor3257fb52008-12-22 05:46:06 +00002730 if (getLangOptions().CPlusPlus) {
Douglas Gregor3e368512009-09-04 17:36:40 +00002731 // If this is a pseudo-destructor expression, build the call immediately.
2732 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2733 if (NumArgs > 0) {
2734 // Pseudo-destructor calls should not have any arguments.
2735 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2736 << CodeModificationHint::CreateRemoval(
2737 SourceRange(Args[0]->getLocStart(),
2738 Args[NumArgs-1]->getLocEnd()));
2739
2740 for (unsigned I = 0; I != NumArgs; ++I)
2741 Args[I]->Destroy(Context);
2742
2743 NumArgs = 0;
2744 }
2745
2746 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2747 RParenLoc));
2748 }
2749
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002750 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002751 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002752 // FIXME: Will need to cache the results of name lookup (including ADL) in
2753 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002754 bool Dependent = false;
2755 if (Fn->isTypeDependent())
2756 Dependent = true;
2757 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2758 Dependent = true;
2759
2760 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002761 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002762 Context.DependentTy, RParenLoc));
2763
2764 // Determine whether this is a call to an object (C++ [over.call.object]).
2765 if (Fn->getType()->isRecordType())
2766 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2767 CommaLocs, RParenLoc));
2768
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002769 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002770 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2771 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2772 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2773 isa<CXXMethodDecl>(MemDecl) ||
2774 (isa<FunctionTemplateDecl>(MemDecl) &&
2775 isa<CXXMethodDecl>(
2776 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002777 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2778 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002779 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002780 }
2781
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002782 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002783 // Also, in C++, keep track of whether we should perform argument-dependent
2784 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002785 Expr *FnExpr = Fn;
2786 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002787 bool HasExplicitTemplateArgs = 0;
2788 const TemplateArgument *ExplicitTemplateArgs = 0;
2789 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002790 while (true) {
2791 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2792 FnExpr = IcExpr->getSubExpr();
2793 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002794 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002795 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002796 ADL = false;
2797 FnExpr = PExpr->getSubExpr();
2798 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002799 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002800 == UnaryOperator::AddrOf) {
2801 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002802 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002803 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2804 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002805 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002806 break;
Mike Stump9afab102009-02-19 03:04:26 +00002807 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002808 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2809 UnqualifiedName = DepName->getName();
2810 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002811 } else if (TemplateIdRefExpr *TemplateIdRef
2812 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2813 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002814 if (!NDecl)
2815 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002816 HasExplicitTemplateArgs = true;
2817 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2818 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2819
2820 // C++ [temp.arg.explicit]p6:
2821 // [Note: For simple function names, argument dependent lookup (3.4.2)
2822 // applies even when the function name is not visible within the
2823 // scope of the call. This is because the call still has the syntactic
2824 // form of a function call (3.4.1). But when a function template with
2825 // explicit template arguments is used, the call does not have the
2826 // correct syntactic form unless there is a function template with
2827 // that name visible at the point of the call. If no such name is
2828 // visible, the call is not syntactically well-formed and
2829 // argument-dependent lookup does not apply. If some such name is
2830 // visible, argument dependent lookup applies and additional function
2831 // templates may be found in other namespaces.
2832 //
2833 // The summary of this paragraph is that, if we get to this point and the
2834 // template-id was not a qualified name, then argument-dependent lookup
2835 // is still possible.
2836 if (TemplateIdRef->getQualifier())
2837 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002838 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002839 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002840 // Any kind of name that does not refer to a declaration (or
2841 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2842 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002843 break;
2844 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002845 }
Mike Stump9afab102009-02-19 03:04:26 +00002846
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002847 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002848 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002849 if (NDecl) {
2850 FDecl = dyn_cast<FunctionDecl>(NDecl);
2851 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002852 FDecl = FunctionTemplate->getTemplatedDecl();
2853 else
Douglas Gregor28857752009-06-30 22:34:41 +00002854 FDecl = dyn_cast<FunctionDecl>(NDecl);
2855 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002856 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002857
Douglas Gregorb60eb752009-06-25 22:08:12 +00002858 if (Ovl || FunctionTemplate ||
2859 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002860 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002861 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002862 ADL = false;
2863
Douglas Gregorfcb19192009-02-11 23:02:49 +00002864 // We don't perform ADL in C.
2865 if (!getLangOptions().CPlusPlus)
2866 ADL = false;
2867
Douglas Gregorb60eb752009-06-25 22:08:12 +00002868 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002869 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2870 HasExplicitTemplateArgs,
2871 ExplicitTemplateArgs,
2872 NumExplicitTemplateArgs,
2873 LParenLoc, Args, NumArgs, CommaLocs,
2874 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002875 if (!FDecl)
2876 return ExprError();
2877
2878 // Update Fn to refer to the actual function selected.
2879 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002880 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002881 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002882 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2883 QDRExpr->getLocation(),
2884 false, false,
2885 QDRExpr->getQualifierRange(),
2886 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002887 else
Mike Stump9afab102009-02-19 03:04:26 +00002888 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002889 Fn->getSourceRange().getBegin());
2890 Fn->Destroy(Context);
2891 Fn = NewFn;
2892 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002893 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002894
2895 // Promote the function operand.
2896 UsualUnaryConversions(Fn);
2897
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002898 // Make the call expr early, before semantic checks. This guarantees cleanup
2899 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002900 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2901 Args, NumArgs,
2902 Context.BoolTy,
2903 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002904
Steve Naroffd6163f32008-09-05 22:11:13 +00002905 const FunctionType *FuncT;
2906 if (!Fn->getType()->isBlockPointerType()) {
2907 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2908 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002909 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002910 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002911 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2912 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002913 FuncT = PT->getPointeeType()->getAsFunctionType();
2914 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002915 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002916 getAsFunctionType();
2917 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002918 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002919 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2920 << Fn->getType() << Fn->getSourceRange());
2921
Eli Friedman83dec9e2009-03-22 22:00:50 +00002922 // Check for a valid return type
2923 if (!FuncT->getResultType()->isVoidType() &&
2924 RequireCompleteType(Fn->getSourceRange().getBegin(),
2925 FuncT->getResultType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002926 PDiag(diag::err_call_incomplete_return)
2927 << TheCall->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002928 return ExprError();
2929
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002930 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002931 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002932
Douglas Gregor4fa58902009-02-26 23:50:07 +00002933 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002934 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002935 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002936 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002937 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002938 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002939
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002940 if (FDecl) {
2941 // Check if we have too few/too many template arguments, based
2942 // on our knowledge of the function definition.
2943 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002944 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002945 const FunctionProtoType *Proto =
2946 Def->getType()->getAsFunctionProtoType();
2947 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2948 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2949 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2950 }
2951 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002952 }
2953
Steve Naroffdb65e052007-08-28 23:30:39 +00002954 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002955 for (unsigned i = 0; i != NumArgs; i++) {
2956 Expr *Arg = Args[i];
2957 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002958 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2959 Arg->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002960 PDiag(diag::err_call_incomplete_argument)
2961 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002962 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002963 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002964 }
Chris Lattner4b009652007-07-25 00:24:17 +00002965 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002966
Douglas Gregor3257fb52008-12-22 05:46:06 +00002967 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2968 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002969 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2970 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002971
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002972 // Check for sentinels
2973 if (NDecl)
2974 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002975
Chris Lattner2e64c072007-08-10 20:18:51 +00002976 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002977 if (FDecl) {
2978 if (CheckFunctionCall(FDecl, TheCall.get()))
2979 return ExprError();
2980
2981 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2982 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2983 } else if (NDecl) {
2984 if (CheckBlockCall(NDecl, TheCall.get()))
2985 return ExprError();
2986 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002987
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002988 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002989}
2990
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002991Action::OwningExprResult
2992Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2993 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002994 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002995 //FIXME: Preserve type source info.
2996 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002997 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002998 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002999 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00003000
Eli Friedman8c2173d2008-05-20 05:22:08 +00003001 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00003002 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003003 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3004 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00003005 } else if (!literalType->isDependentType() &&
3006 RequireCompleteType(LParenLoc, literalType,
Anders Carlssona21e7872009-08-26 23:45:07 +00003007 PDiag(diag::err_typecheck_decl_incomplete_type)
3008 << SourceRange(LParenLoc,
3009 literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003010 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00003011
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003012 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003013 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003014 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00003015
Chris Lattnere5cb5862008-12-04 23:50:19 +00003016 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00003017 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00003018 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003019 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00003020 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003021 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00003022 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00003023 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00003024}
3025
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003026Action::OwningExprResult
3027Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003028 SourceLocation RBraceLoc) {
3029 unsigned NumInit = initlist.size();
3030 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00003031
Steve Naroff0acc9c92007-09-15 18:49:24 +00003032 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00003033 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003034
Mike Stump9afab102009-02-19 03:04:26 +00003035 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00003036 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00003037 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003038 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00003039}
3040
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003041/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00003042bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003043 CastExpr::CastKind& Kind,
3044 CXXMethodDecl *& ConversionDecl,
3045 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00003046 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003047 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3048 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00003049
Eli Friedman01e0f652009-08-15 19:02:19 +00003050 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003051
3052 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3053 // type needs to be scalar.
3054 if (castType->isVoidType()) {
3055 // Cast to void allows any expr type.
3056 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003057 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3058 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3059 (castType->isStructureType() || castType->isUnionType())) {
3060 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00003061 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003062 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3063 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003064 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003065 } else if (castType->isUnionType()) {
3066 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003067 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003068 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003069 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003070 Field != FieldEnd; ++Field) {
3071 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3072 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3073 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3074 << castExpr->getSourceRange();
3075 break;
3076 }
3077 }
3078 if (Field == FieldEnd)
3079 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3080 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003081 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003082 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003083 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00003084 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003085 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003086 }
Mike Stump9afab102009-02-19 03:04:26 +00003087 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003088 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003089 return Diag(castExpr->getLocStart(),
3090 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003091 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003092 } else if (castType->isExtVectorType()) {
3093 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003094 return true;
3095 } else if (castType->isVectorType()) {
3096 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3097 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003098 } else if (castExpr->getType()->isVectorType()) {
3099 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3100 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003101 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003102 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003103 } else if (!castType->isArithmeticType()) {
3104 QualType castExprType = castExpr->getType();
3105 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3106 return Diag(castExpr->getLocStart(),
3107 diag::err_cast_pointer_from_non_pointer_int)
3108 << castExprType << castExpr->getSourceRange();
3109 } else if (!castExpr->getType()->isArithmeticType()) {
3110 if (!castType->isIntegralType() && castType->isArithmeticType())
3111 return Diag(castExpr->getLocStart(),
3112 diag::err_cast_pointer_to_non_pointer_int)
3113 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003114 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003115 if (isa<ObjCSelectorExpr>(castExpr))
3116 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003117 return false;
3118}
3119
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003120bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003121 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003122
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003123 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003124 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003125 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003126 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003127 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003128 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003129 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003130 } else
3131 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003132 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003133 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003134
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003135 return false;
3136}
3137
Nate Begemanbd42e022009-06-26 00:50:28 +00003138bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3139 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3140
Nate Begeman9e063702009-06-27 22:05:55 +00003141 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3142 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003143 if (SrcTy->isVectorType()) {
3144 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3145 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3146 << DestTy << SrcTy << R;
3147 return false;
3148 }
3149
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003150 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003151 // conversion will take place first from scalar to elt type, and then
3152 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003153 if (SrcTy->isPointerType())
3154 return Diag(R.getBegin(),
3155 diag::err_invalid_conversion_between_vector_and_scalar)
3156 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003157 return false;
3158}
3159
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003160Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003161Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003162 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003163 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3164
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003165 assert((Ty != 0) && (Op.get() != 0) &&
3166 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003167
Nate Begemane85f43d2009-08-10 23:49:36 +00003168 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003169 //FIXME: Preserve type source info.
3170 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003171
3172 // If the Expr being casted is a ParenListExpr, handle it specially.
3173 if (isa<ParenListExpr>(castExpr))
3174 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003175 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003176 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003177 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003178 return ExprError();
Fariborz Jahanianec172132009-08-29 19:15:16 +00003179 if (ConversionDecl) {
3180 // encounterred a c-style cast requiring a conversion function.
3181 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) {
3182 castExpr =
3183 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(),
3184 castType, LParenLoc,
3185 CastExpr::CK_UserDefinedConversion,
3186 castExpr, CD,
3187 RParenLoc);
3188 Kind = CastExpr::CK_UserDefinedConversion;
3189 }
3190 // FIXME. AST for when dealing with conversion functions (FunctionDecl).
3191 }
Nate Begemane85f43d2009-08-10 23:49:36 +00003192
3193 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003194 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003195 Kind, castExpr, castType,
3196 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003197}
3198
Nate Begemane85f43d2009-08-10 23:49:36 +00003199/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3200/// of comma binary operators.
3201Action::OwningExprResult
3202Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3203 Expr *expr = EA.takeAs<Expr>();
3204 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3205 if (!E)
3206 return Owned(expr);
3207
3208 OwningExprResult Result(*this, E->getExpr(0));
3209
3210 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3211 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3212 Owned(E->getExpr(i)));
3213
3214 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3215}
3216
3217Action::OwningExprResult
3218Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3219 SourceLocation RParenLoc, ExprArg Op,
3220 QualType Ty) {
3221 ParenListExpr *PE = (ParenListExpr *)Op.get();
3222
3223 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3224 // then handle it as such.
3225 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3226 if (PE->getNumExprs() == 0) {
3227 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3228 return ExprError();
3229 }
3230
3231 llvm::SmallVector<Expr *, 8> initExprs;
3232 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3233 initExprs.push_back(PE->getExpr(i));
3234
3235 // FIXME: This means that pretty-printing the final AST will produce curly
3236 // braces instead of the original commas.
3237 Op.release();
3238 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3239 initExprs.size(), RParenLoc);
3240 E->setType(Ty);
3241 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3242 Owned(E));
3243 } else {
3244 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3245 // sequence of BinOp comma operators.
3246 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3247 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3248 }
3249}
3250
3251Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3252 SourceLocation R,
3253 MultiExprArg Val) {
3254 unsigned nexprs = Val.size();
3255 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3256 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3257 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3258 return Owned(expr);
3259}
3260
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003261/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3262/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003263/// C99 6.5.15
3264QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3265 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003266 // C++ is sufficiently different to merit its own checker.
3267 if (getLangOptions().CPlusPlus)
3268 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3269
Chris Lattnere2897262009-02-18 04:28:32 +00003270 UsualUnaryConversions(Cond);
3271 UsualUnaryConversions(LHS);
3272 UsualUnaryConversions(RHS);
3273 QualType CondTy = Cond->getType();
3274 QualType LHSTy = LHS->getType();
3275 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003276
3277 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003278 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3279 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3280 << CondTy;
3281 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003282 }
Mike Stump9afab102009-02-19 03:04:26 +00003283
Chris Lattner992ae932008-01-06 22:42:25 +00003284 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003285 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3286 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003287
Chris Lattner992ae932008-01-06 22:42:25 +00003288 // If both operands have arithmetic type, do the usual arithmetic conversions
3289 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003290 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3291 UsualArithmeticConversions(LHS, RHS);
3292 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003293 }
Mike Stump9afab102009-02-19 03:04:26 +00003294
Chris Lattner992ae932008-01-06 22:42:25 +00003295 // If both operands are the same structure or union type, the result is that
3296 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003297 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3298 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003299 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003300 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003301 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003302 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003303 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003304 }
Mike Stump9afab102009-02-19 03:04:26 +00003305
Chris Lattner992ae932008-01-06 22:42:25 +00003306 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003307 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003308 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3309 if (!LHSTy->isVoidType())
3310 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3311 << RHS->getSourceRange();
3312 if (!RHSTy->isVoidType())
3313 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3314 << LHS->getSourceRange();
3315 ImpCastExprToType(LHS, Context.VoidTy);
3316 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003317 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003318 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003319 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3320 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003321 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003322 RHS->isNullPointerConstant(Context)) {
3323 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3324 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003325 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003326 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003327 LHS->isNullPointerConstant(Context)) {
3328 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3329 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003330 }
David Chisnall44663db2009-08-17 16:35:33 +00003331 // Handle things like Class and struct objc_class*. Here we case the result
3332 // to the pseudo-builtin, because that will be implicitly cast back to the
3333 // redefinition type if an attempt is made to access its fields.
3334 if (LHSTy->isObjCClassType() &&
3335 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3336 ImpCastExprToType(RHS, LHSTy);
3337 return LHSTy;
3338 }
3339 if (RHSTy->isObjCClassType() &&
3340 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3341 ImpCastExprToType(LHS, RHSTy);
3342 return RHSTy;
3343 }
3344 // And the same for struct objc_object* / id
3345 if (LHSTy->isObjCIdType() &&
3346 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3347 ImpCastExprToType(RHS, LHSTy);
3348 return LHSTy;
3349 }
3350 if (RHSTy->isObjCIdType() &&
3351 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3352 ImpCastExprToType(LHS, RHSTy);
3353 return RHSTy;
3354 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003355 // Handle block pointer types.
3356 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3357 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3358 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3359 QualType destType = Context.getPointerType(Context.VoidTy);
3360 ImpCastExprToType(LHS, destType);
3361 ImpCastExprToType(RHS, destType);
3362 return destType;
3363 }
3364 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3365 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3366 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003367 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003368 // We have 2 block pointer types.
3369 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3370 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003371 return LHSTy;
3372 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003373 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003374 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3375 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003376
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003377 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3378 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003379 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3380 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3381 // In this situation, we assume void* type. No especially good
3382 // reason, but this is what gcc does, and we do have to pick
3383 // to get a consistent AST.
3384 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3385 ImpCastExprToType(LHS, incompatTy);
3386 ImpCastExprToType(RHS, incompatTy);
3387 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003388 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003389 // The block pointer types are compatible.
3390 ImpCastExprToType(LHS, LHSTy);
3391 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003392 return LHSTy;
3393 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003394 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003395 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003396
3397 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3398 // Two identical object pointer types are always compatible.
3399 return LHSTy;
3400 }
Steve Naroff329ec222009-07-10 23:34:53 +00003401 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3402 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003403 QualType compositeType = LHSTy;
3404
3405 // If both operands are interfaces and either operand can be
3406 // assigned to the other, use that type as the composite
3407 // type. This allows
3408 // xxx ? (A*) a : (B*) b
3409 // where B is a subclass of A.
3410 //
3411 // Additionally, as for assignment, if either type is 'id'
3412 // allow silent coercion. Finally, if the types are
3413 // incompatible then make sure to use 'id' as the composite
3414 // type so the result is acceptable for sending messages to.
3415
3416 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3417 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003418 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003419 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003420 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003421 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003422 } else if ((LHSTy->isObjCQualifiedIdType() ||
3423 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003424 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003425 // Need to handle "id<xx>" explicitly.
3426 // GCC allows qualified id and any Objective-C type to devolve to
3427 // id. Currently localizing to here until clear this should be
3428 // part of ObjCQualifiedIdTypesAreCompatible.
3429 compositeType = Context.getObjCIdType();
3430 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003431 compositeType = Context.getObjCIdType();
3432 } else {
3433 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3434 << LHSTy << RHSTy
3435 << LHS->getSourceRange() << RHS->getSourceRange();
3436 QualType incompatTy = Context.getObjCIdType();
3437 ImpCastExprToType(LHS, incompatTy);
3438 ImpCastExprToType(RHS, incompatTy);
3439 return incompatTy;
3440 }
3441 // The object pointer types are compatible.
3442 ImpCastExprToType(LHS, compositeType);
3443 ImpCastExprToType(RHS, compositeType);
3444 return compositeType;
3445 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003446 // Check Objective-C object pointer types and 'void *'
3447 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003448 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003449 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3450 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3451 QualType destType = Context.getPointerType(destPointee);
3452 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3453 ImpCastExprToType(RHS, destType); // promote to void*
3454 return destType;
3455 }
3456 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3457 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003458 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003459 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3460 QualType destType = Context.getPointerType(destPointee);
3461 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3462 ImpCastExprToType(LHS, destType); // promote to void*
3463 return destType;
3464 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003465 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3466 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3467 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003468 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3469 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003470
3471 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3472 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3473 // Figure out necessary qualifiers (C99 6.5.15p6)
3474 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3475 QualType destType = Context.getPointerType(destPointee);
3476 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3477 ImpCastExprToType(RHS, destType); // promote to void*
3478 return destType;
3479 }
3480 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3481 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3482 QualType destType = Context.getPointerType(destPointee);
3483 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3484 ImpCastExprToType(RHS, destType); // promote to void*
3485 return destType;
3486 }
3487
3488 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3489 // Two identical pointer types are always compatible.
3490 return LHSTy;
3491 }
3492 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3493 rhptee.getUnqualifiedType())) {
3494 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3495 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3496 // In this situation, we assume void* type. No especially good
3497 // reason, but this is what gcc does, and we do have to pick
3498 // to get a consistent AST.
3499 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3500 ImpCastExprToType(LHS, incompatTy);
3501 ImpCastExprToType(RHS, incompatTy);
3502 return incompatTy;
3503 }
3504 // The pointer types are compatible.
3505 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3506 // differently qualified versions of compatible types, the result type is
3507 // a pointer to an appropriately qualified version of the *composite*
3508 // type.
3509 // FIXME: Need to calculate the composite type.
3510 // FIXME: Need to add qualifiers
3511 ImpCastExprToType(LHS, LHSTy);
3512 ImpCastExprToType(RHS, LHSTy);
3513 return LHSTy;
3514 }
3515
3516 // GCC compatibility: soften pointer/integer mismatch.
3517 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3518 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3519 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3520 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3521 return RHSTy;
3522 }
3523 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3524 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3525 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3526 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3527 return LHSTy;
3528 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003529
Chris Lattner992ae932008-01-06 22:42:25 +00003530 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003531 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3532 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003533 return QualType();
3534}
3535
Steve Naroff87d58b42007-09-16 03:34:24 +00003536/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003537/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003538Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3539 SourceLocation ColonLoc,
3540 ExprArg Cond, ExprArg LHS,
3541 ExprArg RHS) {
3542 Expr *CondExpr = (Expr *) Cond.get();
3543 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003544
3545 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3546 // was the condition.
3547 bool isLHSNull = LHSExpr == 0;
3548 if (isLHSNull)
3549 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003550
3551 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003552 RHSExpr, QuestionLoc);
3553 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003554 return ExprError();
3555
3556 Cond.release();
3557 LHS.release();
3558 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003559 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003560 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003561 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003562}
3563
Chris Lattner4b009652007-07-25 00:24:17 +00003564// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003565// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003566// routine is it effectively iqnores the qualifiers on the top level pointee.
3567// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3568// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003569Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003570Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3571 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003572
David Chisnall44663db2009-08-17 16:35:33 +00003573 if ((lhsType->isObjCClassType() &&
3574 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3575 (rhsType->isObjCClassType() &&
3576 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3577 return Compatible;
3578 }
3579
Chris Lattner4b009652007-07-25 00:24:17 +00003580 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003581 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3582 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003583
Chris Lattner4b009652007-07-25 00:24:17 +00003584 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003585 lhptee = Context.getCanonicalType(lhptee);
3586 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003587
Chris Lattner005ed752008-01-04 18:04:52 +00003588 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003589
3590 // C99 6.5.16.1p1: This following citation is common to constraints
3591 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3592 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003593 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003594 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003595 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003596
Mike Stump9afab102009-02-19 03:04:26 +00003597 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3598 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003599 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003600 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003601 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003602 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003603
Chris Lattner4ca3d772008-01-03 22:56:36 +00003604 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003605 assert(rhptee->isFunctionType());
3606 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003607 }
Mike Stump9afab102009-02-19 03:04:26 +00003608
Chris Lattner4ca3d772008-01-03 22:56:36 +00003609 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003610 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003611 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003612
3613 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003614 assert(lhptee->isFunctionType());
3615 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003616 }
Mike Stump9afab102009-02-19 03:04:26 +00003617 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003618 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003619 lhptee = lhptee.getUnqualifiedType();
3620 rhptee = rhptee.getUnqualifiedType();
3621 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3622 // Check if the pointee types are compatible ignoring the sign.
3623 // We explicitly check for char so that we catch "char" vs
3624 // "unsigned char" on systems where "char" is unsigned.
3625 if (lhptee->isCharType()) {
3626 lhptee = Context.UnsignedCharTy;
3627 } else if (lhptee->isSignedIntegerType()) {
3628 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3629 }
3630 if (rhptee->isCharType()) {
3631 rhptee = Context.UnsignedCharTy;
3632 } else if (rhptee->isSignedIntegerType()) {
3633 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3634 }
3635 if (lhptee == rhptee) {
3636 // Types are compatible ignoring the sign. Qualifier incompatibility
3637 // takes priority over sign incompatibility because the sign
3638 // warning can be disabled.
3639 if (ConvTy != Compatible)
3640 return ConvTy;
3641 return IncompatiblePointerSign;
3642 }
3643 // General pointer incompatibility takes priority over qualifiers.
3644 return IncompatiblePointer;
3645 }
Chris Lattner005ed752008-01-04 18:04:52 +00003646 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003647}
3648
Steve Naroff3454b6c2008-09-04 15:10:53 +00003649/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3650/// block pointer types are compatible or whether a block and normal pointer
3651/// are compatible. It is more restrict than comparing two function pointer
3652// types.
Mike Stump9afab102009-02-19 03:04:26 +00003653Sema::AssignConvertType
3654Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003655 QualType rhsType) {
3656 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003657
Steve Naroff3454b6c2008-09-04 15:10:53 +00003658 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003659 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3660 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003661
Steve Naroff3454b6c2008-09-04 15:10:53 +00003662 // make sure we operate on the canonical type
3663 lhptee = Context.getCanonicalType(lhptee);
3664 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003665
Steve Naroff3454b6c2008-09-04 15:10:53 +00003666 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003667
Steve Naroff3454b6c2008-09-04 15:10:53 +00003668 // For blocks we enforce that qualifiers are identical.
3669 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3670 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003671
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003672 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003673 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003674 return ConvTy;
3675}
3676
Mike Stump9afab102009-02-19 03:04:26 +00003677/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3678/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003679/// pointers. Here are some objectionable examples that GCC considers warnings:
3680///
3681/// int a, *pint;
3682/// short *pshort;
3683/// struct foo *pfoo;
3684///
3685/// pint = pshort; // warning: assignment from incompatible pointer type
3686/// a = pint; // warning: assignment makes integer from pointer without a cast
3687/// pint = a; // warning: assignment makes pointer from integer without a cast
3688/// pint = pfoo; // warning: assignment from incompatible pointer type
3689///
3690/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003691/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003692///
Chris Lattner005ed752008-01-04 18:04:52 +00003693Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003694Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003695 // Get canonical types. We're not formatting these types, just comparing
3696 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003697 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3698 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003699
3700 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003701 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003702
David Chisnall44663db2009-08-17 16:35:33 +00003703 if ((lhsType->isObjCClassType() &&
3704 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3705 (rhsType->isObjCClassType() &&
3706 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3707 return Compatible;
3708 }
3709
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003710 // If the left-hand side is a reference type, then we are in a
3711 // (rare!) case where we've allowed the use of references in C,
3712 // e.g., as a parameter type in a built-in function. In this case,
3713 // just make sure that the type referenced is compatible with the
3714 // right-hand side type. The caller is responsible for adjusting
3715 // lhsType so that the resulting expression does not have reference
3716 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003717 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003718 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003719 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003720 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003721 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003722 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3723 // to the same ExtVector type.
3724 if (lhsType->isExtVectorType()) {
3725 if (rhsType->isExtVectorType())
3726 return lhsType == rhsType ? Compatible : Incompatible;
3727 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3728 return Compatible;
3729 }
3730
Nate Begemanc5f0f652008-07-14 18:02:46 +00003731 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003732 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003733 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003734 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003735 if (getLangOptions().LaxVectorConversions &&
3736 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003737 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003738 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003739 }
3740 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003741 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003742
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003743 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003744 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003745
Chris Lattner390564e2008-04-07 06:49:41 +00003746 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003747 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003748 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003749
Chris Lattner390564e2008-04-07 06:49:41 +00003750 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003751 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003752
Steve Naroff8194a542009-07-20 17:56:53 +00003753 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003754 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003755 if (lhsType->isVoidPointerType()) // an exception to the rule.
3756 return Compatible;
3757 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003758 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003759 if (rhsType->getAs<BlockPointerType>()) {
3760 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003761 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003762
3763 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003764 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003765 return Compatible;
3766 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003767 return Incompatible;
3768 }
3769
3770 if (isa<BlockPointerType>(lhsType)) {
3771 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003772 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003773
Steve Naroffa982c712008-09-29 18:10:17 +00003774 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003775 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003776 return Compatible;
3777
Steve Naroff3454b6c2008-09-04 15:10:53 +00003778 if (rhsType->isBlockPointerType())
3779 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003780
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003781 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003782 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003783 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003784 }
Chris Lattner1853da22008-01-04 23:18:45 +00003785 return Incompatible;
3786 }
3787
Steve Naroff329ec222009-07-10 23:34:53 +00003788 if (isa<ObjCObjectPointerType>(lhsType)) {
3789 if (rhsType->isIntegerType())
3790 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003791
3792 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003793 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003794 if (rhsType->isVoidPointerType()) // an exception to the rule.
3795 return Compatible;
3796 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003797 }
3798 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003799 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3800 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003801 if (Context.typesAreCompatible(lhsType, rhsType))
3802 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003803 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3804 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003805 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003806 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003807 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003808 if (RHSPT->getPointeeType()->isVoidType())
3809 return Compatible;
3810 }
3811 // Treat block pointers as objects.
3812 if (rhsType->isBlockPointerType())
3813 return Compatible;
3814 return Incompatible;
3815 }
Chris Lattner390564e2008-04-07 06:49:41 +00003816 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003817 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003818 if (lhsType == Context.BoolTy)
3819 return Compatible;
3820
3821 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003822 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003823
Mike Stump9afab102009-02-19 03:04:26 +00003824 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003825 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003826
3827 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003828 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003829 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003830 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003831 }
Steve Naroff329ec222009-07-10 23:34:53 +00003832 if (isa<ObjCObjectPointerType>(rhsType)) {
3833 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3834 if (lhsType == Context.BoolTy)
3835 return Compatible;
3836
3837 if (lhsType->isIntegerType())
3838 return PointerToInt;
3839
Steve Naroff8194a542009-07-20 17:56:53 +00003840 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003841 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003842 if (lhsType->isVoidPointerType()) // an exception to the rule.
3843 return Compatible;
3844 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003845 }
3846 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003847 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003848 return Compatible;
3849 return Incompatible;
3850 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003851
Chris Lattner1853da22008-01-04 23:18:45 +00003852 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003853 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003854 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003855 }
3856 return Incompatible;
3857}
3858
Douglas Gregor144b06c2009-04-29 22:16:16 +00003859/// \brief Constructs a transparent union from an expression that is
3860/// used to initialize the transparent union.
3861static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3862 QualType UnionType, FieldDecl *Field) {
3863 // Build an initializer list that designates the appropriate member
3864 // of the transparent union.
3865 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3866 &E, 1,
3867 SourceLocation());
3868 Initializer->setType(UnionType);
3869 Initializer->setInitializedFieldInUnion(Field);
3870
3871 // Build a compound literal constructing a value of the transparent
3872 // union type from this initializer list.
3873 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3874 false);
3875}
3876
3877Sema::AssignConvertType
3878Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3879 QualType FromType = rExpr->getType();
3880
3881 // If the ArgType is a Union type, we want to handle a potential
3882 // transparent_union GCC extension.
3883 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003884 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003885 return Incompatible;
3886
3887 // The field to initialize within the transparent union.
3888 RecordDecl *UD = UT->getDecl();
3889 FieldDecl *InitField = 0;
3890 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003891 for (RecordDecl::field_iterator it = UD->field_begin(),
3892 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003893 it != itend; ++it) {
3894 if (it->getType()->isPointerType()) {
3895 // If the transparent union contains a pointer type, we allow:
3896 // 1) void pointer
3897 // 2) null pointer constant
3898 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003899 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003900 ImpCastExprToType(rExpr, it->getType());
3901 InitField = *it;
3902 break;
3903 }
3904
3905 if (rExpr->isNullPointerConstant(Context)) {
3906 ImpCastExprToType(rExpr, it->getType());
3907 InitField = *it;
3908 break;
3909 }
3910 }
3911
3912 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3913 == Compatible) {
3914 InitField = *it;
3915 break;
3916 }
3917 }
3918
3919 if (!InitField)
3920 return Incompatible;
3921
3922 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3923 return Compatible;
3924}
3925
Chris Lattner005ed752008-01-04 18:04:52 +00003926Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003927Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003928 if (getLangOptions().CPlusPlus) {
3929 if (!lhsType->isRecordType()) {
3930 // C++ 5.17p3: If the left operand is not of class type, the
3931 // expression is implicitly converted (C++ 4) to the
3932 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003933 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3934 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003935 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003936 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003937 }
3938
3939 // FIXME: Currently, we fall through and treat C++ classes like C
3940 // structures.
3941 }
3942
Steve Naroffcdee22d2007-11-27 17:58:44 +00003943 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3944 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003945 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003946 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003947 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003948 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003949 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003950 return Compatible;
3951 }
Mike Stump9afab102009-02-19 03:04:26 +00003952
Chris Lattner5f505bf2007-10-16 02:55:40 +00003953 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003954 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003955 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003956 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003957 //
Mike Stump9afab102009-02-19 03:04:26 +00003958 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003959 if (!lhsType->isReferenceType())
3960 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003961
Chris Lattner005ed752008-01-04 18:04:52 +00003962 Sema::AssignConvertType result =
3963 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003964
Steve Naroff0f32f432007-08-24 22:33:52 +00003965 // C99 6.5.16.1p2: The value of the right operand is converted to the
3966 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003967 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3968 // so that we can use references in built-in functions even in C.
3969 // The getNonReferenceType() call makes sure that the resulting expression
3970 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003971 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003972 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003973 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003974}
3975
Chris Lattner1eafdea2008-11-18 01:30:42 +00003976QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003977 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003978 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003979 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003980 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003981}
3982
Mike Stump9afab102009-02-19 03:04:26 +00003983inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003984 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003985 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003986 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003987 QualType lhsType =
3988 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3989 QualType rhsType =
3990 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003991
Nate Begemanc5f0f652008-07-14 18:02:46 +00003992 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003993 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003994 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003995
Nate Begemanc5f0f652008-07-14 18:02:46 +00003996 // Handle the case of a vector & extvector type of the same size and element
3997 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003998 if (getLangOptions().LaxVectorConversions) {
3999 // FIXME: Should we warn here?
4000 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00004001 if (const VectorType *RV = rhsType->getAsVectorType())
4002 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00004003 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00004004 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00004005 }
4006 }
4007 }
Mike Stump9afab102009-02-19 03:04:26 +00004008
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004009 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4010 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4011 bool swapped = false;
4012 if (rhsType->isExtVectorType()) {
4013 swapped = true;
4014 std::swap(rex, lex);
4015 std::swap(rhsType, lhsType);
4016 }
4017
Nate Begemanf1695892009-06-28 19:12:57 +00004018 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004019 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
4020 QualType EltTy = LV->getElementType();
4021 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4022 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00004023 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004024 if (swapped) std::swap(rex, lex);
4025 return lhsType;
4026 }
4027 }
4028 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4029 rhsType->isRealFloatingType()) {
4030 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00004031 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004032 if (swapped) std::swap(rex, lex);
4033 return lhsType;
4034 }
Nate Begemanec2d1062007-12-30 02:59:45 +00004035 }
4036 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004037
Nate Begemanf1695892009-06-28 19:12:57 +00004038 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00004039 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004040 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00004041 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004042 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00004043}
4044
Chris Lattner4b009652007-07-25 00:24:17 +00004045inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004046 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004047{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00004048 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004049 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004050
Steve Naroff8f708362007-08-24 19:07:16 +00004051 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004052
Chris Lattner4b009652007-07-25 00:24:17 +00004053 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00004054 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004055 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004056}
4057
4058inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004059 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004060{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00004061 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4062 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4063 return CheckVectorOperands(Loc, lex, rex);
4064 return InvalidOperands(Loc, lex, rex);
4065 }
Chris Lattner4b009652007-07-25 00:24:17 +00004066
Steve Naroff8f708362007-08-24 19:07:16 +00004067 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004068
Chris Lattner4b009652007-07-25 00:24:17 +00004069 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004070 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004071 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004072}
4073
4074inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00004075 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00004076{
Eli Friedman3cd92882009-03-28 01:22:36 +00004077 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4078 QualType compType = CheckVectorOperands(Loc, lex, rex);
4079 if (CompLHSTy) *CompLHSTy = compType;
4080 return compType;
4081 }
Chris Lattner4b009652007-07-25 00:24:17 +00004082
Eli Friedman3cd92882009-03-28 01:22:36 +00004083 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004084
Chris Lattner4b009652007-07-25 00:24:17 +00004085 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00004086 if (lex->getType()->isArithmeticType() &&
4087 rex->getType()->isArithmeticType()) {
4088 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004089 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004090 }
Chris Lattner4b009652007-07-25 00:24:17 +00004091
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004092 // Put any potential pointer into PExp
4093 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00004094 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004095 std::swap(PExp, IExp);
4096
Steve Naroff79ae19a2009-07-14 18:25:06 +00004097 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00004098
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004099 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00004100 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004101
Chris Lattner184f92d2009-04-24 23:50:08 +00004102 // Check for arithmetic on pointers to incomplete types.
4103 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004104 if (getLangOptions().CPlusPlus) {
4105 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00004106 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004107 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004108 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004109
4110 // GNU extension: arithmetic on pointer to void
4111 Diag(Loc, diag::ext_gnu_void_ptr)
4112 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00004113 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004114 if (getLangOptions().CPlusPlus) {
4115 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4116 << lex->getType() << lex->getSourceRange();
4117 return QualType();
4118 }
4119
4120 // GNU extension: arithmetic on pointer to function
4121 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4122 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004123 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004124 // Check if we require a complete type.
4125 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004126 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004127 PExp->getType()->isObjCObjectPointerType()) &&
4128 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004129 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4130 << PExp->getSourceRange()
4131 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00004132 return QualType();
4133 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004134 // Diagnose bad cases where we step over interface counts.
4135 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4136 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4137 << PointeeTy << PExp->getSourceRange();
4138 return QualType();
4139 }
4140
Eli Friedman3cd92882009-03-28 01:22:36 +00004141 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004142 QualType LHSTy = Context.isPromotableBitField(lex);
4143 if (LHSTy.isNull()) {
4144 LHSTy = lex->getType();
4145 if (LHSTy->isPromotableIntegerType())
4146 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004147 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004148 *CompLHSTy = LHSTy;
4149 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004150 return PExp->getType();
4151 }
4152 }
4153
Chris Lattner1eafdea2008-11-18 01:30:42 +00004154 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004155}
4156
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004157// C99 6.5.6
4158QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004159 SourceLocation Loc, QualType* CompLHSTy) {
4160 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4161 QualType compType = CheckVectorOperands(Loc, lex, rex);
4162 if (CompLHSTy) *CompLHSTy = compType;
4163 return compType;
4164 }
Mike Stump9afab102009-02-19 03:04:26 +00004165
Eli Friedman3cd92882009-03-28 01:22:36 +00004166 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004167
Chris Lattnerf6da2912007-12-09 21:53:25 +00004168 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004169
Chris Lattnerf6da2912007-12-09 21:53:25 +00004170 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004171 if (lex->getType()->isArithmeticType()
4172 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004173 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004174 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004175 }
Steve Naroff329ec222009-07-10 23:34:53 +00004176
Chris Lattnerf6da2912007-12-09 21:53:25 +00004177 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004178 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004179 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004180
Douglas Gregor05e28f62009-03-24 19:52:54 +00004181 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004182
Douglas Gregor05e28f62009-03-24 19:52:54 +00004183 bool ComplainAboutVoid = false;
4184 Expr *ComplainAboutFunc = 0;
4185 if (lpointee->isVoidType()) {
4186 if (getLangOptions().CPlusPlus) {
4187 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4188 << lex->getSourceRange() << rex->getSourceRange();
4189 return QualType();
4190 }
4191
4192 // GNU C extension: arithmetic on pointer to void
4193 ComplainAboutVoid = true;
4194 } else if (lpointee->isFunctionType()) {
4195 if (getLangOptions().CPlusPlus) {
4196 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004197 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004198 return QualType();
4199 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004200
4201 // GNU C extension: arithmetic on pointer to function
4202 ComplainAboutFunc = lex;
4203 } else if (!lpointee->isDependentType() &&
4204 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004205 PDiag(diag::err_typecheck_sub_ptr_object)
4206 << lex->getSourceRange()
4207 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004208 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004209
Chris Lattner184f92d2009-04-24 23:50:08 +00004210 // Diagnose bad cases where we step over interface counts.
4211 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4212 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4213 << lpointee << lex->getSourceRange();
4214 return QualType();
4215 }
4216
Chris Lattnerf6da2912007-12-09 21:53:25 +00004217 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004218 if (rex->getType()->isIntegerType()) {
4219 if (ComplainAboutVoid)
4220 Diag(Loc, diag::ext_gnu_void_ptr)
4221 << lex->getSourceRange() << rex->getSourceRange();
4222 if (ComplainAboutFunc)
4223 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4224 << ComplainAboutFunc->getType()
4225 << ComplainAboutFunc->getSourceRange();
4226
Eli Friedman3cd92882009-03-28 01:22:36 +00004227 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004228 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004229 }
Mike Stump9afab102009-02-19 03:04:26 +00004230
Chris Lattnerf6da2912007-12-09 21:53:25 +00004231 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004232 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004233 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004234
Douglas Gregor05e28f62009-03-24 19:52:54 +00004235 // RHS must be a completely-type object type.
4236 // Handle the GNU void* extension.
4237 if (rpointee->isVoidType()) {
4238 if (getLangOptions().CPlusPlus) {
4239 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4240 << lex->getSourceRange() << rex->getSourceRange();
4241 return QualType();
4242 }
Mike Stump9afab102009-02-19 03:04:26 +00004243
Douglas Gregor05e28f62009-03-24 19:52:54 +00004244 ComplainAboutVoid = true;
4245 } else if (rpointee->isFunctionType()) {
4246 if (getLangOptions().CPlusPlus) {
4247 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004248 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004249 return QualType();
4250 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004251
4252 // GNU extension: arithmetic on pointer to function
4253 if (!ComplainAboutFunc)
4254 ComplainAboutFunc = rex;
4255 } else if (!rpointee->isDependentType() &&
4256 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004257 PDiag(diag::err_typecheck_sub_ptr_object)
4258 << rex->getSourceRange()
4259 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004260 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004261
Eli Friedman143ddc92009-05-16 13:54:38 +00004262 if (getLangOptions().CPlusPlus) {
4263 // Pointee types must be the same: C++ [expr.add]
4264 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4265 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4266 << lex->getType() << rex->getType()
4267 << lex->getSourceRange() << rex->getSourceRange();
4268 return QualType();
4269 }
4270 } else {
4271 // Pointee types must be compatible C99 6.5.6p3
4272 if (!Context.typesAreCompatible(
4273 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4274 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4275 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4276 << lex->getType() << rex->getType()
4277 << lex->getSourceRange() << rex->getSourceRange();
4278 return QualType();
4279 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004280 }
Mike Stump9afab102009-02-19 03:04:26 +00004281
Douglas Gregor05e28f62009-03-24 19:52:54 +00004282 if (ComplainAboutVoid)
4283 Diag(Loc, diag::ext_gnu_void_ptr)
4284 << lex->getSourceRange() << rex->getSourceRange();
4285 if (ComplainAboutFunc)
4286 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4287 << ComplainAboutFunc->getType()
4288 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004289
4290 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004291 return Context.getPointerDiffType();
4292 }
4293 }
Mike Stump9afab102009-02-19 03:04:26 +00004294
Chris Lattner1eafdea2008-11-18 01:30:42 +00004295 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004296}
4297
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004298// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004299QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004300 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004301 // C99 6.5.7p2: Each of the operands shall have integer type.
4302 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004303 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004304
Chris Lattner2c8bff72007-12-12 05:47:28 +00004305 // Shifts don't perform usual arithmetic conversions, they just do integer
4306 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004307 QualType LHSTy = Context.isPromotableBitField(lex);
4308 if (LHSTy.isNull()) {
4309 LHSTy = lex->getType();
4310 if (LHSTy->isPromotableIntegerType())
4311 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004312 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004313 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004314 ImpCastExprToType(lex, LHSTy);
4315
Chris Lattner2c8bff72007-12-12 05:47:28 +00004316 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004317
Ryan Flynnf109fff2009-08-07 16:20:20 +00004318 // Sanity-check shift operands
4319 llvm::APSInt Right;
4320 // Check right/shifter operand
4321 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004322 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004323 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4324 else {
4325 llvm::APInt LeftBits(Right.getBitWidth(),
4326 Context.getTypeSize(lex->getType()));
4327 if (Right.uge(LeftBits))
4328 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4329 }
4330 }
4331
Chris Lattner2c8bff72007-12-12 05:47:28 +00004332 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004333 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004334}
4335
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004336// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004337QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004338 unsigned OpaqueOpc, bool isRelational) {
4339 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4340
Nate Begemanc5f0f652008-07-14 18:02:46 +00004341 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004342 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004343
Chris Lattner254f3bc2007-08-26 01:18:55 +00004344 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004345 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4346 UsualArithmeticConversions(lex, rex);
4347 else {
4348 UsualUnaryConversions(lex);
4349 UsualUnaryConversions(rex);
4350 }
Chris Lattner4b009652007-07-25 00:24:17 +00004351 QualType lType = lex->getType();
4352 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004353
Mike Stumpea3d74e2009-05-07 18:43:07 +00004354 if (!lType->isFloatingType()
4355 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004356 // For non-floating point types, check for self-comparisons of the form
4357 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4358 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004359 // NOTE: Don't warn about comparisons of enum constants. These can arise
4360 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004361 Expr *LHSStripped = lex->IgnoreParens();
4362 Expr *RHSStripped = rex->IgnoreParens();
4363 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4364 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004365 if (DRL->getDecl() == DRR->getDecl() &&
4366 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004367 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004368
4369 if (isa<CastExpr>(LHSStripped))
4370 LHSStripped = LHSStripped->IgnoreParenCasts();
4371 if (isa<CastExpr>(RHSStripped))
4372 RHSStripped = RHSStripped->IgnoreParenCasts();
4373
4374 // Warn about comparisons against a string constant (unless the other
4375 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004376 Expr *literalString = 0;
4377 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004378 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004379 !RHSStripped->isNullPointerConstant(Context)) {
4380 literalString = lex;
4381 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004382 } else if ((isa<StringLiteral>(RHSStripped) ||
4383 isa<ObjCEncodeExpr>(RHSStripped)) &&
4384 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004385 literalString = rex;
4386 literalStringStripped = RHSStripped;
4387 }
4388
4389 if (literalString) {
4390 std::string resultComparison;
4391 switch (Opc) {
4392 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4393 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4394 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4395 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4396 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4397 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4398 default: assert(false && "Invalid comparison operator");
4399 }
4400 Diag(Loc, diag::warn_stringcompare)
4401 << isa<ObjCEncodeExpr>(literalStringStripped)
4402 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004403 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4404 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4405 "strcmp(")
4406 << CodeModificationHint::CreateInsertion(
4407 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004408 resultComparison);
4409 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004410 }
Mike Stump9afab102009-02-19 03:04:26 +00004411
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004412 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004413 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004414
Chris Lattner254f3bc2007-08-26 01:18:55 +00004415 if (isRelational) {
4416 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004417 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004418 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004419 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004420 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004421 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004422 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004423 }
Mike Stump9afab102009-02-19 03:04:26 +00004424
Chris Lattner254f3bc2007-08-26 01:18:55 +00004425 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004426 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004427 }
Mike Stump9afab102009-02-19 03:04:26 +00004428
Chris Lattner22be8422007-08-26 01:10:14 +00004429 bool LHSIsNull = lex->isNullPointerConstant(Context);
4430 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004431
Chris Lattner254f3bc2007-08-26 01:18:55 +00004432 // All of the following pointer related warnings are GCC extensions, except
4433 // when handling null pointer constants. One day, we can consider making them
4434 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004435 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004436 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004437 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004438 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004439 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004440
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004441 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004442 if (LCanPointeeTy == RCanPointeeTy)
4443 return ResultTy;
4444
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004445 // C++ [expr.rel]p2:
4446 // [...] Pointer conversions (4.10) and qualification
4447 // conversions (4.4) are performed on pointer operands (or on
4448 // a pointer operand and a null pointer constant) to bring
4449 // them to their composite pointer type. [...]
4450 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004451 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004452 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004453 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004454 if (T.isNull()) {
4455 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4456 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4457 return QualType();
4458 }
4459
4460 ImpCastExprToType(lex, T);
4461 ImpCastExprToType(rex, T);
4462 return ResultTy;
4463 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004464 // C99 6.5.9p2 and C99 6.5.8p2
4465 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4466 RCanPointeeTy.getUnqualifiedType())) {
4467 // Valid unless a relational comparison of function pointers
4468 if (isRelational && LCanPointeeTy->isFunctionType()) {
4469 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4470 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4471 }
4472 } else if (!isRelational &&
4473 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4474 // Valid unless comparison between non-null pointer and function pointer
4475 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4476 && !LHSIsNull && !RHSIsNull) {
4477 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4478 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4479 }
4480 } else {
4481 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004482 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004483 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004484 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004485 if (LCanPointeeTy != RCanPointeeTy)
4486 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004487 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004488 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004489
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004490 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004491 // Comparison of pointers with null pointer constants and equality
4492 // comparisons of member pointers to null pointer constants.
4493 if (RHSIsNull &&
4494 (lType->isPointerType() ||
4495 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004496 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004497 return ResultTy;
4498 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004499 if (LHSIsNull &&
4500 (rType->isPointerType() ||
4501 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004502 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004503 return ResultTy;
4504 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004505
4506 // Comparison of member pointers.
4507 if (!isRelational &&
4508 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4509 // C++ [expr.eq]p2:
4510 // In addition, pointers to members can be compared, or a pointer to
4511 // member and a null pointer constant. Pointer to member conversions
4512 // (4.11) and qualification conversions (4.4) are performed to bring
4513 // them to a common type. If one operand is a null pointer constant,
4514 // the common type is the type of the other operand. Otherwise, the
4515 // common type is a pointer to member type similar (4.4) to the type
4516 // of one of the operands, with a cv-qualification signature (4.4)
4517 // that is the union of the cv-qualification signatures of the operand
4518 // types.
4519 QualType T = FindCompositePointerType(lex, rex);
4520 if (T.isNull()) {
4521 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4522 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4523 return QualType();
4524 }
4525
4526 ImpCastExprToType(lex, T);
4527 ImpCastExprToType(rex, T);
4528 return ResultTy;
4529 }
4530
4531 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004532 if (lType->isNullPtrType() && rType->isNullPtrType())
4533 return ResultTy;
4534 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004535
Steve Naroff3454b6c2008-09-04 15:10:53 +00004536 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004537 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004538 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4539 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004540
Steve Naroff3454b6c2008-09-04 15:10:53 +00004541 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004542 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004543 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004544 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004545 }
4546 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004547 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004548 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004549 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004550 if (!isRelational
4551 && ((lType->isBlockPointerType() && rType->isPointerType())
4552 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004553 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004554 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004555 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004556 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004557 ->getPointeeType()->isVoidType())))
4558 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4559 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004560 }
4561 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004562 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004563 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004564
Steve Naroff329ec222009-07-10 23:34:53 +00004565 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004566 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004567 const PointerType *LPT = lType->getAs<PointerType>();
4568 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004569 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004570 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004571 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004572 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004573
Steve Naroff030fcda2008-11-17 19:49:16 +00004574 if (!LPtrToVoid && !RPtrToVoid &&
4575 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004576 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004577 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004578 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004579 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004580 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004581 }
Steve Naroff329ec222009-07-10 23:34:53 +00004582 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004583 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004584 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4585 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004586 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004587 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004588 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004589 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004590 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004591 unsigned DiagID = 0;
4592 if (RHSIsNull) {
4593 if (isRelational)
4594 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4595 } else if (isRelational)
4596 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4597 else
4598 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4599
4600 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004601 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004602 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004603 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004604 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004605 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004606 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004607 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004608 unsigned DiagID = 0;
4609 if (LHSIsNull) {
4610 if (isRelational)
4611 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4612 } else if (isRelational)
4613 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4614 else
4615 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004616
Chris Lattner124569f2009-08-23 00:03:44 +00004617 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004618 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004619 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004620 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004621 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004622 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004623 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004624 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004625 if (!isRelational && RHSIsNull
4626 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004627 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004628 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004629 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004630 if (!isRelational && LHSIsNull
4631 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004632 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004633 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004634 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004635 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004636}
4637
Nate Begemanc5f0f652008-07-14 18:02:46 +00004638/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004639/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004640/// like a scalar comparison, a vector comparison produces a vector of integer
4641/// types.
4642QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004643 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004644 bool isRelational) {
4645 // Check to make sure we're operating on vectors of the same type and width,
4646 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004647 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004648 if (vType.isNull())
4649 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004650
Nate Begemanc5f0f652008-07-14 18:02:46 +00004651 QualType lType = lex->getType();
4652 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004653
Nate Begemanc5f0f652008-07-14 18:02:46 +00004654 // For non-floating point types, check for self-comparisons of the form
4655 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4656 // often indicate logic errors in the program.
4657 if (!lType->isFloatingType()) {
4658 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4659 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4660 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004661 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004662 }
Mike Stump9afab102009-02-19 03:04:26 +00004663
Nate Begemanc5f0f652008-07-14 18:02:46 +00004664 // Check for comparisons of floating point operands using != and ==.
4665 if (!isRelational && lType->isFloatingType()) {
4666 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004667 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004668 }
Mike Stump9afab102009-02-19 03:04:26 +00004669
Nate Begemanc5f0f652008-07-14 18:02:46 +00004670 // Return the type for the comparison, which is the same as vector type for
4671 // integer vectors, or an integer type of identical size and number of
4672 // elements for floating point vectors.
4673 if (lType->isIntegerType())
4674 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004675
Nate Begemanc5f0f652008-07-14 18:02:46 +00004676 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004677 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004678 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004679 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004680 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004681 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4682
Mike Stump9afab102009-02-19 03:04:26 +00004683 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004684 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004685 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4686}
4687
Chris Lattner4b009652007-07-25 00:24:17 +00004688inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004689 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004690{
4691 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004692 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004693
Steve Naroff8f708362007-08-24 19:07:16 +00004694 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004695
Chris Lattner4b009652007-07-25 00:24:17 +00004696 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004697 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004698 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004699}
4700
4701inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004702 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004703{
4704 UsualUnaryConversions(lex);
4705 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004706
Eli Friedmanbea3f842008-05-13 20:16:47 +00004707 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004708 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004709 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004710}
4711
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004712/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4713/// is a read-only property; return true if so. A readonly property expression
4714/// depends on various declarations and thus must be treated specially.
4715///
Mike Stump9afab102009-02-19 03:04:26 +00004716static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004717{
4718 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4719 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4720 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4721 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004722 if (const ObjCObjectPointerType *OPT =
4723 BaseType->getAsObjCInterfacePointerType())
4724 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4725 if (S.isPropertyReadonly(PDecl, IFace))
4726 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004727 }
4728 }
4729 return false;
4730}
4731
Chris Lattner4c2642c2008-11-18 01:22:49 +00004732/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4733/// emit an error and return true. If so, return false.
4734static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004735 SourceLocation OrigLoc = Loc;
4736 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4737 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004738 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4739 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004740 if (IsLV == Expr::MLV_Valid)
4741 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004742
Chris Lattner4c2642c2008-11-18 01:22:49 +00004743 unsigned Diag = 0;
4744 bool NeedType = false;
4745 switch (IsLV) { // C99 6.5.16p2
4746 default: assert(0 && "Unknown result from isModifiableLvalue!");
4747 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004748 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004749 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4750 NeedType = true;
4751 break;
Mike Stump9afab102009-02-19 03:04:26 +00004752 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004753 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4754 NeedType = true;
4755 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004756 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004757 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4758 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004759 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004760 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4761 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004762 case Expr::MLV_IncompleteType:
4763 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004764 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00004765 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4766 << E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004767 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004768 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4769 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004770 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004771 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4772 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004773 case Expr::MLV_ReadonlyProperty:
4774 Diag = diag::error_readonly_property_assignment;
4775 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004776 case Expr::MLV_NoSetterProperty:
4777 Diag = diag::error_nosetter_property_assignment;
4778 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004779 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004780
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004781 SourceRange Assign;
4782 if (Loc != OrigLoc)
4783 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004784 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004785 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004786 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004787 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004788 return true;
4789}
4790
4791
4792
4793// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004794QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4795 SourceLocation Loc,
4796 QualType CompoundType) {
4797 // Verify that LHS is a modifiable lvalue, and emit error if not.
4798 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004799 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004800
4801 QualType LHSType = LHS->getType();
4802 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004803
Chris Lattner005ed752008-01-04 18:04:52 +00004804 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004805 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004806 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004807 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004808 // Special case of NSObject attributes on c-style pointer types.
4809 if (ConvTy == IncompatiblePointer &&
4810 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004811 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004812 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004813 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004814 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004815
Chris Lattner34c85082008-08-21 18:04:13 +00004816 // If the RHS is a unary plus or minus, check to see if they = and + are
4817 // right next to each other. If so, the user may have typo'd "x =+ 4"
4818 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004819 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004820 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4821 RHSCheck = ICE->getSubExpr();
4822 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4823 if ((UO->getOpcode() == UnaryOperator::Plus ||
4824 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004825 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004826 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004827 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4828 // And there is a space or other character before the subexpr of the
4829 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004830 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4831 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004832 Diag(Loc, diag::warn_not_compound_assign)
4833 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4834 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004835 }
Chris Lattner34c85082008-08-21 18:04:13 +00004836 }
4837 } else {
4838 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004839 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004840 }
Chris Lattner005ed752008-01-04 18:04:52 +00004841
Chris Lattner1eafdea2008-11-18 01:30:42 +00004842 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4843 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004844 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004845
Chris Lattner4b009652007-07-25 00:24:17 +00004846 // C99 6.5.16p3: The type of an assignment expression is the type of the
4847 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004848 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004849 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4850 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004851 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004852 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004853 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004854}
4855
Chris Lattner1eafdea2008-11-18 01:30:42 +00004856// C99 6.5.17
4857QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004858 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004859 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004860
4861 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4862 // incomplete in C++).
4863
Chris Lattner1eafdea2008-11-18 01:30:42 +00004864 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004865}
4866
4867/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4868/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004869QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4870 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004871 if (Op->isTypeDependent())
4872 return Context.DependentTy;
4873
Chris Lattnere65182c2008-11-21 07:05:48 +00004874 QualType ResType = Op->getType();
4875 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004876
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004877 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4878 // Decrement of bool is not allowed.
4879 if (!isInc) {
4880 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4881 return QualType();
4882 }
4883 // Increment of bool sets it to true, but is deprecated.
4884 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4885 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004886 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004887 } else if (ResType->isAnyPointerType()) {
4888 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004889
Chris Lattnere65182c2008-11-21 07:05:48 +00004890 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004891 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004892 if (getLangOptions().CPlusPlus) {
4893 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4894 << Op->getSourceRange();
4895 return QualType();
4896 }
4897
4898 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004899 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004900 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004901 if (getLangOptions().CPlusPlus) {
4902 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4903 << Op->getType() << Op->getSourceRange();
4904 return QualType();
4905 }
4906
4907 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004908 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004909 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004910 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4911 << Op->getSourceRange()
4912 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004913 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004914 // Diagnose bad cases where we step over interface counts.
4915 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4916 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4917 << PointeeTy << Op->getSourceRange();
4918 return QualType();
4919 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004920 } else if (ResType->isComplexType()) {
4921 // C99 does not support ++/-- on complex types, we allow as an extension.
4922 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004923 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004924 } else {
4925 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004926 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004927 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004928 }
Mike Stump9afab102009-02-19 03:04:26 +00004929 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004930 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004931 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004932 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004933 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004934}
4935
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004936/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004937/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004938/// where the declaration is needed for type checking. We only need to
4939/// handle cases when the expression references a function designator
4940/// or is an lvalue. Here are some examples:
4941/// - &(x) => x
4942/// - &*****f => f for f a function designator.
4943/// - &s.xx => s
4944/// - &s.zz[1].yy -> s, if zz is an array
4945/// - *(x + 1) -> x, if x is an array
4946/// - &"123"[2] -> 0
4947/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004948static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004949 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004950 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004951 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004952 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004953 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004954 // If this is an arrow operator, the address is an offset from
4955 // the base's value, so the object the base refers to is
4956 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004957 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004958 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004959 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004960 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004961 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004962 // FIXME: This code shouldn't be necessary! We should catch the implicit
4963 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004964 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4965 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4966 if (ICE->getSubExpr()->getType()->isArrayType())
4967 return getPrimaryDecl(ICE->getSubExpr());
4968 }
4969 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004970 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004971 case Stmt::UnaryOperatorClass: {
4972 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004973
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004974 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004975 case UnaryOperator::Real:
4976 case UnaryOperator::Imag:
4977 case UnaryOperator::Extension:
4978 return getPrimaryDecl(UO->getSubExpr());
4979 default:
4980 return 0;
4981 }
4982 }
Chris Lattner4b009652007-07-25 00:24:17 +00004983 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004984 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004985 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004986 // If the result of an implicit cast is an l-value, we care about
4987 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004988 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004989 default:
4990 return 0;
4991 }
4992}
4993
4994/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004995/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004996/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004997/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004998/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004999/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00005000/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00005001QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00005002 // Make sure to ignore parentheses in subsequent checks
5003 op = op->IgnoreParens();
5004
Douglas Gregore6be68a2008-12-17 22:52:20 +00005005 if (op->isTypeDependent())
5006 return Context.DependentTy;
5007
Steve Naroff9c6c3592008-01-13 17:10:08 +00005008 if (getLangOptions().C99) {
5009 // Implement C99-only parts of addressof rules.
5010 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5011 if (uOp->getOpcode() == UnaryOperator::Deref)
5012 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5013 // (assuming the deref expression is valid).
5014 return uOp->getSubExpr()->getType();
5015 }
5016 // Technically, there should be a check for array subscript
5017 // expressions here, but the result of one is always an lvalue anyway.
5018 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00005019 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00005020 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00005021
Eli Friedman14ab4c42009-05-16 23:27:50 +00005022 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5023 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00005024 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00005025 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00005026 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00005027 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5028 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005029 return QualType();
5030 }
Douglas Gregor531434b2009-05-02 02:18:30 +00005031 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00005032 // The operand cannot be a bit-field
5033 Diag(OpLoc, diag::err_typecheck_address_of)
5034 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00005035 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00005036 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5037 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00005038 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00005039 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00005040 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00005041 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00005042 } else if (isa<ObjCPropertyRefExpr>(op)) {
5043 // cannot take address of a property expression.
5044 Diag(OpLoc, diag::err_typecheck_address_of)
5045 << "property expression" << op->getSourceRange();
5046 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00005047 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00005048 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00005049 // with the register storage-class specifier.
5050 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5051 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00005052 Diag(OpLoc, diag::err_typecheck_address_of)
5053 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005054 return QualType();
5055 }
Douglas Gregor62f78762009-07-08 20:55:45 +00005056 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5057 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00005058 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00005059 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00005060 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00005061 // Could be a pointer to member, though, if there is an explicit
5062 // scope qualifier for the class.
5063 if (isa<QualifiedDeclRefExpr>(op)) {
5064 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00005065 if (Ctx && Ctx->isRecord()) {
5066 if (FD->getType()->isReferenceType()) {
5067 Diag(OpLoc,
5068 diag::err_cannot_form_pointer_to_member_of_reference_type)
5069 << FD->getDeclName() << FD->getType();
5070 return QualType();
5071 }
5072
Sebastian Redl0c9da212009-02-03 20:19:35 +00005073 return Context.getMemberPointerType(op->getType(),
5074 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00005075 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00005076 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00005077 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00005078 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00005079 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00005080 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5081 return Context.getMemberPointerType(op->getType(),
5082 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5083 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00005084 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00005085 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00005086
Eli Friedman14ab4c42009-05-16 23:27:50 +00005087 if (lval == Expr::LV_IncompleteVoidType) {
5088 // Taking the address of a void variable is technically illegal, but we
5089 // allow it in cases which are otherwise valid.
5090 // Example: "extern void x; void* y = &x;".
5091 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5092 }
5093
Chris Lattner4b009652007-07-25 00:24:17 +00005094 // If the operand has type "type", the result has type "pointer to type".
5095 return Context.getPointerType(op->getType());
5096}
5097
Chris Lattnerda5c0872008-11-23 09:13:29 +00005098QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005099 if (Op->isTypeDependent())
5100 return Context.DependentTy;
5101
Chris Lattnerda5c0872008-11-23 09:13:29 +00005102 UsualUnaryConversions(Op);
5103 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00005104
Chris Lattnerda5c0872008-11-23 09:13:29 +00005105 // Note that per both C89 and C99, this is always legal, even if ptype is an
5106 // incomplete type or void. It would be possible to warn about dereferencing
5107 // a void pointer, but it's completely well-defined, and such a warning is
5108 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005109 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00005110 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00005111
Fariborz Jahanian81699d92009-09-03 00:43:07 +00005112 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5113 return OPT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00005114
Chris Lattner77d52da2008-11-20 06:06:08 +00005115 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005116 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005117 return QualType();
5118}
5119
5120static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5121 tok::TokenKind Kind) {
5122 BinaryOperator::Opcode Opc;
5123 switch (Kind) {
5124 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005125 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5126 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005127 case tok::star: Opc = BinaryOperator::Mul; break;
5128 case tok::slash: Opc = BinaryOperator::Div; break;
5129 case tok::percent: Opc = BinaryOperator::Rem; break;
5130 case tok::plus: Opc = BinaryOperator::Add; break;
5131 case tok::minus: Opc = BinaryOperator::Sub; break;
5132 case tok::lessless: Opc = BinaryOperator::Shl; break;
5133 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5134 case tok::lessequal: Opc = BinaryOperator::LE; break;
5135 case tok::less: Opc = BinaryOperator::LT; break;
5136 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5137 case tok::greater: Opc = BinaryOperator::GT; break;
5138 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5139 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5140 case tok::amp: Opc = BinaryOperator::And; break;
5141 case tok::caret: Opc = BinaryOperator::Xor; break;
5142 case tok::pipe: Opc = BinaryOperator::Or; break;
5143 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5144 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5145 case tok::equal: Opc = BinaryOperator::Assign; break;
5146 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5147 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5148 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5149 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5150 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5151 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5152 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5153 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5154 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5155 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5156 case tok::comma: Opc = BinaryOperator::Comma; break;
5157 }
5158 return Opc;
5159}
5160
5161static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5162 tok::TokenKind Kind) {
5163 UnaryOperator::Opcode Opc;
5164 switch (Kind) {
5165 default: assert(0 && "Unknown unary op!");
5166 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5167 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5168 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5169 case tok::star: Opc = UnaryOperator::Deref; break;
5170 case tok::plus: Opc = UnaryOperator::Plus; break;
5171 case tok::minus: Opc = UnaryOperator::Minus; break;
5172 case tok::tilde: Opc = UnaryOperator::Not; break;
5173 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005174 case tok::kw___real: Opc = UnaryOperator::Real; break;
5175 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5176 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5177 }
5178 return Opc;
5179}
5180
Douglas Gregord7f915e2008-11-06 23:29:22 +00005181/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5182/// operator @p Opc at location @c TokLoc. This routine only supports
5183/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005184Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5185 unsigned Op,
5186 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005187 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005188 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005189 // The following two variables are used for compound assignment operators
5190 QualType CompLHSTy; // Type of LHS after promotions for computation
5191 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005192
5193 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005194 case BinaryOperator::Assign:
5195 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5196 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005197 case BinaryOperator::PtrMemD:
5198 case BinaryOperator::PtrMemI:
5199 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5200 Opc == BinaryOperator::PtrMemI);
5201 break;
5202 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005203 case BinaryOperator::Div:
5204 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5205 break;
5206 case BinaryOperator::Rem:
5207 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5208 break;
5209 case BinaryOperator::Add:
5210 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5211 break;
5212 case BinaryOperator::Sub:
5213 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5214 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005215 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005216 case BinaryOperator::Shr:
5217 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5218 break;
5219 case BinaryOperator::LE:
5220 case BinaryOperator::LT:
5221 case BinaryOperator::GE:
5222 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005223 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005224 break;
5225 case BinaryOperator::EQ:
5226 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005227 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005228 break;
5229 case BinaryOperator::And:
5230 case BinaryOperator::Xor:
5231 case BinaryOperator::Or:
5232 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5233 break;
5234 case BinaryOperator::LAnd:
5235 case BinaryOperator::LOr:
5236 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5237 break;
5238 case BinaryOperator::MulAssign:
5239 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005240 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5241 CompLHSTy = CompResultTy;
5242 if (!CompResultTy.isNull())
5243 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005244 break;
5245 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005246 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5247 CompLHSTy = CompResultTy;
5248 if (!CompResultTy.isNull())
5249 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005250 break;
5251 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005252 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5253 if (!CompResultTy.isNull())
5254 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005255 break;
5256 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005257 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5258 if (!CompResultTy.isNull())
5259 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005260 break;
5261 case BinaryOperator::ShlAssign:
5262 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005263 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5264 CompLHSTy = CompResultTy;
5265 if (!CompResultTy.isNull())
5266 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005267 break;
5268 case BinaryOperator::AndAssign:
5269 case BinaryOperator::XorAssign:
5270 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005271 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5272 CompLHSTy = CompResultTy;
5273 if (!CompResultTy.isNull())
5274 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005275 break;
5276 case BinaryOperator::Comma:
5277 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5278 break;
5279 }
5280 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005281 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005282 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005283 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5284 else
5285 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005286 CompLHSTy, CompResultTy,
5287 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005288}
5289
Chris Lattner4b009652007-07-25 00:24:17 +00005290// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005291Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5292 tok::TokenKind Kind,
5293 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005294 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005295 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005296
Steve Naroff87d58b42007-09-16 03:34:24 +00005297 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5298 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005299
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005300 if (getLangOptions().CPlusPlus &&
5301 (lhs->getType()->isOverloadableType() ||
5302 rhs->getType()->isOverloadableType())) {
5303 // Find all of the overloaded operators visible from this
5304 // point. We perform both an operator-name lookup from the local
5305 // scope and an argument-dependent lookup based on the types of
5306 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005307 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005308 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5309 if (OverOp != OO_None) {
5310 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5311 Functions);
5312 Expr *Args[2] = { lhs, rhs };
5313 DeclarationName OpName
5314 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5315 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005316 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005317
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005318 // Build the (potentially-overloaded, potentially-dependent)
5319 // binary operation.
5320 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005321 }
5322
Douglas Gregord7f915e2008-11-06 23:29:22 +00005323 // Build a built-in binary operation.
5324 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005325}
5326
Douglas Gregorc78182d2009-03-13 23:49:33 +00005327Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5328 unsigned OpcIn,
5329 ExprArg InputArg) {
5330 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005331
Mike Stumpe127ae32009-05-16 07:39:55 +00005332 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005333 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005334 QualType resultType;
5335 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005336 case UnaryOperator::OffsetOf:
5337 assert(false && "Invalid unary operator");
5338 break;
5339
Chris Lattner4b009652007-07-25 00:24:17 +00005340 case UnaryOperator::PreInc:
5341 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005342 case UnaryOperator::PostInc:
5343 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005344 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005345 Opc == UnaryOperator::PreInc ||
5346 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005347 break;
Mike Stump9afab102009-02-19 03:04:26 +00005348 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005349 resultType = CheckAddressOfOperand(Input, OpLoc);
5350 break;
Mike Stump9afab102009-02-19 03:04:26 +00005351 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005352 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005353 resultType = CheckIndirectionOperand(Input, OpLoc);
5354 break;
5355 case UnaryOperator::Plus:
5356 case UnaryOperator::Minus:
5357 UsualUnaryConversions(Input);
5358 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005359 if (resultType->isDependentType())
5360 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005361 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5362 break;
5363 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5364 resultType->isEnumeralType())
5365 break;
5366 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5367 Opc == UnaryOperator::Plus &&
5368 resultType->isPointerType())
5369 break;
5370
Sebastian Redl8b769972009-01-19 00:08:26 +00005371 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5372 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005373 case UnaryOperator::Not: // bitwise complement
5374 UsualUnaryConversions(Input);
5375 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005376 if (resultType->isDependentType())
5377 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005378 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5379 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5380 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005381 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005382 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005383 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005384 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5385 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005386 break;
5387 case UnaryOperator::LNot: // logical negation
5388 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5389 DefaultFunctionArrayConversion(Input);
5390 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005391 if (resultType->isDependentType())
5392 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005393 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005394 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5395 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005396 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005397 // In C++, it's bool. C++ 5.3.1p8
5398 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005399 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005400 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005401 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005402 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005403 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005404 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005405 resultType = Input->getType();
5406 break;
5407 }
5408 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005409 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005410
5411 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005412 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005413}
5414
Douglas Gregorc78182d2009-03-13 23:49:33 +00005415// Unary Operators. 'Tok' is the token for the operator.
5416Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5417 tok::TokenKind Op, ExprArg input) {
5418 Expr *Input = (Expr*)input.get();
5419 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5420
5421 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5422 // Find all of the overloaded operators visible from this
5423 // point. We perform both an operator-name lookup from the local
5424 // scope and an argument-dependent lookup based on the types of
5425 // the arguments.
5426 FunctionSet Functions;
5427 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5428 if (OverOp != OO_None) {
5429 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5430 Functions);
5431 DeclarationName OpName
5432 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5433 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5434 }
5435
5436 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5437 }
5438
5439 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5440}
5441
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005442/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005443Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5444 SourceLocation LabLoc,
5445 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005446 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005447 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005448
Daniel Dunbar879788d2008-08-04 16:51:22 +00005449 // If we haven't seen this label yet, create a forward reference. It
5450 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005451 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005452 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005453
Chris Lattner4b009652007-07-25 00:24:17 +00005454 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005455 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5456 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005457}
5458
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005459Sema::OwningExprResult
5460Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5461 SourceLocation RPLoc) { // "({..})"
5462 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005463 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5464 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5465
Eli Friedmanbc941e12009-01-24 23:09:00 +00005466 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005467 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005468 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005469
Chris Lattner4b009652007-07-25 00:24:17 +00005470 // FIXME: there are a variety of strange constraints to enforce here, for
5471 // example, it is not possible to goto into a stmt expression apparently.
5472 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005473
Chris Lattner4b009652007-07-25 00:24:17 +00005474 // If there are sub stmts in the compound stmt, take the type of the last one
5475 // as the type of the stmtexpr.
5476 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005477
Chris Lattner200964f2008-07-26 19:51:01 +00005478 if (!Compound->body_empty()) {
5479 Stmt *LastStmt = Compound->body_back();
5480 // If LastStmt is a label, skip down through into the body.
5481 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5482 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005483
Chris Lattner200964f2008-07-26 19:51:01 +00005484 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005485 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005486 }
Mike Stump9afab102009-02-19 03:04:26 +00005487
Eli Friedman2b128322009-03-23 00:24:07 +00005488 // FIXME: Check that expression type is complete/non-abstract; statement
5489 // expressions are not lvalues.
5490
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005491 substmt.release();
5492 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005493}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005494
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005495Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5496 SourceLocation BuiltinLoc,
5497 SourceLocation TypeLoc,
5498 TypeTy *argty,
5499 OffsetOfComponent *CompPtr,
5500 unsigned NumComponents,
5501 SourceLocation RPLoc) {
5502 // FIXME: This function leaks all expressions in the offset components on
5503 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005504 // FIXME: Preserve type source info.
5505 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005506 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005507
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005508 bool Dependent = ArgTy->isDependentType();
5509
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005510 // We must have at least one component that refers to the type, and the first
5511 // one is known to be a field designator. Verify that the ArgTy represents
5512 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005513 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005514 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005515
Eli Friedman2b128322009-03-23 00:24:07 +00005516 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5517 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005518
Eli Friedman342d9432009-02-27 06:44:11 +00005519 // Otherwise, create a null pointer as the base, and iteratively process
5520 // the offsetof designators.
5521 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5522 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005523 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005524 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005525
Chris Lattnerb37522e2007-08-31 21:49:13 +00005526 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5527 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005528 // FIXME: This diagnostic isn't actually visible because the location is in
5529 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005530 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005531 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5532 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005533
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005534 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005535 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005536
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005537 // FIXME: Dependent case loses a lot of information here. And probably
5538 // leaks like a sieve.
5539 for (unsigned i = 0; i != NumComponents; ++i) {
5540 const OffsetOfComponent &OC = CompPtr[i];
5541 if (OC.isBrackets) {
5542 // Offset of an array sub-field. TODO: Should we allow vector elements?
5543 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5544 if (!AT) {
5545 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005546 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5547 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005548 }
5549
5550 // FIXME: C++: Verify that operator[] isn't overloaded.
5551
Eli Friedman342d9432009-02-27 06:44:11 +00005552 // Promote the array so it looks more like a normal array subscript
5553 // expression.
5554 DefaultFunctionArrayConversion(Res);
5555
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005556 // C99 6.5.2.1p1
5557 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005558 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005559 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005560 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005561 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005562 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005563
5564 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5565 OC.LocEnd);
5566 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005567 }
Mike Stump9afab102009-02-19 03:04:26 +00005568
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005569 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005570 if (!RC) {
5571 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005572 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5573 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005574 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005575
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005576 // Get the decl corresponding to this.
5577 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005578 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005579 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005580 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5581 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5582 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005583 DidWarnAboutNonPOD = true;
5584 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005585 }
5586
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005587 FieldDecl *MemberDecl
5588 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5589 LookupMemberName)
5590 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005591 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005592 if (!MemberDecl)
Anders Carlsson4355a392009-08-30 00:54:35 +00005593 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005594 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005595
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005596 // FIXME: C++: Verify that MemberDecl isn't a static field.
5597 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005598 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005599 Res = BuildAnonymousStructUnionMemberReference(
5600 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005601 } else {
5602 // MemberDecl->getType() doesn't get the right qualifiers, but it
5603 // doesn't matter here.
5604 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5605 MemberDecl->getType().getNonReferenceType());
5606 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005607 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005608 }
Mike Stump9afab102009-02-19 03:04:26 +00005609
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005610 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5611 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005612}
5613
5614
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005615Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5616 TypeTy *arg1,TypeTy *arg2,
5617 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005618 // FIXME: Preserve type source info.
5619 QualType argT1 = GetTypeFromParser(arg1);
5620 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005621
Steve Naroff63bad2d2007-08-01 22:05:33 +00005622 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005623
Douglas Gregore6211502009-05-19 22:28:02 +00005624 if (getLangOptions().CPlusPlus) {
5625 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5626 << SourceRange(BuiltinLoc, RPLoc);
5627 return ExprError();
5628 }
5629
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005630 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5631 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005632}
5633
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005634Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5635 ExprArg cond,
5636 ExprArg expr1, ExprArg expr2,
5637 SourceLocation RPLoc) {
5638 Expr *CondExpr = static_cast<Expr*>(cond.get());
5639 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5640 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005641
Steve Naroff93c53012007-08-03 21:21:27 +00005642 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5643
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005644 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005645 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005646 resType = Context.DependentTy;
5647 } else {
5648 // The conditional expression is required to be a constant expression.
5649 llvm::APSInt condEval(32);
5650 SourceLocation ExpLoc;
5651 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005652 return ExprError(Diag(ExpLoc,
5653 diag::err_typecheck_choose_expr_requires_constant)
5654 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005655
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005656 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5657 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5658 }
5659
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005660 cond.release(); expr1.release(); expr2.release();
5661 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5662 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005663}
5664
Steve Naroff52a81c02008-09-03 18:15:37 +00005665//===----------------------------------------------------------------------===//
5666// Clang Extensions.
5667//===----------------------------------------------------------------------===//
5668
5669/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005670void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005671 // Analyze block parameters.
5672 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005673
Steve Naroff52a81c02008-09-03 18:15:37 +00005674 // Add BSI to CurBlock.
5675 BSI->PrevBlockInfo = CurBlock;
5676 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005677
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005678 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005679 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005680 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005681 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005682 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5683 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005684
Steve Naroff52059382008-10-10 01:28:17 +00005685 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005686 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005687}
5688
Mike Stumpc1fddff2009-02-04 22:31:32 +00005689void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005690 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005691
5692 if (ParamInfo.getNumTypeObjects() == 0
5693 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005694 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005695 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5696
Mike Stump458287d2009-04-28 01:10:27 +00005697 if (T->isArrayType()) {
5698 Diag(ParamInfo.getSourceRange().getBegin(),
5699 diag::err_block_returns_array);
5700 return;
5701 }
5702
Mike Stumpc1fddff2009-02-04 22:31:32 +00005703 // The parameter list is optional, if there was none, assume ().
5704 if (!T->isFunctionType())
5705 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5706
5707 CurBlock->hasPrototype = true;
5708 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005709 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005710 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005711 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005712 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005713 // FIXME: remove the attribute.
5714 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005715 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5716
5717 // Do not allow returning a objc interface by-value.
5718 if (RetTy->isObjCInterfaceType()) {
5719 Diag(ParamInfo.getSourceRange().getBegin(),
5720 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5721 return;
5722 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005723 return;
5724 }
5725
Steve Naroff52a81c02008-09-03 18:15:37 +00005726 // Analyze arguments to block.
5727 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5728 "Not a function declarator!");
5729 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005730
Steve Naroff52059382008-10-10 01:28:17 +00005731 CurBlock->hasPrototype = FTI.hasPrototype;
5732 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005733
Steve Naroff52a81c02008-09-03 18:15:37 +00005734 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5735 // no arguments, not a function that takes a single void argument.
5736 if (FTI.hasPrototype &&
5737 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005738 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5739 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005740 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005741 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005742 } else if (FTI.hasPrototype) {
5743 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005744 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005745 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005746 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005747 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005748 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005749 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005750 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005751 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5752 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5753 // If this has an identifier, add it to the scope stack.
5754 if ((*AI)->getIdentifier())
5755 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005756
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005757 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005758 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005759 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005760 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005761 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005762 // FIXME: remove the attribute.
5763 }
5764
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005765 // Analyze the return type.
5766 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5767 QualType RetTy = T->getAsFunctionType()->getResultType();
5768
5769 // Do not allow returning a objc interface by-value.
5770 if (RetTy->isObjCInterfaceType()) {
5771 Diag(ParamInfo.getSourceRange().getBegin(),
5772 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5773 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005774 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005775}
5776
5777/// ActOnBlockError - If there is an error parsing a block, this callback
5778/// is invoked to pop the information about the block from the action impl.
5779void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5780 // Ensure that CurBlock is deleted.
5781 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005782
Chris Lattnere7765e12009-04-19 05:28:12 +00005783 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5784
Steve Naroff52a81c02008-09-03 18:15:37 +00005785 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005786 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005787 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005788 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005789}
5790
5791/// ActOnBlockStmtExpr - This is called when the body of a block statement
5792/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005793Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5794 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005795 // If blocks are disabled, emit an error.
5796 if (!LangOpts.Blocks)
5797 Diag(CaretLoc, diag::err_blocks_disable);
5798
Steve Naroff52a81c02008-09-03 18:15:37 +00005799 // Ensure that CurBlock is deleted.
5800 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005801
Steve Naroff52059382008-10-10 01:28:17 +00005802 PopDeclContext();
5803
Steve Naroff52a81c02008-09-03 18:15:37 +00005804 // Pop off CurBlock, handle nested blocks.
5805 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005806
Steve Naroff52a81c02008-09-03 18:15:37 +00005807 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005808 if (!BSI->ReturnType.isNull())
5809 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005810
Steve Naroff52a81c02008-09-03 18:15:37 +00005811 llvm::SmallVector<QualType, 8> ArgTypes;
5812 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5813 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005814
Mike Stump8e288f42009-07-28 22:04:01 +00005815 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005816 QualType BlockTy;
5817 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005818 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5819 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005820 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005821 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005822 BSI->isVariadic, 0, false, false, 0, 0,
5823 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005824
Eli Friedman2b128322009-03-23 00:24:07 +00005825 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005826 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005827 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005828
Chris Lattnere7765e12009-04-19 05:28:12 +00005829 // If needed, diagnose invalid gotos and switches in the block.
5830 if (CurFunctionNeedsScopeChecking)
5831 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5832 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5833
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005834 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005835 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005836 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5837 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005838}
5839
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005840Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5841 ExprArg expr, TypeTy *type,
5842 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005843 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005844 Expr *E = static_cast<Expr*>(expr.get());
5845 Expr *OrigExpr = E;
5846
Anders Carlsson36760332007-10-15 20:28:48 +00005847 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005848
5849 // Get the va_list type
5850 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005851 if (VaListType->isArrayType()) {
5852 // Deal with implicit array decay; for example, on x86-64,
5853 // va_list is an array, but it's supposed to decay to
5854 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005855 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005856 // Make sure the input expression also decays appropriately.
5857 UsualUnaryConversions(E);
5858 } else {
5859 // Otherwise, the va_list argument must be an l-value because
5860 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005861 if (!E->isTypeDependent() &&
5862 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005863 return ExprError();
5864 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005865
Douglas Gregor25990972009-05-19 23:10:31 +00005866 if (!E->isTypeDependent() &&
5867 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005868 return ExprError(Diag(E->getLocStart(),
5869 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005870 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005871 }
Mike Stump9afab102009-02-19 03:04:26 +00005872
Eli Friedman2b128322009-03-23 00:24:07 +00005873 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005874 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005875
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005876 expr.release();
5877 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5878 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005879}
5880
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005881Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005882 // The type of __null will be int or long, depending on the size of
5883 // pointers on the target.
5884 QualType Ty;
5885 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5886 Ty = Context.IntTy;
5887 else
5888 Ty = Context.LongTy;
5889
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005890 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005891}
5892
Chris Lattner005ed752008-01-04 18:04:52 +00005893bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5894 SourceLocation Loc,
5895 QualType DstType, QualType SrcType,
5896 Expr *SrcExpr, const char *Flavor) {
5897 // Decode the result (notice that AST's are still created for extensions).
5898 bool isInvalid = false;
5899 unsigned DiagKind;
5900 switch (ConvTy) {
5901 default: assert(0 && "Unknown conversion type");
5902 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005903 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005904 DiagKind = diag::ext_typecheck_convert_pointer_int;
5905 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005906 case IntToPointer:
5907 DiagKind = diag::ext_typecheck_convert_int_pointer;
5908 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005909 case IncompatiblePointer:
5910 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5911 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005912 case IncompatiblePointerSign:
5913 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5914 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005915 case FunctionVoidPointer:
5916 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5917 break;
5918 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005919 // If the qualifiers lost were because we were applying the
5920 // (deprecated) C++ conversion from a string literal to a char*
5921 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5922 // Ideally, this check would be performed in
5923 // CheckPointerTypesForAssignment. However, that would require a
5924 // bit of refactoring (so that the second argument is an
5925 // expression, rather than a type), which should be done as part
5926 // of a larger effort to fix CheckPointerTypesForAssignment for
5927 // C++ semantics.
5928 if (getLangOptions().CPlusPlus &&
5929 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5930 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005931 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5932 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005933 case IntToBlockPointer:
5934 DiagKind = diag::err_int_to_block_pointer;
5935 break;
5936 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005937 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005938 break;
Steve Naroff19608432008-10-14 22:18:38 +00005939 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005940 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005941 // it can give a more specific diagnostic.
5942 DiagKind = diag::warn_incompatible_qualified_id;
5943 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005944 case IncompatibleVectors:
5945 DiagKind = diag::warn_incompatible_vectors;
5946 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005947 case Incompatible:
5948 DiagKind = diag::err_typecheck_convert_incompatible;
5949 isInvalid = true;
5950 break;
5951 }
Mike Stump9afab102009-02-19 03:04:26 +00005952
Chris Lattner271d4c22008-11-24 05:29:24 +00005953 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5954 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005955 return isInvalid;
5956}
Anders Carlssond5201b92008-11-30 19:50:32 +00005957
Chris Lattnereec8ae22009-04-25 21:59:05 +00005958bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005959 llvm::APSInt ICEResult;
5960 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5961 if (Result)
5962 *Result = ICEResult;
5963 return false;
5964 }
5965
Anders Carlssond5201b92008-11-30 19:50:32 +00005966 Expr::EvalResult EvalResult;
5967
Mike Stump9afab102009-02-19 03:04:26 +00005968 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005969 EvalResult.HasSideEffects) {
5970 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5971
5972 if (EvalResult.Diag) {
5973 // We only show the note if it's not the usual "invalid subexpression"
5974 // or if it's actually in a subexpression.
5975 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5976 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5977 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5978 }
Mike Stump9afab102009-02-19 03:04:26 +00005979
Anders Carlssond5201b92008-11-30 19:50:32 +00005980 return true;
5981 }
5982
Eli Friedmance329412009-04-25 22:26:58 +00005983 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5984 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005985
Eli Friedmance329412009-04-25 22:26:58 +00005986 if (EvalResult.Diag &&
5987 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5988 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005989
Anders Carlssond5201b92008-11-30 19:50:32 +00005990 if (Result)
5991 *Result = EvalResult.Val.getInt();
5992 return false;
5993}
Douglas Gregor98189262009-06-19 23:52:42 +00005994
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005995Sema::ExpressionEvaluationContext
5996Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5997 // Introduce a new set of potentially referenced declarations to the stack.
5998 if (NewContext == PotentiallyPotentiallyEvaluated)
5999 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
6000
6001 std::swap(ExprEvalContext, NewContext);
6002 return NewContext;
6003}
6004
6005void
6006Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6007 ExpressionEvaluationContext NewContext) {
6008 ExprEvalContext = NewContext;
6009
6010 if (OldContext == PotentiallyPotentiallyEvaluated) {
6011 // Mark any remaining declarations in the current position of the stack
6012 // as "referenced". If they were not meant to be referenced, semantic
6013 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6014 PotentiallyReferencedDecls RemainingDecls;
6015 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6016 PotentiallyReferencedDeclStack.pop_back();
6017
6018 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6019 IEnd = RemainingDecls.end();
6020 I != IEnd; ++I)
6021 MarkDeclarationReferenced(I->first, I->second);
6022 }
6023}
Douglas Gregor98189262009-06-19 23:52:42 +00006024
6025/// \brief Note that the given declaration was referenced in the source code.
6026///
6027/// This routine should be invoke whenever a given declaration is referenced
6028/// in the source code, and where that reference occurred. If this declaration
6029/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6030/// C99 6.9p3), then the declaration will be marked as used.
6031///
6032/// \param Loc the location where the declaration was referenced.
6033///
6034/// \param D the declaration that has been referenced by the source code.
6035void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6036 assert(D && "No declaration?");
6037
Douglas Gregorcad27f62009-06-22 23:06:13 +00006038 if (D->isUsed())
6039 return;
6040
Douglas Gregor98189262009-06-19 23:52:42 +00006041 // Mark a parameter declaration "used", regardless of whether we're in a
6042 // template or not.
6043 if (isa<ParmVarDecl>(D))
6044 D->setUsed(true);
6045
6046 // Do not mark anything as "used" within a dependent context; wait for
6047 // an instantiation.
6048 if (CurContext->isDependentContext())
6049 return;
6050
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00006051 switch (ExprEvalContext) {
6052 case Unevaluated:
6053 // We are in an expression that is not potentially evaluated; do nothing.
6054 return;
6055
6056 case PotentiallyEvaluated:
6057 // We are in a potentially-evaluated expression, so this declaration is
6058 // "used"; handle this below.
6059 break;
6060
6061 case PotentiallyPotentiallyEvaluated:
6062 // We are in an expression that may be potentially evaluated; queue this
6063 // declaration reference until we know whether the expression is
6064 // potentially evaluated.
6065 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6066 return;
6067 }
6068
Douglas Gregor98189262009-06-19 23:52:42 +00006069 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00006070 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00006071 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00006072 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6073 if (!Constructor->isUsed())
6074 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00006075 } else if (Constructor->isImplicit() &&
6076 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00006077 if (!Constructor->isUsed())
6078 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6079 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00006080 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6081 if (Destructor->isImplicit() && !Destructor->isUsed())
6082 DefineImplicitDestructor(Loc, Destructor);
6083
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00006084 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6085 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6086 MethodDecl->getOverloadedOperator() == OO_Equal) {
6087 if (!MethodDecl->isUsed())
6088 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6089 }
6090 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00006091 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006092 // Implicit instantiation of function templates and member functions of
6093 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00006094 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006095 // FIXME: distinguish between implicit instantiations of function
6096 // templates and explicit specializations (the latter don't get
6097 // instantiated, naturally).
6098 if (Function->getInstantiatedFromMemberFunction() ||
6099 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00006100 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00006101 }
6102
6103
Douglas Gregor98189262009-06-19 23:52:42 +00006104 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00006105 Function->setUsed(true);
6106 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00006107 }
Douglas Gregor98189262009-06-19 23:52:42 +00006108
6109 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00006110 // Implicit instantiation of static data members of class templates.
6111 // FIXME: distinguish between implicit instantiations (which we need to
6112 // actually instantiate) and explicit specializations.
6113 if (Var->isStaticDataMember() &&
6114 Var->getInstantiatedFromStaticDataMember())
6115 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6116
Douglas Gregor98189262009-06-19 23:52:42 +00006117 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006118
Douglas Gregor98189262009-06-19 23:52:42 +00006119 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006120 return;
6121}
Douglas Gregor98189262009-06-19 23:52:42 +00006122}
6123