blob: b17f7bc1ca8e8fd35796de1ecbab33d04181d8b6 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Douglas Gregoraa57e862009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62 MD->isInstanceMethod());
63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64 }
65 }
66 }
67
68 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000069 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70 }
71
Douglas Gregoraa57e862009-02-18 21:56:37 +000072 // See if this is a deleted function.
73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
74 if (FD->isDeleted()) {
75 Diag(Loc, diag::err_deleted_function_use);
76 Diag(D->getLocation(), diag::note_unavailable_here) << true;
77 return true;
78 }
79
80 // See if the decl is unavailable
81 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000082 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000083 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
84 }
85
86
87 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000088}
89
Chris Lattner299b8842008-07-25 21:10:04 +000090//===----------------------------------------------------------------------===//
91// Standard Promotions and Conversions
92//===----------------------------------------------------------------------===//
93
Chris Lattner299b8842008-07-25 21:10:04 +000094/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
95void Sema::DefaultFunctionArrayConversion(Expr *&E) {
96 QualType Ty = E->getType();
97 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
98
Chris Lattner299b8842008-07-25 21:10:04 +000099 if (Ty->isFunctionType())
100 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000101 else if (Ty->isArrayType()) {
102 // In C90 mode, arrays only promote to pointers if the array expression is
103 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
104 // type 'array of type' is converted to an expression that has type 'pointer
105 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
106 // that has type 'array of type' ...". The relevant change is "an lvalue"
107 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000108 //
109 // C++ 4.2p1:
110 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
111 // T" can be converted to an rvalue of type "pointer to T".
112 //
113 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
114 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000115 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
116 }
Chris Lattner299b8842008-07-25 21:10:04 +0000117}
118
119/// UsualUnaryConversions - Performs various conversions that are common to most
120/// operators (C99 6.3). The conversions of array and function types are
121/// sometimes surpressed. For example, the array->pointer conversion doesn't
122/// apply if the array is an argument to the sizeof or address (&) operators.
123/// In these instances, this routine should *not* be called.
124Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
125 QualType Ty = Expr->getType();
126 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
127
Chris Lattner299b8842008-07-25 21:10:04 +0000128 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
129 ImpCastExprToType(Expr, Context.IntTy);
130 else
131 DefaultFunctionArrayConversion(Expr);
132
133 return Expr;
134}
135
Chris Lattner9305c3d2008-07-25 22:25:12 +0000136/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
137/// do not have a prototype. Arguments that have type float are promoted to
138/// double. All other argument types are converted by UsualUnaryConversions().
139void Sema::DefaultArgumentPromotion(Expr *&Expr) {
140 QualType Ty = Expr->getType();
141 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
142
143 // If this is a 'float' (CVR qualified or typedef) promote to double.
144 if (const BuiltinType *BT = Ty->getAsBuiltinType())
145 if (BT->getKind() == BuiltinType::Float)
146 return ImpCastExprToType(Expr, Context.DoubleTy);
147
148 UsualUnaryConversions(Expr);
149}
150
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000151// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
152// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000153void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000154 DefaultArgumentPromotion(Expr);
155
156 if (!Expr->getType()->isPODType()) {
157 Diag(Expr->getLocStart(),
158 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
159 Expr->getType() << CT;
160 }
161}
162
163
Chris Lattner299b8842008-07-25 21:10:04 +0000164/// UsualArithmeticConversions - Performs various conversions that are common to
165/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
166/// routine returns the first non-arithmetic type found. The client is
167/// responsible for emitting appropriate error diagnostics.
168/// FIXME: verify the conversion rules for "complex int" are consistent with
169/// GCC.
170QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
171 bool isCompAssign) {
172 if (!isCompAssign) {
173 UsualUnaryConversions(lhsExpr);
174 UsualUnaryConversions(rhsExpr);
175 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000176
Chris Lattner299b8842008-07-25 21:10:04 +0000177 // For conversion purposes, we ignore any qualifiers.
178 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000179 QualType lhs =
180 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
181 QualType rhs =
182 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000183
184 // If both types are identical, no conversion is needed.
185 if (lhs == rhs)
186 return lhs;
187
188 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
189 // The caller can deal with this (e.g. pointer + int).
190 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
191 return lhs;
192
193 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
194 if (!isCompAssign) {
195 ImpCastExprToType(lhsExpr, destType);
196 ImpCastExprToType(rhsExpr, destType);
197 }
198 return destType;
199}
200
201QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
202 // Perform the usual unary conversions. We do this early so that
203 // integral promotions to "int" can allow us to exit early, in the
204 // lhs == rhs check. Also, for conversion purposes, we ignore any
205 // qualifiers. For example, "const float" and "float" are
206 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000207 if (lhs->isPromotableIntegerType())
208 lhs = Context.IntTy;
209 else
210 lhs = lhs.getUnqualifiedType();
211 if (rhs->isPromotableIntegerType())
212 rhs = Context.IntTy;
213 else
214 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000215
Chris Lattner299b8842008-07-25 21:10:04 +0000216 // If both types are identical, no conversion is needed.
217 if (lhs == rhs)
218 return lhs;
219
220 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
221 // The caller can deal with this (e.g. pointer + int).
222 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
223 return lhs;
224
225 // At this point, we have two different arithmetic types.
226
227 // Handle complex types first (C99 6.3.1.8p1).
228 if (lhs->isComplexType() || rhs->isComplexType()) {
229 // if we have an integer operand, the result is the complex type.
230 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
231 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000232 return lhs;
233 }
234 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
235 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000236 return rhs;
237 }
238 // This handles complex/complex, complex/float, or float/complex.
239 // When both operands are complex, the shorter operand is converted to the
240 // type of the longer, and that is the type of the result. This corresponds
241 // to what is done when combining two real floating-point operands.
242 // The fun begins when size promotion occur across type domains.
243 // From H&S 6.3.4: When one operand is complex and the other is a real
244 // floating-point type, the less precise type is converted, within it's
245 // real or complex domain, to the precision of the other type. For example,
246 // when combining a "long double" with a "double _Complex", the
247 // "double _Complex" is promoted to "long double _Complex".
248 int result = Context.getFloatingTypeOrder(lhs, rhs);
249
250 if (result > 0) { // The left side is bigger, convert rhs.
251 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000252 } else if (result < 0) { // The right side is bigger, convert lhs.
253 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000254 }
255 // At this point, lhs and rhs have the same rank/size. Now, make sure the
256 // domains match. This is a requirement for our implementation, C99
257 // does not require this promotion.
258 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
259 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000260 return rhs;
261 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000262 return lhs;
263 }
264 }
265 return lhs; // The domain/size match exactly.
266 }
267 // Now handle "real" floating types (i.e. float, double, long double).
268 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
269 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000270 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000271 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000272 return lhs;
273 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000274 if (rhs->isComplexIntegerType()) {
275 // convert rhs to the complex floating point type.
276 return Context.getComplexType(lhs);
277 }
278 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000279 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000280 return rhs;
281 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000282 if (lhs->isComplexIntegerType()) {
283 // convert lhs to the complex floating point type.
284 return Context.getComplexType(rhs);
285 }
Chris Lattner299b8842008-07-25 21:10:04 +0000286 // We have two real floating types, float/complex combos were handled above.
287 // Convert the smaller operand to the bigger result.
288 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000289 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000290 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000291 assert(result < 0 && "illegal float comparison");
292 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000293 }
294 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
295 // Handle GCC complex int extension.
296 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
297 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
298
299 if (lhsComplexInt && rhsComplexInt) {
300 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000301 rhsComplexInt->getElementType()) >= 0)
302 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000303 return rhs;
304 } else if (lhsComplexInt && rhs->isIntegerType()) {
305 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000306 return lhs;
307 } else if (rhsComplexInt && lhs->isIntegerType()) {
308 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000309 return rhs;
310 }
311 }
312 // Finally, we have two differing integer types.
313 // The rules for this case are in C99 6.3.1.8
314 int compare = Context.getIntegerTypeOrder(lhs, rhs);
315 bool lhsSigned = lhs->isSignedIntegerType(),
316 rhsSigned = rhs->isSignedIntegerType();
317 QualType destType;
318 if (lhsSigned == rhsSigned) {
319 // Same signedness; use the higher-ranked type
320 destType = compare >= 0 ? lhs : rhs;
321 } else if (compare != (lhsSigned ? 1 : -1)) {
322 // The unsigned type has greater than or equal rank to the
323 // signed type, so use the unsigned type
324 destType = lhsSigned ? rhs : lhs;
325 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
326 // The two types are different widths; if we are here, that
327 // means the signed type is larger than the unsigned type, so
328 // use the signed type.
329 destType = lhsSigned ? lhs : rhs;
330 } else {
331 // The signed type is higher-ranked than the unsigned type,
332 // but isn't actually any bigger (like unsigned int and long
333 // on most 32-bit systems). Use the unsigned type corresponding
334 // to the signed type.
335 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
336 }
Chris Lattner299b8842008-07-25 21:10:04 +0000337 return destType;
338}
339
340//===----------------------------------------------------------------------===//
341// Semantic Analysis for various Expression Types
342//===----------------------------------------------------------------------===//
343
344
Steve Naroff87d58b42007-09-16 03:34:24 +0000345/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000346/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
347/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
348/// multiple tokens. However, the common case is that StringToks points to one
349/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000350///
351Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000352Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000353 assert(NumStringToks && "Must have at least one string!");
354
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000355 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000356 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000357 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000358
359 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
360 for (unsigned i = 0; i != NumStringToks; ++i)
361 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000362
Chris Lattnera6dcce32008-02-11 00:02:17 +0000363 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000364 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000365 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000366
367 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
368 if (getLangOptions().CPlusPlus)
369 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000370
Chris Lattnera6dcce32008-02-11 00:02:17 +0000371 // Get an array type for the string, according to C99 6.4.5. This includes
372 // the nul terminator character as well as the string length for pascal
373 // strings.
374 StrTy = Context.getConstantArrayType(StrTy,
375 llvm::APInt(32, Literal.GetStringLength()+1),
376 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000377
Chris Lattner4b009652007-07-25 00:24:17 +0000378 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000379 return Owned(StringLiteral::Create(Context, Literal.GetString(),
380 Literal.GetStringLength(),
381 Literal.AnyWide, StrTy,
382 &StringTokLocs[0],
383 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000384}
385
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000386/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
387/// CurBlock to VD should cause it to be snapshotted (as we do for auto
388/// variables defined outside the block) or false if this is not needed (e.g.
389/// for values inside the block or for globals).
390///
391/// FIXME: This will create BlockDeclRefExprs for global variables,
392/// function references, etc which is suboptimal :) and breaks
393/// things like "integer constant expression" tests.
394static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
395 ValueDecl *VD) {
396 // If the value is defined inside the block, we couldn't snapshot it even if
397 // we wanted to.
398 if (CurBlock->TheDecl == VD->getDeclContext())
399 return false;
400
401 // If this is an enum constant or function, it is constant, don't snapshot.
402 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
403 return false;
404
405 // If this is a reference to an extern, static, or global variable, no need to
406 // snapshot it.
407 // FIXME: What about 'const' variables in C++?
408 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
409 return Var->hasLocalStorage();
410
411 return true;
412}
413
414
415
Steve Naroff0acc9c92007-09-15 18:49:24 +0000416/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000417/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000418/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000419/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000420/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000421Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
422 IdentifierInfo &II,
423 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000424 const CXXScopeSpec *SS,
425 bool isAddressOfOperand) {
426 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000427 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000428}
429
Douglas Gregor566782a2009-01-06 05:10:23 +0000430/// BuildDeclRefExpr - Build either a DeclRefExpr or a
431/// QualifiedDeclRefExpr based on whether or not SS is a
432/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000433DeclRefExpr *
434Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
435 bool TypeDependent, bool ValueDependent,
436 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000437 if (SS && !SS->isEmpty())
438 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Mike Stump9afab102009-02-19 03:04:26 +0000439 ValueDependent,
440 SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000441 else
442 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000443}
444
Douglas Gregor723d3332009-01-07 00:43:41 +0000445/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
446/// variable corresponding to the anonymous union or struct whose type
447/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000448static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000449 assert(Record->isAnonymousStructOrUnion() &&
450 "Record must be an anonymous struct or union!");
451
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000452 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000453 // be an O(1) operation rather than a slow walk through DeclContext's
454 // vector (which itself will be eliminated). DeclGroups might make
455 // this even better.
456 DeclContext *Ctx = Record->getDeclContext();
457 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
458 DEnd = Ctx->decls_end();
459 D != DEnd; ++D) {
460 if (*D == Record) {
461 // The object for the anonymous struct/union directly
462 // follows its type in the list of declarations.
463 ++D;
464 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000465 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000466 return *D;
467 }
468 }
469
470 assert(false && "Missing object for anonymous record");
471 return 0;
472}
473
Sebastian Redlcd883f72009-01-18 18:53:16 +0000474Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000475Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
476 FieldDecl *Field,
477 Expr *BaseObjectExpr,
478 SourceLocation OpLoc) {
479 assert(Field->getDeclContext()->isRecord() &&
480 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
481 && "Field must be stored inside an anonymous struct or union");
482
483 // Construct the sequence of field member references
484 // we'll have to perform to get to the field in the anonymous
485 // union/struct. The list of members is built from the field
486 // outward, so traverse it backwards to go from an object in
487 // the current context to the field we found.
488 llvm::SmallVector<FieldDecl *, 4> AnonFields;
489 AnonFields.push_back(Field);
490 VarDecl *BaseObject = 0;
491 DeclContext *Ctx = Field->getDeclContext();
492 do {
493 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000494 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000495 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
496 AnonFields.push_back(AnonField);
497 else {
498 BaseObject = cast<VarDecl>(AnonObject);
499 break;
500 }
501 Ctx = Ctx->getParent();
502 } while (Ctx->isRecord() &&
503 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
504
505 // Build the expression that refers to the base object, from
506 // which we will build a sequence of member references to each
507 // of the anonymous union objects and, eventually, the field we
508 // found via name lookup.
509 bool BaseObjectIsPointer = false;
510 unsigned ExtraQuals = 0;
511 if (BaseObject) {
512 // BaseObject is an anonymous struct/union variable (and is,
513 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000514 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000515 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000516 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000517 ExtraQuals
518 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
519 } else if (BaseObjectExpr) {
520 // The caller provided the base object expression. Determine
521 // whether its a pointer and whether it adds any qualifiers to the
522 // anonymous struct/union fields we're looking into.
523 QualType ObjectType = BaseObjectExpr->getType();
524 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
525 BaseObjectIsPointer = true;
526 ObjectType = ObjectPtr->getPointeeType();
527 }
528 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
529 } else {
530 // We've found a member of an anonymous struct/union that is
531 // inside a non-anonymous struct/union, so in a well-formed
532 // program our base object expression is "this".
533 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
534 if (!MD->isStatic()) {
535 QualType AnonFieldType
536 = Context.getTagDeclType(
537 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
538 QualType ThisType = Context.getTagDeclType(MD->getParent());
539 if ((Context.getCanonicalType(AnonFieldType)
540 == Context.getCanonicalType(ThisType)) ||
541 IsDerivedFrom(ThisType, AnonFieldType)) {
542 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000543 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000544 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000545 BaseObjectIsPointer = true;
546 }
547 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000548 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
549 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000550 }
551 ExtraQuals = MD->getTypeQualifiers();
552 }
553
554 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000555 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
556 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000557 }
558
559 // Build the implicit member references to the field of the
560 // anonymous struct/union.
561 Expr *Result = BaseObjectExpr;
562 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
563 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
564 FI != FIEnd; ++FI) {
565 QualType MemberType = (*FI)->getType();
566 if (!(*FI)->isMutable()) {
567 unsigned combinedQualifiers
568 = MemberType.getCVRQualifiers() | ExtraQuals;
569 MemberType = MemberType.getQualifiedType(combinedQualifiers);
570 }
Steve Naroff774e4152009-01-21 00:14:39 +0000571 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
572 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000573 BaseObjectIsPointer = false;
574 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
575 OpLoc = SourceLocation();
576 }
577
Sebastian Redlcd883f72009-01-18 18:53:16 +0000578 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000579}
580
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000581/// ActOnDeclarationNameExpr - The parser has read some kind of name
582/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
583/// performs lookup on that name and returns an expression that refers
584/// to that name. This routine isn't directly called from the parser,
585/// because the parser doesn't know about DeclarationName. Rather,
586/// this routine is called by ActOnIdentifierExpr,
587/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
588/// which form the DeclarationName from the corresponding syntactic
589/// forms.
590///
591/// HasTrailingLParen indicates whether this identifier is used in a
592/// function call context. LookupCtx is only used for a C++
593/// qualified-id (foo::bar) to indicate the class or namespace that
594/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000595///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000596/// isAddressOfOperand means that this expression is the direct operand
597/// of an address-of operator. This matters because this is the only
598/// situation where a qualified name referencing a non-static member may
599/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000600Sema::OwningExprResult
601Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
602 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000603 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000604 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000605 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000606 if (SS && SS->isInvalid())
607 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000608 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
609 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000610
Douglas Gregor09be81b2009-02-04 17:27:36 +0000611 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000612 if (Lookup.isAmbiguous()) {
613 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
614 SS && SS->isSet() ? SS->getRange()
615 : SourceRange());
616 return ExprError();
617 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000618 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000619
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000620 // If this reference is in an Objective-C method, then ivar lookup happens as
621 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000622 IdentifierInfo *II = Name.getAsIdentifierInfo();
623 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000624 // There are two cases to handle here. 1) scoped lookup could have failed,
625 // in which case we should look for an ivar. 2) scoped lookup could have
626 // found a decl, but that decl is outside the current method (i.e. a global
627 // variable). In these two cases, we do a lookup for an ivar with this
628 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000629 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000630 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000631 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000632 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000633 if (DiagnoseUseOfDecl(IV, Loc))
634 return ExprError();
Chris Lattner2a3bef92009-02-16 17:19:12 +0000635
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000636 // FIXME: This should use a new expr for a direct reference, don't turn
637 // this into Self->ivar, just return a BareIVarExpr or something.
638 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000639 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Mike Stump9afab102009-02-19 03:04:26 +0000640 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +0000641 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000642 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000643 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000644 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000645 }
646 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000647 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000648 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000649 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000650 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000651 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000652 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000653 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000654
Douglas Gregoraa57e862009-02-18 21:56:37 +0000655 // Determine whether this name might be a candidate for
656 // argument-dependent lookup.
657 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
658 HasTrailingLParen;
659
660 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000661 // We've seen something of the form
662 //
663 // identifier(
664 //
665 // and we did not find any entity by the name
666 // "identifier". However, this identifier is still subject to
667 // argument-dependent lookup, so keep track of the name.
668 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
669 Context.OverloadTy,
670 Loc));
671 }
672
Chris Lattner4b009652007-07-25 00:24:17 +0000673 if (D == 0) {
674 // Otherwise, this could be an implicitly declared function reference (legal
675 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000676 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000677 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000678 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000679 else {
680 // If this name wasn't predeclared and if this is not a function call,
681 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000682 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000683 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
684 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000685 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
686 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000687 return ExprError(Diag(Loc, diag::err_undeclared_use)
688 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000689 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000690 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000691 }
692 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000693
Sebastian Redl0c9da212009-02-03 20:19:35 +0000694 // If this is an expression of the form &Class::member, don't build an
695 // implicit member ref, because we want a pointer to the member in general,
696 // not any specific instance's member.
697 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000698 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000699 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000700 QualType DType;
701 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
702 DType = FD->getType().getNonReferenceType();
703 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
704 DType = Method->getType();
705 } else if (isa<OverloadedFunctionDecl>(D)) {
706 DType = Context.OverloadTy;
707 }
708 // Could be an inner type. That's diagnosed below, so ignore it here.
709 if (!DType.isNull()) {
710 // The pointer is type- and value-dependent if it points into something
711 // dependent.
712 bool Dependent = false;
713 for (; DC; DC = DC->getParent()) {
714 // FIXME: could stop early at namespace scope.
715 if (DC->isRecord()) {
716 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
717 if (Context.getTypeDeclType(Record)->isDependentType()) {
718 Dependent = true;
719 break;
720 }
721 }
722 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000723 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000724 }
725 }
726 }
727
Douglas Gregor723d3332009-01-07 00:43:41 +0000728 // We may have found a field within an anonymous union or struct
729 // (C++ [class.union]).
730 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
731 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
732 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000733
Douglas Gregor3257fb52008-12-22 05:46:06 +0000734 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
735 if (!MD->isStatic()) {
736 // C++ [class.mfct.nonstatic]p2:
737 // [...] if name lookup (3.4.1) resolves the name in the
738 // id-expression to a nonstatic nontype member of class X or of
739 // a base class of X, the id-expression is transformed into a
740 // class member access expression (5.2.5) using (*this) (9.3.2)
741 // as the postfix-expression to the left of the '.' operator.
742 DeclContext *Ctx = 0;
743 QualType MemberType;
744 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
745 Ctx = FD->getDeclContext();
746 MemberType = FD->getType();
747
748 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
749 MemberType = RefType->getPointeeType();
750 else if (!FD->isMutable()) {
751 unsigned combinedQualifiers
752 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
753 MemberType = MemberType.getQualifiedType(combinedQualifiers);
754 }
755 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
756 if (!Method->isStatic()) {
757 Ctx = Method->getParent();
758 MemberType = Method->getType();
759 }
760 } else if (OverloadedFunctionDecl *Ovl
761 = dyn_cast<OverloadedFunctionDecl>(D)) {
762 for (OverloadedFunctionDecl::function_iterator
763 Func = Ovl->function_begin(),
764 FuncEnd = Ovl->function_end();
765 Func != FuncEnd; ++Func) {
766 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
767 if (!DMethod->isStatic()) {
768 Ctx = Ovl->getDeclContext();
769 MemberType = Context.OverloadTy;
770 break;
771 }
772 }
773 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000774
775 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000776 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
777 QualType ThisType = Context.getTagDeclType(MD->getParent());
778 if ((Context.getCanonicalType(CtxType)
779 == Context.getCanonicalType(ThisType)) ||
780 IsDerivedFrom(ThisType, CtxType)) {
781 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000782 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000783 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000784 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000785 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000786 }
787 }
788 }
789 }
790
Douglas Gregor8acb7272008-12-11 16:49:14 +0000791 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000792 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
793 if (MD->isStatic())
794 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000795 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
796 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000797 }
798
Douglas Gregor3257fb52008-12-22 05:46:06 +0000799 // Any other ways we could have found the field in a well-formed
800 // program would have been turned into implicit member expressions
801 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000802 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
803 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000804 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000805
Chris Lattner4b009652007-07-25 00:24:17 +0000806 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000807 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000808 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000809 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000810 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000811 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000812
Steve Naroffd6163f32008-09-05 22:11:13 +0000813 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000814 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000815 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
816 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000817 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
818 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
819 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000820 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000821
Douglas Gregoraa57e862009-02-18 21:56:37 +0000822 // Check whether this declaration can be used. Note that we suppress
823 // this check when we're going to perform argument-dependent lookup
824 // on this function name, because this might not be the function
825 // that overload resolution actually selects.
826 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
827 return ExprError();
828
Douglas Gregor48840c72008-12-10 23:01:14 +0000829 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000830 // Warn about constructs like:
831 // if (void *X = foo()) { ... } else { X }.
832 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000833 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
834 Scope *CheckS = S;
835 while (CheckS) {
836 if (CheckS->isWithinElse() &&
837 CheckS->getControlParent()->isDeclScope(Var)) {
838 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000839 ExprError(Diag(Loc, diag::warn_value_always_false)
840 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000841 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000842 ExprError(Diag(Loc, diag::warn_value_always_zero)
843 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000844 break;
845 }
846
847 // Move up one more control parent to check again.
848 CheckS = CheckS->getControlParent();
849 if (CheckS)
850 CheckS = CheckS->getParent();
851 }
852 }
853 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000854
855 // Only create DeclRefExpr's for valid Decl's.
856 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000857 return ExprError();
858
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000859 // If the identifier reference is inside a block, and it refers to a value
860 // that is outside the block, create a BlockDeclRefExpr instead of a
861 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
862 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000863 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000864 // We do not do this for things like enum constants, global variables, etc,
865 // as they do not get snapshotted.
866 //
867 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000868 // Blocks that have these can't be constant.
869 CurBlock->hasBlockDeclRefExprs = true;
870
Steve Naroff52059382008-10-10 01:28:17 +0000871 // The BlocksAttr indicates the variable is bound by-reference.
872 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000873 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000874 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000875
Steve Naroff52059382008-10-10 01:28:17 +0000876 // Variable will be bound by-copy, make it const within the closure.
877 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000878 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000879 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000880 }
881 // If this reference is not in a block or if the referenced variable is
882 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000883
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000884 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000885 bool ValueDependent = false;
886 if (getLangOptions().CPlusPlus) {
887 // C++ [temp.dep.expr]p3:
888 // An id-expression is type-dependent if it contains:
889 // - an identifier that was declared with a dependent type,
890 if (VD->getType()->isDependentType())
891 TypeDependent = true;
892 // - FIXME: a template-id that is dependent,
893 // - a conversion-function-id that specifies a dependent type,
894 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
895 Name.getCXXNameType()->isDependentType())
896 TypeDependent = true;
897 // - a nested-name-specifier that contains a class-name that
898 // names a dependent type.
899 else if (SS && !SS->isEmpty()) {
900 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
901 DC; DC = DC->getParent()) {
902 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000903 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000904 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
905 if (Context.getTypeDeclType(Record)->isDependentType()) {
906 TypeDependent = true;
907 break;
908 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000909 }
910 }
911 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000912
Douglas Gregora5d84612008-12-10 20:57:37 +0000913 // C++ [temp.dep.constexpr]p2:
914 //
915 // An identifier is value-dependent if it is:
916 // - a name declared with a dependent type,
917 if (TypeDependent)
918 ValueDependent = true;
919 // - the name of a non-type template parameter,
920 else if (isa<NonTypeTemplateParmDecl>(VD))
921 ValueDependent = true;
922 // - a constant with integral or enumeration type and is
923 // initialized with an expression that is value-dependent
924 // (FIXME!).
925 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000926
Sebastian Redlcd883f72009-01-18 18:53:16 +0000927 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
928 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000929}
930
Sebastian Redlcd883f72009-01-18 18:53:16 +0000931Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
932 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000933 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000934
Chris Lattner4b009652007-07-25 00:24:17 +0000935 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000936 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000937 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
938 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
939 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000940 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000941
Chris Lattner7e637512008-01-12 08:14:25 +0000942 // Pre-defined identifiers are of type char[x], where x is the length of the
943 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000944 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000945 if (FunctionDecl *FD = getCurFunctionDecl())
946 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000947 else if (ObjCMethodDecl *MD = getCurMethodDecl())
948 Length = MD->getSynthesizedMethodSize();
949 else {
950 Diag(Loc, diag::ext_predef_outside_function);
951 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
952 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
953 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000954
955
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000956 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000957 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000958 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000959 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000960}
961
Sebastian Redlcd883f72009-01-18 18:53:16 +0000962Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000963 llvm::SmallString<16> CharBuffer;
964 CharBuffer.resize(Tok.getLength());
965 const char *ThisTokBegin = &CharBuffer[0];
966 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000967
Chris Lattner4b009652007-07-25 00:24:17 +0000968 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
969 Tok.getLocation(), PP);
970 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000971 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000972
973 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
974
Sebastian Redl75324932009-01-20 22:23:13 +0000975 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
976 Literal.isWide(),
977 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000978}
979
Sebastian Redlcd883f72009-01-18 18:53:16 +0000980Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
981 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000982 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
983 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000984 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000985 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000986 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000987 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000988 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000989
Chris Lattner4b009652007-07-25 00:24:17 +0000990 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000991 // Add padding so that NumericLiteralParser can overread by one character.
992 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000993 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000994
Chris Lattner4b009652007-07-25 00:24:17 +0000995 // Get the spelling of the token, which eliminates trigraphs, etc.
996 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000997
Chris Lattner4b009652007-07-25 00:24:17 +0000998 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
999 Tok.getLocation(), PP);
1000 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001001 return ExprError();
1002
Chris Lattner1de66eb2007-08-26 03:42:43 +00001003 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001004
Chris Lattner1de66eb2007-08-26 03:42:43 +00001005 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001006 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001007 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001008 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001009 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001010 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001011 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001012 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001013
1014 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1015
Ted Kremenekddedbe22007-11-29 00:56:49 +00001016 // isExact will be set by GetFloatValue().
1017 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001018 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1019 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001020
Chris Lattner1de66eb2007-08-26 03:42:43 +00001021 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001022 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001023 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001024 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001025
Neil Booth7421e9c2007-08-29 22:00:19 +00001026 // long long is a C99 feature.
1027 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001028 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001029 Diag(Tok.getLocation(), diag::ext_longlong);
1030
Chris Lattner4b009652007-07-25 00:24:17 +00001031 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001032 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033
Chris Lattner4b009652007-07-25 00:24:17 +00001034 if (Literal.GetIntegerValue(ResultVal)) {
1035 // If this value didn't fit into uintmax_t, warn and force to ull.
1036 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001037 Ty = Context.UnsignedLongLongTy;
1038 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001039 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001040 } else {
1041 // If this value fits into a ULL, try to figure out what else it fits into
1042 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001043
Chris Lattner4b009652007-07-25 00:24:17 +00001044 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1045 // be an unsigned int.
1046 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1047
1048 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001049 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001050 if (!Literal.isLong && !Literal.isLongLong) {
1051 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001052 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001053
Chris Lattner4b009652007-07-25 00:24:17 +00001054 // Does it fit in a unsigned int?
1055 if (ResultVal.isIntN(IntSize)) {
1056 // Does it fit in a signed int?
1057 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001058 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001059 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001060 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001061 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001062 }
Chris Lattner4b009652007-07-25 00:24:17 +00001063 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001064
Chris Lattner4b009652007-07-25 00:24:17 +00001065 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001066 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001067 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001068
Chris Lattner4b009652007-07-25 00:24:17 +00001069 // Does it fit in a unsigned long?
1070 if (ResultVal.isIntN(LongSize)) {
1071 // Does it fit in a signed long?
1072 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001073 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001074 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001075 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001076 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001077 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001078 }
1079
Chris Lattner4b009652007-07-25 00:24:17 +00001080 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001081 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001082 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001083
Chris Lattner4b009652007-07-25 00:24:17 +00001084 // Does it fit in a unsigned long long?
1085 if (ResultVal.isIntN(LongLongSize)) {
1086 // Does it fit in a signed long long?
1087 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001088 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001089 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001090 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001091 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001092 }
1093 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001094
Chris Lattner4b009652007-07-25 00:24:17 +00001095 // If we still couldn't decide a type, we probably have something that
1096 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001097 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001098 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001099 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001100 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001101 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001102
Chris Lattnere4068872008-05-09 05:59:00 +00001103 if (ResultVal.getBitWidth() != Width)
1104 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001105 }
Sebastian Redl75324932009-01-20 22:23:13 +00001106 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001107 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001108
Chris Lattner1de66eb2007-08-26 03:42:43 +00001109 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1110 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001111 Res = new (Context) ImaginaryLiteral(Res,
1112 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001113
1114 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001115}
1116
Sebastian Redlcd883f72009-01-18 18:53:16 +00001117Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1118 SourceLocation R, ExprArg Val) {
1119 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001120 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001121 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001122}
1123
1124/// The UsualUnaryConversions() function is *not* called by this routine.
1125/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001126bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1127 SourceLocation OpLoc,
1128 const SourceRange &ExprRange,
1129 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001130 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001131 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001132 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001133 if (isSizeof)
1134 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1135 return false;
1136 }
1137
1138 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001139 Diag(OpLoc, diag::ext_sizeof_void_type)
1140 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001141 return false;
1142 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001143
Chris Lattner159fe082009-01-24 19:46:37 +00001144 return DiagnoseIncompleteType(OpLoc, exprType,
1145 isSizeof ? diag::err_sizeof_incomplete_type :
1146 diag::err_alignof_incomplete_type,
1147 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001148}
1149
Chris Lattner8d9f7962009-01-24 20:17:12 +00001150bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1151 const SourceRange &ExprRange) {
1152 E = E->IgnoreParens();
1153
1154 // alignof decl is always ok.
1155 if (isa<DeclRefExpr>(E))
1156 return false;
1157
1158 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1159 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1160 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001161 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001162 return true;
1163 }
1164 // Other fields are ok.
1165 return false;
1166 }
1167 }
1168 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1169}
1170
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001171/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1172/// the same for @c alignof and @c __alignof
1173/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001174Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001175Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1176 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001177 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001178 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001179
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001180 QualType ArgTy;
1181 SourceRange Range;
1182 if (isType) {
1183 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1184 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001185
1186 // Verify that the operand is valid.
1187 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1188 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001189 } else {
1190 // Get the end location.
1191 Expr *ArgEx = (Expr *)TyOrEx;
1192 Range = ArgEx->getSourceRange();
1193 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001194
1195 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001196 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001197 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001198 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001199 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1200 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1201 isInvalid = true;
1202 } else {
1203 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1204 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001205
1206 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001207 DeleteExpr(ArgEx);
1208 return ExprError();
1209 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001210 }
1211
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001212 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001213 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001214 Context.getSizeType(), OpLoc,
1215 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001216}
1217
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001218QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Chris Lattner03931a72007-08-24 21:16:53 +00001219 DefaultFunctionArrayConversion(V);
1220
Chris Lattnera16e42d2007-08-26 05:39:26 +00001221 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001222 if (const ComplexType *CT = V->getType()->getAsComplexType())
1223 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001224
1225 // Otherwise they pass through real integer and floating point types here.
1226 if (V->getType()->isArithmeticType())
1227 return V->getType();
1228
1229 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001230 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1231 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001232 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001233}
1234
1235
Chris Lattner4b009652007-07-25 00:24:17 +00001236
Sebastian Redl8b769972009-01-19 00:08:26 +00001237Action::OwningExprResult
1238Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1239 tok::TokenKind Kind, ExprArg Input) {
1240 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001241
Chris Lattner4b009652007-07-25 00:24:17 +00001242 UnaryOperator::Opcode Opc;
1243 switch (Kind) {
1244 default: assert(0 && "Unknown unary op!");
1245 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1246 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1247 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001248
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001249 if (getLangOptions().CPlusPlus &&
1250 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1251 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001252 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001253 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1254
1255 // C++ [over.inc]p1:
1256 //
1257 // [...] If the function is a member function with one
1258 // parameter (which shall be of type int) or a non-member
1259 // function with two parameters (the second of which shall be
1260 // of type int), it defines the postfix increment operator ++
1261 // for objects of that type. When the postfix increment is
1262 // called as a result of using the ++ operator, the int
1263 // argument will have value zero.
1264 Expr *Args[2] = {
1265 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001266 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1267 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001268 };
1269
1270 // Build the candidate set for overloading
1271 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001272 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1273 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001274
1275 // Perform overload resolution.
1276 OverloadCandidateSet::iterator Best;
1277 switch (BestViableFunction(CandidateSet, Best)) {
1278 case OR_Success: {
1279 // We found a built-in operator or an overloaded operator.
1280 FunctionDecl *FnDecl = Best->Function;
1281
1282 if (FnDecl) {
1283 // We matched an overloaded operator. Build a call to that
1284 // operator.
1285
1286 // Convert the arguments.
1287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1288 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001289 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001290 } else {
1291 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001292 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001293 FnDecl->getParamDecl(0)->getType(),
1294 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001295 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001296 }
1297
1298 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001299 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001300 = FnDecl->getType()->getAsFunctionType()->getResultType();
1301 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001302
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001303 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001304 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001305 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001306 UsualUnaryConversions(FnExpr);
1307
Sebastian Redl8b769972009-01-19 00:08:26 +00001308 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001309 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1310 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001311 } else {
1312 // We matched a built-in operator. Convert the arguments, then
1313 // break out so that we will build the appropriate built-in
1314 // operator node.
1315 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1316 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001317 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001318
1319 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001320 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001321 }
1322
1323 case OR_No_Viable_Function:
1324 // No viable function; fall through to handling this as a
1325 // built-in operator, which will produce an error message for us.
1326 break;
1327
1328 case OR_Ambiguous:
1329 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1330 << UnaryOperator::getOpcodeStr(Opc)
1331 << Arg->getSourceRange();
1332 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001333 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001334
1335 case OR_Deleted:
1336 Diag(OpLoc, diag::err_ovl_deleted_oper)
1337 << Best->Function->isDeleted()
1338 << UnaryOperator::getOpcodeStr(Opc)
1339 << Arg->getSourceRange();
1340 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1341 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001342 }
1343
1344 // Either we found no viable overloaded operator or we matched a
1345 // built-in operator. In either case, fall through to trying to
1346 // build a built-in operation.
1347 }
1348
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001349 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1350 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001351 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001352 return ExprError();
1353 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001354 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001355}
1356
Sebastian Redl8b769972009-01-19 00:08:26 +00001357Action::OwningExprResult
1358Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1359 ExprArg Idx, SourceLocation RLoc) {
1360 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1361 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001362
Douglas Gregor80723c52008-11-19 17:17:41 +00001363 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001364 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001365 LHSExp->getType()->isEnumeralType() ||
1366 RHSExp->getType()->isRecordType() ||
1367 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001368 // Add the appropriate overloaded operators (C++ [over.match.oper])
1369 // to the candidate set.
1370 OverloadCandidateSet CandidateSet;
1371 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001372 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1373 SourceRange(LLoc, RLoc)))
1374 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001375
Douglas Gregor80723c52008-11-19 17:17:41 +00001376 // Perform overload resolution.
1377 OverloadCandidateSet::iterator Best;
1378 switch (BestViableFunction(CandidateSet, Best)) {
1379 case OR_Success: {
1380 // We found a built-in operator or an overloaded operator.
1381 FunctionDecl *FnDecl = Best->Function;
1382
1383 if (FnDecl) {
1384 // We matched an overloaded operator. Build a call to that
1385 // operator.
1386
1387 // Convert the arguments.
1388 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1389 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1390 PerformCopyInitialization(RHSExp,
1391 FnDecl->getParamDecl(0)->getType(),
1392 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001393 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001394 } else {
1395 // Convert the arguments.
1396 if (PerformCopyInitialization(LHSExp,
1397 FnDecl->getParamDecl(0)->getType(),
1398 "passing") ||
1399 PerformCopyInitialization(RHSExp,
1400 FnDecl->getParamDecl(1)->getType(),
1401 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001402 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001403 }
1404
1405 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001406 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001407 = FnDecl->getType()->getAsFunctionType()->getResultType();
1408 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001409
Douglas Gregor80723c52008-11-19 17:17:41 +00001410 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001411 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1412 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001413 UsualUnaryConversions(FnExpr);
1414
Sebastian Redl8b769972009-01-19 00:08:26 +00001415 Base.release();
1416 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001417 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001418 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001419 } else {
1420 // We matched a built-in operator. Convert the arguments, then
1421 // break out so that we will build the appropriate built-in
1422 // operator node.
1423 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1424 "passing") ||
1425 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1426 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001427 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001428
1429 break;
1430 }
1431 }
1432
1433 case OR_No_Viable_Function:
1434 // No viable function; fall through to handling this as a
1435 // built-in operator, which will produce an error message for us.
1436 break;
1437
1438 case OR_Ambiguous:
1439 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1440 << "[]"
1441 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1442 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001443 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001444
1445 case OR_Deleted:
1446 Diag(LLoc, diag::err_ovl_deleted_oper)
1447 << Best->Function->isDeleted()
1448 << "[]"
1449 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1450 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1451 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001452 }
1453
1454 // Either we found no viable overloaded operator or we matched a
1455 // built-in operator. In either case, fall through to trying to
1456 // build a built-in operation.
1457 }
1458
Chris Lattner4b009652007-07-25 00:24:17 +00001459 // Perform default conversions.
1460 DefaultFunctionArrayConversion(LHSExp);
1461 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001462
Chris Lattner4b009652007-07-25 00:24:17 +00001463 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1464
1465 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001466 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001467 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001468 // and index from the expression types.
1469 Expr *BaseExpr, *IndexExpr;
1470 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001471 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001472 BaseExpr = LHSExp;
1473 IndexExpr = RHSExp;
1474 // FIXME: need to deal with const...
1475 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001476 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001477 // Handle the uncommon case of "123[Ptr]".
1478 BaseExpr = RHSExp;
1479 IndexExpr = LHSExp;
1480 // FIXME: need to deal with const...
1481 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001482 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1483 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001484 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001485
Chris Lattner4b009652007-07-25 00:24:17 +00001486 // FIXME: need to deal with const...
1487 ResultType = VTy->getElementType();
1488 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001489 return ExprError(Diag(LHSExp->getLocStart(),
1490 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1491 }
Chris Lattner4b009652007-07-25 00:24:17 +00001492 // C99 6.5.2.1p1
1493 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001494 return ExprError(Diag(IndexExpr->getLocStart(),
1495 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001496
1497 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1498 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001499 // void (*)(int)) and pointers to incomplete types. Functions are not
1500 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001501 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001502 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001503 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001504 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001505
Sebastian Redl8b769972009-01-19 00:08:26 +00001506 Base.release();
1507 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001508 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001509 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001510}
1511
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001512QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001513CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001514 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001515 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001516
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001517 // The vector accessor can't exceed the number of elements.
1518 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001519
Mike Stump9afab102009-02-19 03:04:26 +00001520 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001521 // special names that indicate a subset of exactly half the elements are
1522 // to be selected.
1523 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001524
Nate Begeman1486b502009-01-18 01:47:54 +00001525 // This flag determines whether or not CompName has an 's' char prefix,
1526 // indicating that it is a string of hex values to be used as vector indices.
1527 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001528
1529 // Check that we've found one of the special components, or that the component
1530 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001531 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001532 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1533 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001534 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001535 do
1536 compStr++;
1537 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001538 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001539 do
1540 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001541 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001542 }
Nate Begeman1486b502009-01-18 01:47:54 +00001543
Mike Stump9afab102009-02-19 03:04:26 +00001544 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001545 // We didn't get to the end of the string. This means the component names
1546 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001547 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1548 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001549 return QualType();
1550 }
Mike Stump9afab102009-02-19 03:04:26 +00001551
Nate Begeman1486b502009-01-18 01:47:54 +00001552 // Ensure no component accessor exceeds the width of the vector type it
1553 // operates on.
1554 if (!HalvingSwizzle) {
1555 compStr = CompName.getName();
1556
1557 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001558 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001559
1560 while (*compStr) {
1561 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1562 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1563 << baseType << SourceRange(CompLoc);
1564 return QualType();
1565 }
1566 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001567 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001568
Nate Begeman1486b502009-01-18 01:47:54 +00001569 // If this is a halving swizzle, verify that the base type has an even
1570 // number of elements.
1571 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001572 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001573 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001574 return QualType();
1575 }
Mike Stump9afab102009-02-19 03:04:26 +00001576
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001577 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001578 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001579 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001580 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001581 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001582 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1583 : CompName.getLength();
1584 if (HexSwizzle)
1585 CompSize--;
1586
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001587 if (CompSize == 1)
1588 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001589
Nate Begemanaf6ed502008-04-18 23:10:10 +00001590 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001591 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001592 // diagostics look bad. We want extended vector types to appear built-in.
1593 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1594 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1595 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001596 }
1597 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001598}
1599
Chris Lattner2cb744b2009-02-15 22:43:40 +00001600
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001601/// constructSetterName - Return the setter name for the given
1602/// identifier, i.e. "set" + Name where the initial character of Name
1603/// has been capitalized.
1604// FIXME: Merge with same routine in Parser. But where should this
1605// live?
1606static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1607 const IdentifierInfo *Name) {
1608 llvm::SmallString<100> SelectorName;
1609 SelectorName = "set";
1610 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1611 SelectorName[3] = toupper(SelectorName[3]);
1612 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1613}
1614
Sebastian Redl8b769972009-01-19 00:08:26 +00001615Action::OwningExprResult
1616Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1617 tok::TokenKind OpKind, SourceLocation MemberLoc,
1618 IdentifierInfo &Member) {
1619 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001620 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001621
1622 // Perform default conversions.
1623 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001624
Steve Naroff2cb66382007-07-26 03:11:44 +00001625 QualType BaseType = BaseExpr->getType();
1626 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001627
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001628 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1629 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001630 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001631 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001632 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001633 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001634 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1635 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001636 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001637 return ExprError(Diag(MemberLoc,
1638 diag::err_typecheck_member_reference_arrow)
1639 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001640 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001641
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001642 // Handle field access to simple records. This also handles access to fields
1643 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001644 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001645 RecordDecl *RDecl = RTy->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00001646 if (DiagnoseIncompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001647 diag::err_typecheck_incomplete_tag,
1648 BaseExpr->getSourceRange()))
1649 return ExprError();
1650
Steve Naroff2cb66382007-07-26 03:11:44 +00001651 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001652 // FIXME: Qualified name lookup for C++ is a bit more complicated
1653 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001654 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001655 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001656 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001657
Douglas Gregor09be81b2009-02-04 17:27:36 +00001658 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001659 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001660 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1661 << &Member << BaseExpr->getSourceRange());
1662 else if (Result.isAmbiguous()) {
1663 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1664 MemberLoc, BaseExpr->getSourceRange());
1665 return ExprError();
1666 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001667 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001668
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001669 // If the decl being referenced had an error, return an error for this
1670 // sub-expr without emitting another error, in order to avoid cascading
1671 // error cases.
1672 if (MemberDecl->isInvalidDecl())
1673 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001674
Douglas Gregoraa57e862009-02-18 21:56:37 +00001675 // Check the use of this field
1676 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1677 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001678
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001679 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001680 // We may have found a field within an anonymous union or struct
1681 // (C++ [class.union]).
1682 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001683 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001684 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001685
Douglas Gregor82d44772008-12-20 23:49:58 +00001686 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1687 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001688 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001689 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1690 MemberType = Ref->getPointeeType();
1691 else {
1692 unsigned combinedQualifiers =
1693 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001694 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001695 combinedQualifiers &= ~QualType::Const;
1696 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1697 }
Eli Friedman76b49832008-02-06 22:48:16 +00001698
Steve Naroff774e4152009-01-21 00:14:39 +00001699 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1700 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001701 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001702 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001703 Var, MemberLoc,
1704 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001705 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001706 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001707 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001708 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001709 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001710 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001711 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001712 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001713 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1714 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001715 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001716 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1717 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001718
Douglas Gregor82d44772008-12-20 23:49:58 +00001719 // We found a declaration kind that we didn't expect. This is a
1720 // generic error message that tells the user that she can't refer
1721 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001722 return ExprError(Diag(MemberLoc,
1723 diag::err_typecheck_member_reference_unknown)
1724 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001725 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001726
Chris Lattnere9d71612008-07-21 04:59:05 +00001727 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1728 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001729 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001730 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001731 // If the decl being referenced had an error, return an error for this
1732 // sub-expr without emitting another error, in order to avoid cascading
1733 // error cases.
1734 if (IV->isInvalidDecl())
1735 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001736
1737 // Check whether we can reference this field.
1738 if (DiagnoseUseOfDecl(IV, MemberLoc))
1739 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001740
1741 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001742 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001743 OpKind == tok::arrow);
1744 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001745 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001746 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001747 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1748 << IFTy->getDecl()->getDeclName() << &Member
1749 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001750 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001751
Chris Lattnere9d71612008-07-21 04:59:05 +00001752 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1753 // pointer to a (potentially qualified) interface type.
1754 const PointerType *PTy;
1755 const ObjCInterfaceType *IFTy;
1756 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1757 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1758 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001759
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001760 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001761 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001762 // Check whether we can reference this property.
1763 if (DiagnoseUseOfDecl(PD, MemberLoc))
1764 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001765
Steve Naroff774e4152009-01-21 00:14:39 +00001766 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001767 MemberLoc, BaseExpr));
1768 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001769
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001770 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001771 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1772 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001773 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001774 // Check whether we can reference this property.
1775 if (DiagnoseUseOfDecl(PD, MemberLoc))
1776 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001777
Steve Naroff774e4152009-01-21 00:14:39 +00001778 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001779 MemberLoc, BaseExpr));
1780 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001781
1782 // If that failed, look for an "implicit" property by seeing if the nullary
1783 // selector is implemented.
1784
1785 // FIXME: The logic for looking up nullary and unary selectors should be
1786 // shared with the code in ActOnInstanceMessage.
1787
1788 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1789 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001790
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001791 // If this reference is in an @implementation, check for 'private' methods.
1792 if (!Getter)
1793 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1794 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001795 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001796 ObjCImplementations[ClassDecl->getIdentifier()])
1797 Getter = ImpDecl->getInstanceMethod(Sel);
1798
Steve Naroff04151f32008-10-22 19:16:27 +00001799 // Look through local category implementations associated with the class.
1800 if (!Getter) {
1801 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1802 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1803 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1804 }
1805 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001806 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001807 // Check if we can reference this property.
1808 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1809 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001810
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001811 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001812 // will look for the matching setter, in case it is needed.
1813 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1814 &Member);
1815 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1816 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1817 if (!Setter) {
Mike Stump9afab102009-02-19 03:04:26 +00001818 // If this reference is in an @implementation, also check for 'private'
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001819 // methods.
1820 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1821 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001822 if (ObjCImplementationDecl *ImpDecl =
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001823 ObjCImplementations[ClassDecl->getIdentifier()])
1824 Setter = ImpDecl->getInstanceMethod(SetterSel);
1825 }
1826 // Look through local category implementations associated with the class.
1827 if (!Setter) {
1828 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1829 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1830 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1831 }
1832 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001833
Douglas Gregoraa57e862009-02-18 21:56:37 +00001834 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1835 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001836
Sebastian Redl8b769972009-01-19 00:08:26 +00001837 // FIXME: we must check that the setter has property type.
Mike Stump9afab102009-02-19 03:04:26 +00001838 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001839 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001840 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001841
1842 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1843 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001844 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001845 // Handle properties on qualified "id" protocols.
1846 const ObjCQualifiedIdType *QIdTy;
1847 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1848 // Check protocols on qualified interfaces.
1849 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001850 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001851 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001852 // Check the use of this declaration
1853 if (DiagnoseUseOfDecl(PD, MemberLoc))
1854 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001855
Steve Naroff774e4152009-01-21 00:14:39 +00001856 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001857 MemberLoc, BaseExpr));
1858 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001859 // Also must look for a getter name which uses property syntax.
1860 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1861 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001862 // Check the use of this method.
1863 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1864 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001865
1866 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001867 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001868 }
1869 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001870
1871 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1872 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001873 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001874 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001875 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001876 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1877 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001878 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001879 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00001880 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001881 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001882
1883 return ExprError(Diag(MemberLoc,
1884 diag::err_typecheck_member_reference_struct_union)
1885 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001886}
1887
Douglas Gregor3257fb52008-12-22 05:46:06 +00001888/// ConvertArgumentsForCall - Converts the arguments specified in
1889/// Args/NumArgs to the parameter types of the function FDecl with
1890/// function prototype Proto. Call is the call expression itself, and
1891/// Fn is the function expression. For a C++ member function, this
1892/// routine does not attempt to convert the object argument. Returns
1893/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00001894bool
1895Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001896 FunctionDecl *FDecl,
1897 const FunctionTypeProto *Proto,
1898 Expr **Args, unsigned NumArgs,
1899 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00001900 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00001901 // assignment, to the types of the corresponding parameter, ...
1902 unsigned NumArgsInProto = Proto->getNumArgs();
1903 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001904 bool Invalid = false;
1905
Douglas Gregor3257fb52008-12-22 05:46:06 +00001906 // If too few arguments are available (and we don't have default
1907 // arguments for the remaining parameters), don't make the call.
1908 if (NumArgs < NumArgsInProto) {
1909 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1910 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1911 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1912 // Use default arguments for missing arguments
1913 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001914 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001915 }
1916
1917 // If too many are passed and not variadic, error on the extras and drop
1918 // them.
1919 if (NumArgs > NumArgsInProto) {
1920 if (!Proto->isVariadic()) {
1921 Diag(Args[NumArgsInProto]->getLocStart(),
1922 diag::err_typecheck_call_too_many_args)
1923 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1924 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1925 Args[NumArgs-1]->getLocEnd());
1926 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001927 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001928 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001929 }
1930 NumArgsToCheck = NumArgsInProto;
1931 }
Mike Stump9afab102009-02-19 03:04:26 +00001932
Douglas Gregor3257fb52008-12-22 05:46:06 +00001933 // Continue to check argument types (even if we have too few/many args).
1934 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1935 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00001936
Douglas Gregor3257fb52008-12-22 05:46:06 +00001937 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001938 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001939 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001940
1941 // Pass the argument.
1942 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1943 return true;
Mike Stump9afab102009-02-19 03:04:26 +00001944 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001945 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001946 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001947 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00001948
Douglas Gregor3257fb52008-12-22 05:46:06 +00001949 Call->setArg(i, Arg);
1950 }
Mike Stump9afab102009-02-19 03:04:26 +00001951
Douglas Gregor3257fb52008-12-22 05:46:06 +00001952 // If this is a variadic call, handle args passed through "...".
1953 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001954 VariadicCallType CallType = VariadicFunction;
1955 if (Fn->getType()->isBlockPointerType())
1956 CallType = VariadicBlock; // Block
1957 else if (isa<MemberExpr>(Fn))
1958 CallType = VariadicMethod;
1959
Douglas Gregor3257fb52008-12-22 05:46:06 +00001960 // Promote the arguments (C99 6.5.2.2p7).
1961 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1962 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001963 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001964 Call->setArg(i, Arg);
1965 }
1966 }
1967
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001968 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001969}
1970
Steve Naroff87d58b42007-09-16 03:34:24 +00001971/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001972/// This provides the location of the left/right parens and a list of comma
1973/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001974Action::OwningExprResult
1975Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1976 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001977 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001978 unsigned NumArgs = args.size();
1979 Expr *Fn = static_cast<Expr *>(fn.release());
1980 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001981 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001982 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001983 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001984
Douglas Gregor3257fb52008-12-22 05:46:06 +00001985 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001986 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00001987 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001988 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1989 bool Dependent = false;
1990 if (Fn->isTypeDependent())
1991 Dependent = true;
1992 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1993 Dependent = true;
1994
1995 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001996 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001997 Context.DependentTy, RParenLoc));
1998
1999 // Determine whether this is a call to an object (C++ [over.call.object]).
2000 if (Fn->getType()->isRecordType())
2001 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2002 CommaLocs, RParenLoc));
2003
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002004 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002005 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2006 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2007 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002008 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2009 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002010 }
2011
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002012 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002013 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002014 Expr *FnExpr = Fn;
2015 bool ADL = true;
2016 while (true) {
2017 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2018 FnExpr = IcExpr->getSubExpr();
2019 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002020 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002021 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002022 ADL = false;
2023 FnExpr = PExpr->getSubExpr();
2024 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002025 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002026 == UnaryOperator::AddrOf) {
2027 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002028 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2029 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2030 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2031 break;
Mike Stump9afab102009-02-19 03:04:26 +00002032 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002033 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2034 UnqualifiedName = DepName->getName();
2035 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002036 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002037 // Any kind of name that does not refer to a declaration (or
2038 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2039 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002040 break;
2041 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002042 }
Mike Stump9afab102009-02-19 03:04:26 +00002043
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002044 OverloadedFunctionDecl *Ovl = 0;
2045 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002046 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002047 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2048 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002049
Douglas Gregorfcb19192009-02-11 23:02:49 +00002050 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002051 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002052 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002053 ADL = false;
2054
Douglas Gregorfcb19192009-02-11 23:02:49 +00002055 // We don't perform ADL in C.
2056 if (!getLangOptions().CPlusPlus)
2057 ADL = false;
2058
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002059 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002060 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2061 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002062 NumArgs, CommaLocs, RParenLoc, ADL);
2063 if (!FDecl)
2064 return ExprError();
2065
2066 // Update Fn to refer to the actual function selected.
2067 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002068 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002069 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stump9afab102009-02-19 03:04:26 +00002070 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2071 QDRExpr->getLocation(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002072 false, false,
2073 QDRExpr->getSourceRange().getBegin());
2074 else
Mike Stump9afab102009-02-19 03:04:26 +00002075 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002076 Fn->getSourceRange().getBegin());
2077 Fn->Destroy(Context);
2078 Fn = NewFn;
2079 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002080 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002081
2082 // Promote the function operand.
2083 UsualUnaryConversions(Fn);
2084
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002085 // Make the call expr early, before semantic checks. This guarantees cleanup
2086 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002087 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2088 Args, NumArgs,
2089 Context.BoolTy,
2090 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002091
Steve Naroffd6163f32008-09-05 22:11:13 +00002092 const FunctionType *FuncT;
2093 if (!Fn->getType()->isBlockPointerType()) {
2094 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2095 // have type pointer to function".
2096 const PointerType *PT = Fn->getType()->getAsPointerType();
2097 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002098 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2099 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002100 FuncT = PT->getPointeeType()->getAsFunctionType();
2101 } else { // This is a block call.
2102 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2103 getAsFunctionType();
2104 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002105 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002106 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2107 << Fn->getType() << Fn->getSourceRange());
2108
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002109 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002110 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002111
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002112 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002113 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002114 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002115 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002116 } else {
2117 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002118
Steve Naroffdb65e052007-08-28 23:30:39 +00002119 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002120 for (unsigned i = 0; i != NumArgs; i++) {
2121 Expr *Arg = Args[i];
2122 DefaultArgumentPromotion(Arg);
2123 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002124 }
Chris Lattner4b009652007-07-25 00:24:17 +00002125 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002126
Douglas Gregor3257fb52008-12-22 05:46:06 +00002127 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2128 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002129 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2130 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002131
Chris Lattner2e64c072007-08-10 20:18:51 +00002132 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002133 if (FDecl)
2134 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002135
Sebastian Redl8b769972009-01-19 00:08:26 +00002136 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002137}
2138
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002139Action::OwningExprResult
2140Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2141 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002142 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002143 QualType literalType = QualType::getFromOpaquePtr(Ty);
2144 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002145 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002146 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002147
Eli Friedman8c2173d2008-05-20 05:22:08 +00002148 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002149 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002150 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2151 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002152 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2153 diag::err_typecheck_decl_incomplete_type,
2154 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002155 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002156
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002157 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002158 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002159 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002160
Chris Lattnere5cb5862008-12-04 23:50:19 +00002161 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002162 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002163 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002164 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002165 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002166 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002167 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002168 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002169}
2170
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002171Action::OwningExprResult
2172Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2173 InitListDesignations &Designators,
2174 SourceLocation RBraceLoc) {
2175 unsigned NumInit = initlist.size();
2176 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002177
Steve Naroff0acc9c92007-09-15 18:49:24 +00002178 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002179 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002180
Mike Stump9afab102009-02-19 03:04:26 +00002181 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002182 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002183 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002184 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002185}
2186
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002187/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002188bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002189 UsualUnaryConversions(castExpr);
2190
2191 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2192 // type needs to be scalar.
2193 if (castType->isVoidType()) {
2194 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002195 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2196 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002197 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002198 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2199 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2200 (castType->isStructureType() || castType->isUnionType())) {
2201 // GCC struct/union extension: allow cast to self.
2202 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2203 << castType << castExpr->getSourceRange();
2204 } else if (castType->isUnionType()) {
2205 // GCC cast to union extension
2206 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2207 RecordDecl::field_iterator Field, FieldEnd;
2208 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2209 Field != FieldEnd; ++Field) {
2210 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2211 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2212 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2213 << castExpr->getSourceRange();
2214 break;
2215 }
2216 }
2217 if (Field == FieldEnd)
2218 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2219 << castExpr->getType() << castExpr->getSourceRange();
2220 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002221 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002222 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002223 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002224 }
Mike Stump9afab102009-02-19 03:04:26 +00002225 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002226 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002227 return Diag(castExpr->getLocStart(),
2228 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002229 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002230 } else if (castExpr->getType()->isVectorType()) {
2231 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2232 return true;
2233 } else if (castType->isVectorType()) {
2234 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2235 return true;
2236 }
2237 return false;
2238}
2239
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002240bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002241 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002242
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002243 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002244 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002245 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002246 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002247 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002248 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002249 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002250 } else
2251 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002252 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002253 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002254
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002255 return false;
2256}
2257
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002258Action::OwningExprResult
2259Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2260 SourceLocation RParenLoc, ExprArg Op) {
2261 assert((Ty != 0) && (Op.get() != 0) &&
2262 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002263
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002264 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002265 QualType castType = QualType::getFromOpaquePtr(Ty);
2266
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002267 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002268 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002269 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002270 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002271}
2272
Chris Lattner98a425c2007-11-26 01:40:58 +00002273/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2274/// In that case, lex = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002275/// C99 6.5.15
2276QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2277 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002278 UsualUnaryConversions(Cond);
2279 UsualUnaryConversions(LHS);
2280 UsualUnaryConversions(RHS);
2281 QualType CondTy = Cond->getType();
2282 QualType LHSTy = LHS->getType();
2283 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002284
2285 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002286 if (!Cond->isTypeDependent()) {
2287 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2288 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2289 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002290 return QualType();
2291 }
Chris Lattner4b009652007-07-25 00:24:17 +00002292 }
Mike Stump9afab102009-02-19 03:04:26 +00002293
Chris Lattner992ae932008-01-06 22:42:25 +00002294 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002295 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002296 return Context.DependentTy;
2297
Chris Lattner992ae932008-01-06 22:42:25 +00002298 // If both operands have arithmetic type, do the usual arithmetic conversions
2299 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002300 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2301 UsualArithmeticConversions(LHS, RHS);
2302 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002303 }
Mike Stump9afab102009-02-19 03:04:26 +00002304
Chris Lattner992ae932008-01-06 22:42:25 +00002305 // If both operands are the same structure or union type, the result is that
2306 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002307 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2308 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002309 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002310 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002311 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002312 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002313 }
Mike Stump9afab102009-02-19 03:04:26 +00002314
Chris Lattner992ae932008-01-06 22:42:25 +00002315 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002316 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002317 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2318 if (!LHSTy->isVoidType())
2319 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2320 << RHS->getSourceRange();
2321 if (!RHSTy->isVoidType())
2322 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2323 << LHS->getSourceRange();
2324 ImpCastExprToType(LHS, Context.VoidTy);
2325 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002326 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002327 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002328 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2329 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002330 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2331 Context.isObjCObjectPointerType(LHSTy)) &&
2332 RHS->isNullPointerConstant(Context)) {
2333 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2334 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002335 }
Chris Lattnere2897262009-02-18 04:28:32 +00002336 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2337 Context.isObjCObjectPointerType(RHSTy)) &&
2338 LHS->isNullPointerConstant(Context)) {
2339 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2340 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002341 }
Mike Stump9afab102009-02-19 03:04:26 +00002342
Chris Lattner0ac51632008-01-06 22:50:31 +00002343 // Handle the case where both operands are pointers before we handle null
2344 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002345 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2346 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002347 // get the "pointed to" types
2348 QualType lhptee = LHSPT->getPointeeType();
2349 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002350
Chris Lattner71225142007-07-31 21:27:01 +00002351 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2352 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002353 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002354 // Figure out necessary qualifiers (C99 6.5.15p6)
2355 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002356 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002357 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2358 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002359 return destType;
2360 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002361 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002362 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002363 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002364 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2365 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002366 return destType;
2367 }
Chris Lattner4b009652007-07-25 00:24:17 +00002368
Chris Lattner9c039b52009-02-18 04:38:20 +00002369 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002370 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002371 return LHSTy;
2372 }
Mike Stump9afab102009-02-19 03:04:26 +00002373
Chris Lattnere2897262009-02-18 04:28:32 +00002374 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002375
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002376 // If either type is an Objective-C object type then check
2377 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002378 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002379 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002380 // If both operands are interfaces and either operand can be
2381 // assigned to the other, use that type as the composite
2382 // type. This allows
2383 // xxx ? (A*) a : (B*) b
2384 // where B is a subclass of A.
2385 //
2386 // Additionally, as for assignment, if either type is 'id'
2387 // allow silent coercion. Finally, if the types are
2388 // incompatible then make sure to use 'id' as the composite
2389 // type so the result is acceptable for sending messages to.
2390
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002391 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002392 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002393 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2394 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2395 if (LHSIface && RHSIface &&
2396 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002397 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002398 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002399 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002400 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002401 } else if (Context.isObjCIdStructType(lhptee) ||
2402 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002403 compositeType = Context.getObjCIdType();
2404 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002405 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002406 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002407 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002408 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002409 ImpCastExprToType(LHS, incompatTy);
2410 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002411 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002412 }
Mike Stump9afab102009-02-19 03:04:26 +00002413 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002414 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002415 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2416 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002417 // In this situation, we assume void* type. No especially good
2418 // reason, but this is what gcc does, and we do have to pick
2419 // to get a consistent AST.
2420 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002421 ImpCastExprToType(LHS, incompatTy);
2422 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002423 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002424 }
2425 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002426 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2427 // differently qualified versions of compatible types, the result type is
2428 // a pointer to an appropriately qualified version of the *composite*
2429 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002430 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002431 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002432 ImpCastExprToType(LHS, compositeType);
2433 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002434 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002435 }
Chris Lattner4b009652007-07-25 00:24:17 +00002436 }
Mike Stump9afab102009-02-19 03:04:26 +00002437
Chris Lattner9c039b52009-02-18 04:38:20 +00002438 // Selection between block pointer types is ok as long as they are the same.
2439 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2440 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2441 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002442
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002443 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2444 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002445 // id with statically typed objects).
2446 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002447 // GCC allows qualified id and any Objective-C type to devolve to
2448 // id. Currently localizing to here until clear this should be
2449 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002450 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002451 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002452 Context.isObjCObjectPointerType(RHSTy)) ||
2453 (RHSTy->isObjCQualifiedIdType() &&
2454 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002455 // FIXME: This is not the correct composite type. This only
2456 // happens to work because id can more or less be used anywhere,
2457 // however this may change the type of method sends.
2458 // FIXME: gcc adds some type-checking of the arguments and emits
2459 // (confusing) incompatible comparison warnings in some
2460 // cases. Investigate.
2461 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002462 ImpCastExprToType(LHS, compositeType);
2463 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002464 return compositeType;
2465 }
2466 }
2467
Chris Lattner992ae932008-01-06 22:42:25 +00002468 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002469 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2470 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002471 return QualType();
2472}
2473
Steve Naroff87d58b42007-09-16 03:34:24 +00002474/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002475/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002476Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2477 SourceLocation ColonLoc,
2478 ExprArg Cond, ExprArg LHS,
2479 ExprArg RHS) {
2480 Expr *CondExpr = (Expr *) Cond.get();
2481 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002482
2483 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2484 // was the condition.
2485 bool isLHSNull = LHSExpr == 0;
2486 if (isLHSNull)
2487 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002488
2489 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002490 RHSExpr, QuestionLoc);
2491 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002492 return ExprError();
2493
2494 Cond.release();
2495 LHS.release();
2496 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002497 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002498 isLHSNull ? 0 : LHSExpr,
2499 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002500}
2501
Chris Lattner4b009652007-07-25 00:24:17 +00002502
2503// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002504// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002505// routine is it effectively iqnores the qualifiers on the top level pointee.
2506// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2507// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002508Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002509Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2510 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002511
Chris Lattner4b009652007-07-25 00:24:17 +00002512 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002513 lhptee = lhsType->getAsPointerType()->getPointeeType();
2514 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002515
Chris Lattner4b009652007-07-25 00:24:17 +00002516 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002517 lhptee = Context.getCanonicalType(lhptee);
2518 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002519
Chris Lattner005ed752008-01-04 18:04:52 +00002520 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002521
2522 // C99 6.5.16.1p1: This following citation is common to constraints
2523 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2524 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002525 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002526 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002527 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002528
Mike Stump9afab102009-02-19 03:04:26 +00002529 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2530 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002531 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002532 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002533 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002534 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002535
Chris Lattner4ca3d772008-01-03 22:56:36 +00002536 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002537 assert(rhptee->isFunctionType());
2538 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002539 }
Mike Stump9afab102009-02-19 03:04:26 +00002540
Chris Lattner4ca3d772008-01-03 22:56:36 +00002541 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002542 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002543 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002544
2545 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002546 assert(lhptee->isFunctionType());
2547 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002548 }
Mike Stump9afab102009-02-19 03:04:26 +00002549 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002550 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002551 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002552 rhptee.getUnqualifiedType()))
2553 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002554 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002555}
2556
Steve Naroff3454b6c2008-09-04 15:10:53 +00002557/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2558/// block pointer types are compatible or whether a block and normal pointer
2559/// are compatible. It is more restrict than comparing two function pointer
2560// types.
Mike Stump9afab102009-02-19 03:04:26 +00002561Sema::AssignConvertType
2562Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002563 QualType rhsType) {
2564 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002565
Steve Naroff3454b6c2008-09-04 15:10:53 +00002566 // get the "pointed to" type (ignoring qualifiers at the top level)
2567 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002568 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2569
Steve Naroff3454b6c2008-09-04 15:10:53 +00002570 // make sure we operate on the canonical type
2571 lhptee = Context.getCanonicalType(lhptee);
2572 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002573
Steve Naroff3454b6c2008-09-04 15:10:53 +00002574 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002575
Steve Naroff3454b6c2008-09-04 15:10:53 +00002576 // For blocks we enforce that qualifiers are identical.
2577 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2578 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002579
Steve Naroff3454b6c2008-09-04 15:10:53 +00002580 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002581 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002582 return ConvTy;
2583}
2584
Mike Stump9afab102009-02-19 03:04:26 +00002585/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2586/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002587/// pointers. Here are some objectionable examples that GCC considers warnings:
2588///
2589/// int a, *pint;
2590/// short *pshort;
2591/// struct foo *pfoo;
2592///
2593/// pint = pshort; // warning: assignment from incompatible pointer type
2594/// a = pint; // warning: assignment makes integer from pointer without a cast
2595/// pint = a; // warning: assignment makes pointer from integer without a cast
2596/// pint = pfoo; // warning: assignment from incompatible pointer type
2597///
2598/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002599/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002600///
Chris Lattner005ed752008-01-04 18:04:52 +00002601Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002602Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002603 // Get canonical types. We're not formatting these types, just comparing
2604 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002605 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2606 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002607
2608 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002609 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002610
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002611 // If the left-hand side is a reference type, then we are in a
2612 // (rare!) case where we've allowed the use of references in C,
2613 // e.g., as a parameter type in a built-in function. In this case,
2614 // just make sure that the type referenced is compatible with the
2615 // right-hand side type. The caller is responsible for adjusting
2616 // lhsType so that the resulting expression does not have reference
2617 // type.
2618 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2619 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002620 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002621 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002622 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002623
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002624 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2625 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002626 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002627 // Relax integer conversions like we do for pointers below.
2628 if (rhsType->isIntegerType())
2629 return IntToPointer;
2630 if (lhsType->isIntegerType())
2631 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002632 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002633 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002634
Nate Begemanc5f0f652008-07-14 18:02:46 +00002635 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002636 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002637 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2638 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002639 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002640
Nate Begemanc5f0f652008-07-14 18:02:46 +00002641 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002642 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002643 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002644 if (getLangOptions().LaxVectorConversions &&
2645 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002646 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002647 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002648 }
2649 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002650 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002651
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002652 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002653 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002654
Chris Lattner390564e2008-04-07 06:49:41 +00002655 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002656 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002657 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002658
Chris Lattner390564e2008-04-07 06:49:41 +00002659 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002660 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002661
Steve Naroffa982c712008-09-29 18:10:17 +00002662 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002663 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002664 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002665
2666 // Treat block pointers as objects.
2667 if (getLangOptions().ObjC1 &&
2668 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2669 return Compatible;
2670 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002671 return Incompatible;
2672 }
2673
2674 if (isa<BlockPointerType>(lhsType)) {
2675 if (rhsType->isIntegerType())
2676 return IntToPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002677
Steve Naroffa982c712008-09-29 18:10:17 +00002678 // Treat block pointers as objects.
2679 if (getLangOptions().ObjC1 &&
2680 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2681 return Compatible;
2682
Steve Naroff3454b6c2008-09-04 15:10:53 +00002683 if (rhsType->isBlockPointerType())
2684 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002685
Steve Naroff3454b6c2008-09-04 15:10:53 +00002686 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2687 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002688 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002689 }
Chris Lattner1853da22008-01-04 23:18:45 +00002690 return Incompatible;
2691 }
2692
Chris Lattner390564e2008-04-07 06:49:41 +00002693 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002694 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002695 if (lhsType == Context.BoolTy)
2696 return Compatible;
2697
2698 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002699 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002700
Mike Stump9afab102009-02-19 03:04:26 +00002701 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002702 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002703
2704 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002705 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002706 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002707 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002708 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002709
Chris Lattner1853da22008-01-04 23:18:45 +00002710 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002711 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002712 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002713 }
2714 return Incompatible;
2715}
2716
Chris Lattner005ed752008-01-04 18:04:52 +00002717Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002718Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002719 if (getLangOptions().CPlusPlus) {
2720 if (!lhsType->isRecordType()) {
2721 // C++ 5.17p3: If the left operand is not of class type, the
2722 // expression is implicitly converted (C++ 4) to the
2723 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002724 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2725 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002726 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002727 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002728 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002729 }
2730
2731 // FIXME: Currently, we fall through and treat C++ classes like C
2732 // structures.
2733 }
2734
Steve Naroffcdee22d2007-11-27 17:58:44 +00002735 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2736 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002737 if ((lhsType->isPointerType() ||
2738 lhsType->isObjCQualifiedIdType() ||
2739 lhsType->isObjCQualifiedClassType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002740 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002741 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002742 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002743 return Compatible;
2744 }
Mike Stump9afab102009-02-19 03:04:26 +00002745
Steve Naroff3454b6c2008-09-04 15:10:53 +00002746 // We don't allow conversion of non-null-pointer constants to integers.
2747 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2748 return IntToBlockPointer;
2749
Chris Lattner5f505bf2007-10-16 02:55:40 +00002750 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002751 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002752 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002753 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002754 //
Mike Stump9afab102009-02-19 03:04:26 +00002755 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002756 if (!lhsType->isReferenceType())
2757 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002758
Chris Lattner005ed752008-01-04 18:04:52 +00002759 Sema::AssignConvertType result =
2760 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002761
Steve Naroff0f32f432007-08-24 22:33:52 +00002762 // C99 6.5.16.1p2: The value of the right operand is converted to the
2763 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002764 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2765 // so that we can use references in built-in functions even in C.
2766 // The getNonReferenceType() call makes sure that the resulting expression
2767 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002768 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002769 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002770 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002771}
2772
Chris Lattner005ed752008-01-04 18:04:52 +00002773Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002774Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2775 return CheckAssignmentConstraints(lhsType, rhsType);
2776}
2777
Chris Lattner1eafdea2008-11-18 01:30:42 +00002778QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002779 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002780 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002781 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002782 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002783}
2784
Mike Stump9afab102009-02-19 03:04:26 +00002785inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002786 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002787 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002788 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002789 QualType lhsType =
2790 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2791 QualType rhsType =
2792 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002793
Nate Begemanc5f0f652008-07-14 18:02:46 +00002794 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002795 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002796 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002797
Nate Begemanc5f0f652008-07-14 18:02:46 +00002798 // Handle the case of a vector & extvector type of the same size and element
2799 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002800 if (getLangOptions().LaxVectorConversions) {
2801 // FIXME: Should we warn here?
2802 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002803 if (const VectorType *RV = rhsType->getAsVectorType())
2804 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002805 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002806 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002807 }
2808 }
2809 }
Mike Stump9afab102009-02-19 03:04:26 +00002810
Nate Begemanc5f0f652008-07-14 18:02:46 +00002811 // If the lhs is an extended vector and the rhs is a scalar of the same type
2812 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002813 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002814 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002815
2816 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002817 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2818 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002819 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002820 return lhsType;
2821 }
2822 }
2823
Nate Begemanc5f0f652008-07-14 18:02:46 +00002824 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002825 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002826 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002827 QualType eltType = V->getElementType();
2828
Mike Stump9afab102009-02-19 03:04:26 +00002829 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002830 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2831 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002832 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002833 return rhsType;
2834 }
2835 }
2836
Chris Lattner4b009652007-07-25 00:24:17 +00002837 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002838 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002839 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002840 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002841 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002842}
2843
Chris Lattner4b009652007-07-25 00:24:17 +00002844inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002845 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002846{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002847 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002848 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002849
Steve Naroff8f708362007-08-24 19:07:16 +00002850 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002851
Chris Lattner4b009652007-07-25 00:24:17 +00002852 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002853 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002854 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002855}
2856
2857inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002858 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002859{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002860 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2861 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2862 return CheckVectorOperands(Loc, lex, rex);
2863 return InvalidOperands(Loc, lex, rex);
2864 }
Chris Lattner4b009652007-07-25 00:24:17 +00002865
Steve Naroff8f708362007-08-24 19:07:16 +00002866 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002867
Chris Lattner4b009652007-07-25 00:24:17 +00002868 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002869 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002870 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002871}
2872
2873inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00002874 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002875{
2876 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002877 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002878
Steve Naroff8f708362007-08-24 19:07:16 +00002879 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002880
Chris Lattner4b009652007-07-25 00:24:17 +00002881 // handle the common case first (both operands are arithmetic).
2882 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002883 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002884
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002885 // Put any potential pointer into PExp
2886 Expr* PExp = lex, *IExp = rex;
2887 if (IExp->getType()->isPointerType())
2888 std::swap(PExp, IExp);
2889
2890 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2891 if (IExp->getType()->isIntegerType()) {
2892 // Check for arithmetic on pointers to incomplete types
2893 if (!PTy->getPointeeType()->isObjectType()) {
2894 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002895 if (getLangOptions().CPlusPlus) {
2896 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2897 << lex->getSourceRange() << rex->getSourceRange();
2898 return QualType();
2899 }
2900
2901 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002902 Diag(Loc, diag::ext_gnu_void_ptr)
2903 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002904 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002905 if (getLangOptions().CPlusPlus) {
2906 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2907 << lex->getType() << lex->getSourceRange();
2908 return QualType();
2909 }
2910
2911 // GNU extension: arithmetic on pointer to function
2912 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002913 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002914 } else {
Mike Stump9afab102009-02-19 03:04:26 +00002915 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002916 diag::err_typecheck_arithmetic_incomplete_type,
2917 lex->getSourceRange(), SourceRange(),
2918 lex->getType());
2919 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002920 }
2921 }
2922 return PExp->getType();
2923 }
2924 }
2925
Chris Lattner1eafdea2008-11-18 01:30:42 +00002926 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002927}
2928
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002929// C99 6.5.6
2930QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002931 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002932 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002933 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002934
Steve Naroff8f708362007-08-24 19:07:16 +00002935 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002936
Chris Lattnerf6da2912007-12-09 21:53:25 +00002937 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00002938
Chris Lattnerf6da2912007-12-09 21:53:25 +00002939 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002940 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002941 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00002942
Chris Lattnerf6da2912007-12-09 21:53:25 +00002943 // Either ptr - int or ptr - ptr.
2944 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002945 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002946
Chris Lattnerf6da2912007-12-09 21:53:25 +00002947 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002948 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002949 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002950 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002951 Diag(Loc, diag::ext_gnu_void_ptr)
2952 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002953 } else if (lpointee->isFunctionType()) {
2954 if (getLangOptions().CPlusPlus) {
2955 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2956 << lex->getType() << lex->getSourceRange();
2957 return QualType();
2958 }
2959
2960 // GNU extension: arithmetic on pointer to function
2961 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2962 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002963 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002964 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002965 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002966 return QualType();
2967 }
2968 }
2969
2970 // The result type of a pointer-int computation is the pointer type.
2971 if (rex->getType()->isIntegerType())
2972 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002973
Chris Lattnerf6da2912007-12-09 21:53:25 +00002974 // Handle pointer-pointer subtractions.
2975 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002976 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002977
Chris Lattnerf6da2912007-12-09 21:53:25 +00002978 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002979 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002980 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002981 if (rpointee->isVoidType()) {
2982 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002983 Diag(Loc, diag::ext_gnu_void_ptr)
2984 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002985 } else if (rpointee->isFunctionType()) {
2986 if (getLangOptions().CPlusPlus) {
2987 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2988 << rex->getType() << rex->getSourceRange();
2989 return QualType();
2990 }
Mike Stump9afab102009-02-19 03:04:26 +00002991
Douglas Gregorf93eda12009-01-23 19:03:35 +00002992 // GNU extension: arithmetic on pointer to function
2993 if (!lpointee->isFunctionType())
2994 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2995 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002996 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002997 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002998 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002999 return QualType();
3000 }
3001 }
Mike Stump9afab102009-02-19 03:04:26 +00003002
Chris Lattnerf6da2912007-12-09 21:53:25 +00003003 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003004 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003005 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003006 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003007 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003008 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003009 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003010 return QualType();
3011 }
Mike Stump9afab102009-02-19 03:04:26 +00003012
Chris Lattnerf6da2912007-12-09 21:53:25 +00003013 return Context.getPointerDiffType();
3014 }
3015 }
Mike Stump9afab102009-02-19 03:04:26 +00003016
Chris Lattner1eafdea2008-11-18 01:30:42 +00003017 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003018}
3019
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003020// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003021QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003022 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003023 // C99 6.5.7p2: Each of the operands shall have integer type.
3024 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003025 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003026
Chris Lattner2c8bff72007-12-12 05:47:28 +00003027 // Shifts don't perform usual arithmetic conversions, they just do integer
3028 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003029 if (!isCompAssign)
3030 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003031 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003032
Chris Lattner2c8bff72007-12-12 05:47:28 +00003033 // "The type of the result is that of the promoted left operand."
3034 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003035}
3036
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003037// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003038QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003039 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003040 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003041 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003042
Chris Lattner254f3bc2007-08-26 01:18:55 +00003043 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003044 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3045 UsualArithmeticConversions(lex, rex);
3046 else {
3047 UsualUnaryConversions(lex);
3048 UsualUnaryConversions(rex);
3049 }
Chris Lattner4b009652007-07-25 00:24:17 +00003050 QualType lType = lex->getType();
3051 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003052
Ted Kremenek486509e2007-10-29 17:13:39 +00003053 // For non-floating point types, check for self-comparisons of the form
3054 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3055 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003056 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003057 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3058 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003059 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003060 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003061 }
Mike Stump9afab102009-02-19 03:04:26 +00003062
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003063 // The result of comparisons is 'bool' in C++, 'int' in C.
3064 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3065
Chris Lattner254f3bc2007-08-26 01:18:55 +00003066 if (isRelational) {
3067 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003068 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003069 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003070 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003071 if (lType->isFloatingType()) {
3072 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003073 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003074 }
Mike Stump9afab102009-02-19 03:04:26 +00003075
Chris Lattner254f3bc2007-08-26 01:18:55 +00003076 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003077 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003078 }
Mike Stump9afab102009-02-19 03:04:26 +00003079
Chris Lattner22be8422007-08-26 01:10:14 +00003080 bool LHSIsNull = lex->isNullPointerConstant(Context);
3081 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003082
Chris Lattner254f3bc2007-08-26 01:18:55 +00003083 // All of the following pointer related warnings are GCC extensions, except
3084 // when handling null pointer constants. One day, we can consider making them
3085 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003086 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003087 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003088 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003089 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003090 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003091
Steve Naroff3b435622007-11-13 14:57:38 +00003092 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003093 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3094 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003095 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003096 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003097 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003098 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003099 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003100 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003101 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003102 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003103 // Handle block pointer types.
3104 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3105 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3106 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003107
Steve Naroff3454b6c2008-09-04 15:10:53 +00003108 if (!LHSIsNull && !RHSIsNull &&
3109 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003110 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003111 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003112 }
3113 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003114 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003115 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003116 // Allow block pointers to be compared with null pointer constants.
3117 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3118 (lType->isPointerType() && rType->isBlockPointerType())) {
3119 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003120 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003121 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003122 }
3123 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003124 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003125 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003126
Steve Naroff936c4362008-06-03 14:04:54 +00003127 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003128 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003129 const PointerType *LPT = lType->getAsPointerType();
3130 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003131 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003132 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003133 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003134 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003135
Steve Naroff030fcda2008-11-17 19:49:16 +00003136 if (!LPtrToVoid && !RPtrToVoid &&
3137 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003138 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003139 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003140 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003141 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003142 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003143 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003144 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003145 }
Steve Naroff936c4362008-06-03 14:04:54 +00003146 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3147 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003148 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003149 } else {
3150 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003151 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003152 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003153 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003154 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003155 }
Steve Naroff936c4362008-06-03 14:04:54 +00003156 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003157 }
Mike Stump9afab102009-02-19 03:04:26 +00003158 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003159 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003160 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003161 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003162 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003163 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003164 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003165 }
Mike Stump9afab102009-02-19 03:04:26 +00003166 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003167 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003168 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003169 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003170 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003171 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003172 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003173 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003174 // Handle block pointers.
3175 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3176 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003177 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003178 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003179 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003180 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003181 }
3182 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3183 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003184 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003185 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003186 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003187 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003188 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003189 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003190}
3191
Nate Begemanc5f0f652008-07-14 18:02:46 +00003192/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003193/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003194/// like a scalar comparison, a vector comparison produces a vector of integer
3195/// types.
3196QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003197 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003198 bool isRelational) {
3199 // Check to make sure we're operating on vectors of the same type and width,
3200 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003201 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003202 if (vType.isNull())
3203 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003204
Nate Begemanc5f0f652008-07-14 18:02:46 +00003205 QualType lType = lex->getType();
3206 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003207
Nate Begemanc5f0f652008-07-14 18:02:46 +00003208 // For non-floating point types, check for self-comparisons of the form
3209 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3210 // often indicate logic errors in the program.
3211 if (!lType->isFloatingType()) {
3212 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3213 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3214 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003215 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003216 }
Mike Stump9afab102009-02-19 03:04:26 +00003217
Nate Begemanc5f0f652008-07-14 18:02:46 +00003218 // Check for comparisons of floating point operands using != and ==.
3219 if (!isRelational && lType->isFloatingType()) {
3220 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003221 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003222 }
Mike Stump9afab102009-02-19 03:04:26 +00003223
Nate Begemanc5f0f652008-07-14 18:02:46 +00003224 // Return the type for the comparison, which is the same as vector type for
3225 // integer vectors, or an integer type of identical size and number of
3226 // elements for floating point vectors.
3227 if (lType->isIntegerType())
3228 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003229
Nate Begemanc5f0f652008-07-14 18:02:46 +00003230 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003231 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003232 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003233 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003234 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3235 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3236
Mike Stump9afab102009-02-19 03:04:26 +00003237 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003238 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003239 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3240}
3241
Chris Lattner4b009652007-07-25 00:24:17 +00003242inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003243 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003244{
3245 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003246 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003247
Steve Naroff8f708362007-08-24 19:07:16 +00003248 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003249
Chris Lattner4b009652007-07-25 00:24:17 +00003250 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003251 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003252 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003253}
3254
3255inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003256 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003257{
3258 UsualUnaryConversions(lex);
3259 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003260
Eli Friedmanbea3f842008-05-13 20:16:47 +00003261 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003262 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003263 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003264}
3265
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003266/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3267/// is a read-only property; return true if so. A readonly property expression
3268/// depends on various declarations and thus must be treated specially.
3269///
Mike Stump9afab102009-02-19 03:04:26 +00003270static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003271{
3272 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3273 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3274 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3275 QualType BaseType = PropExpr->getBase()->getType();
3276 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003277 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003278 PTy->getPointeeType()->getAsObjCInterfaceType())
3279 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3280 if (S.isPropertyReadonly(PDecl, IFace))
3281 return true;
3282 }
3283 }
3284 return false;
3285}
3286
Chris Lattner4c2642c2008-11-18 01:22:49 +00003287/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3288/// emit an error and return true. If so, return false.
3289static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003290 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3291 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3292 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003293 if (IsLV == Expr::MLV_Valid)
3294 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003295
Chris Lattner4c2642c2008-11-18 01:22:49 +00003296 unsigned Diag = 0;
3297 bool NeedType = false;
3298 switch (IsLV) { // C99 6.5.16p2
3299 default: assert(0 && "Unknown result from isModifiableLvalue!");
3300 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003301 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003302 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3303 NeedType = true;
3304 break;
Mike Stump9afab102009-02-19 03:04:26 +00003305 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003306 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3307 NeedType = true;
3308 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003309 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003310 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3311 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003312 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003313 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3314 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003315 case Expr::MLV_IncompleteType:
3316 case Expr::MLV_IncompleteVoidType:
Mike Stump9afab102009-02-19 03:04:26 +00003317 return S.DiagnoseIncompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003318 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3319 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003320 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003321 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3322 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003323 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003324 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3325 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003326 case Expr::MLV_ReadonlyProperty:
3327 Diag = diag::error_readonly_property_assignment;
3328 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003329 case Expr::MLV_NoSetterProperty:
3330 Diag = diag::error_nosetter_property_assignment;
3331 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003332 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003333
Chris Lattner4c2642c2008-11-18 01:22:49 +00003334 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003335 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003336 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003337 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003338 return true;
3339}
3340
3341
3342
3343// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003344QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3345 SourceLocation Loc,
3346 QualType CompoundType) {
3347 // Verify that LHS is a modifiable lvalue, and emit error if not.
3348 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003349 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003350
3351 QualType LHSType = LHS->getType();
3352 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003353
Chris Lattner005ed752008-01-04 18:04:52 +00003354 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003355 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003356 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003357 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003358 // Special case of NSObject attributes on c-style pointer types.
3359 if (ConvTy == IncompatiblePointer &&
3360 ((Context.isObjCNSObjectType(LHSType) &&
3361 Context.isObjCObjectPointerType(RHSType)) ||
3362 (Context.isObjCNSObjectType(RHSType) &&
3363 Context.isObjCObjectPointerType(LHSType))))
3364 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003365
Chris Lattner34c85082008-08-21 18:04:13 +00003366 // If the RHS is a unary plus or minus, check to see if they = and + are
3367 // right next to each other. If so, the user may have typo'd "x =+ 4"
3368 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003369 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003370 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3371 RHSCheck = ICE->getSubExpr();
3372 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3373 if ((UO->getOpcode() == UnaryOperator::Plus ||
3374 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003375 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003376 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003377 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003378 Diag(Loc, diag::warn_not_compound_assign)
3379 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3380 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003381 }
3382 } else {
3383 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003384 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003385 }
Chris Lattner005ed752008-01-04 18:04:52 +00003386
Chris Lattner1eafdea2008-11-18 01:30:42 +00003387 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3388 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003389 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003390
Chris Lattner4b009652007-07-25 00:24:17 +00003391 // C99 6.5.16p3: The type of an assignment expression is the type of the
3392 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003393 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003394 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3395 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003396 // C++ 5.17p1: the type of the assignment expression is that of its left
3397 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003398 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003399}
3400
Chris Lattner1eafdea2008-11-18 01:30:42 +00003401// C99 6.5.17
3402QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3403 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003404
Chris Lattner03c430f2008-07-25 20:54:07 +00003405 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003406 DefaultFunctionArrayConversion(RHS);
3407 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003408}
3409
3410/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3411/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003412QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3413 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003414 QualType ResType = Op->getType();
3415 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003416
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003417 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3418 // Decrement of bool is not allowed.
3419 if (!isInc) {
3420 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3421 return QualType();
3422 }
3423 // Increment of bool sets it to true, but is deprecated.
3424 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3425 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003426 // OK!
3427 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3428 // C99 6.5.2.4p2, 6.5.6p2
3429 if (PT->getPointeeType()->isObjectType()) {
3430 // Pointer to object is ok!
3431 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003432 if (getLangOptions().CPlusPlus) {
3433 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3434 << Op->getSourceRange();
3435 return QualType();
3436 }
3437
3438 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003439 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003440 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003441 if (getLangOptions().CPlusPlus) {
3442 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3443 << Op->getType() << Op->getSourceRange();
3444 return QualType();
3445 }
3446
3447 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003448 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003449 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003450 } else {
Mike Stump9afab102009-02-19 03:04:26 +00003451 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003452 diag::err_typecheck_arithmetic_incomplete_type,
3453 Op->getSourceRange(), SourceRange(),
3454 ResType);
3455 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003456 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003457 } else if (ResType->isComplexType()) {
3458 // C99 does not support ++/-- on complex types, we allow as an extension.
3459 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003460 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003461 } else {
3462 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003463 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003464 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003465 }
Mike Stump9afab102009-02-19 03:04:26 +00003466 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003467 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003468 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003469 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003470 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003471}
3472
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003473/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003474/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003475/// where the declaration is needed for type checking. We only need to
3476/// handle cases when the expression references a function designator
3477/// or is an lvalue. Here are some examples:
3478/// - &(x) => x
3479/// - &*****f => f for f a function designator.
3480/// - &s.xx => s
3481/// - &s.zz[1].yy -> s, if zz is an array
3482/// - *(x + 1) -> x, if x is an array
3483/// - &"123"[2] -> 0
3484/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003485static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003486 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003487 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003488 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003489 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003490 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003491 // Fields cannot be declared with a 'register' storage class.
3492 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003493 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003494 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003495 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003496 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003497 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003498
Douglas Gregord2baafd2008-10-21 16:13:35 +00003499 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003500 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003501 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003502 return 0;
3503 else
3504 return VD;
3505 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003506 case Stmt::UnaryOperatorClass: {
3507 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003508
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003509 switch(UO->getOpcode()) {
3510 case UnaryOperator::Deref: {
3511 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003512 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3513 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3514 if (!VD || VD->getType()->isPointerType())
3515 return 0;
3516 return VD;
3517 }
3518 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003519 }
3520 case UnaryOperator::Real:
3521 case UnaryOperator::Imag:
3522 case UnaryOperator::Extension:
3523 return getPrimaryDecl(UO->getSubExpr());
3524 default:
3525 return 0;
3526 }
3527 }
3528 case Stmt::BinaryOperatorClass: {
3529 BinaryOperator *BO = cast<BinaryOperator>(E);
3530
3531 // Handle cases involving pointer arithmetic. The result of an
3532 // Assign or AddAssign is not an lvalue so they can be ignored.
3533
3534 // (x + n) or (n + x) => x
3535 if (BO->getOpcode() == BinaryOperator::Add) {
3536 if (BO->getLHS()->getType()->isPointerType()) {
3537 return getPrimaryDecl(BO->getLHS());
3538 } else if (BO->getRHS()->getType()->isPointerType()) {
3539 return getPrimaryDecl(BO->getRHS());
3540 }
3541 }
3542
3543 return 0;
3544 }
Chris Lattner4b009652007-07-25 00:24:17 +00003545 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003546 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003547 case Stmt::ImplicitCastExprClass:
3548 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003549 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003550 default:
3551 return 0;
3552 }
3553}
3554
3555/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003556/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003557/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003558/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003559/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003560/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003561/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003562QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003563 if (op->isTypeDependent())
3564 return Context.DependentTy;
3565
Steve Naroff9c6c3592008-01-13 17:10:08 +00003566 if (getLangOptions().C99) {
3567 // Implement C99-only parts of addressof rules.
3568 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3569 if (uOp->getOpcode() == UnaryOperator::Deref)
3570 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3571 // (assuming the deref expression is valid).
3572 return uOp->getSubExpr()->getType();
3573 }
3574 // Technically, there should be a check for array subscript
3575 // expressions here, but the result of one is always an lvalue anyway.
3576 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003577 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003578 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003579
Chris Lattner4b009652007-07-25 00:24:17 +00003580 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003581 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3582 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003583 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3584 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003585 return QualType();
3586 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003587 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003588 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3589 if (Field->isBitField()) {
3590 Diag(OpLoc, diag::err_typecheck_address_of)
3591 << "bit-field" << op->getSourceRange();
3592 return QualType();
3593 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003594 }
3595 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003596 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3597 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003598 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003599 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003600 return QualType();
3601 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003602 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003603 // with the register storage-class specifier.
3604 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3605 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003606 Diag(OpLoc, diag::err_typecheck_address_of)
3607 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003608 return QualType();
3609 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003610 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003611 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003612 } else if (isa<FieldDecl>(dcl)) {
3613 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003614 // Could be a pointer to member, though, if there is an explicit
3615 // scope qualifier for the class.
3616 if (isa<QualifiedDeclRefExpr>(op)) {
3617 DeclContext *Ctx = dcl->getDeclContext();
3618 if (Ctx && Ctx->isRecord())
3619 return Context.getMemberPointerType(op->getType(),
3620 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3621 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003622 } else if (isa<FunctionDecl>(dcl)) {
3623 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003624 // As above.
3625 if (isa<QualifiedDeclRefExpr>(op)) {
3626 DeclContext *Ctx = dcl->getDeclContext();
3627 if (Ctx && Ctx->isRecord())
3628 return Context.getMemberPointerType(op->getType(),
3629 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3630 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003631 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003632 else
Chris Lattner4b009652007-07-25 00:24:17 +00003633 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003634 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003635
Chris Lattner4b009652007-07-25 00:24:17 +00003636 // If the operand has type "type", the result has type "pointer to type".
3637 return Context.getPointerType(op->getType());
3638}
3639
Chris Lattnerda5c0872008-11-23 09:13:29 +00003640QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3641 UsualUnaryConversions(Op);
3642 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003643
Chris Lattnerda5c0872008-11-23 09:13:29 +00003644 // Note that per both C89 and C99, this is always legal, even if ptype is an
3645 // incomplete type or void. It would be possible to warn about dereferencing
3646 // a void pointer, but it's completely well-defined, and such a warning is
3647 // unlikely to catch any mistakes.
3648 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003649 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003650
Chris Lattner77d52da2008-11-20 06:06:08 +00003651 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003652 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003653 return QualType();
3654}
3655
3656static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3657 tok::TokenKind Kind) {
3658 BinaryOperator::Opcode Opc;
3659 switch (Kind) {
3660 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003661 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3662 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003663 case tok::star: Opc = BinaryOperator::Mul; break;
3664 case tok::slash: Opc = BinaryOperator::Div; break;
3665 case tok::percent: Opc = BinaryOperator::Rem; break;
3666 case tok::plus: Opc = BinaryOperator::Add; break;
3667 case tok::minus: Opc = BinaryOperator::Sub; break;
3668 case tok::lessless: Opc = BinaryOperator::Shl; break;
3669 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3670 case tok::lessequal: Opc = BinaryOperator::LE; break;
3671 case tok::less: Opc = BinaryOperator::LT; break;
3672 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3673 case tok::greater: Opc = BinaryOperator::GT; break;
3674 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3675 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3676 case tok::amp: Opc = BinaryOperator::And; break;
3677 case tok::caret: Opc = BinaryOperator::Xor; break;
3678 case tok::pipe: Opc = BinaryOperator::Or; break;
3679 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3680 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3681 case tok::equal: Opc = BinaryOperator::Assign; break;
3682 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3683 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3684 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3685 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3686 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3687 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3688 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3689 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3690 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3691 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3692 case tok::comma: Opc = BinaryOperator::Comma; break;
3693 }
3694 return Opc;
3695}
3696
3697static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3698 tok::TokenKind Kind) {
3699 UnaryOperator::Opcode Opc;
3700 switch (Kind) {
3701 default: assert(0 && "Unknown unary op!");
3702 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3703 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3704 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3705 case tok::star: Opc = UnaryOperator::Deref; break;
3706 case tok::plus: Opc = UnaryOperator::Plus; break;
3707 case tok::minus: Opc = UnaryOperator::Minus; break;
3708 case tok::tilde: Opc = UnaryOperator::Not; break;
3709 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003710 case tok::kw___real: Opc = UnaryOperator::Real; break;
3711 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3712 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3713 }
3714 return Opc;
3715}
3716
Douglas Gregord7f915e2008-11-06 23:29:22 +00003717/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3718/// operator @p Opc at location @c TokLoc. This routine only supports
3719/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003720Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3721 unsigned Op,
3722 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003723 QualType ResultTy; // Result type of the binary operator.
3724 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3725 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3726
3727 switch (Opc) {
3728 default:
3729 assert(0 && "Unknown binary expr!");
3730 case BinaryOperator::Assign:
3731 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3732 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003733 case BinaryOperator::PtrMemD:
3734 case BinaryOperator::PtrMemI:
3735 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3736 Opc == BinaryOperator::PtrMemI);
3737 break;
3738 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003739 case BinaryOperator::Div:
3740 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3741 break;
3742 case BinaryOperator::Rem:
3743 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3744 break;
3745 case BinaryOperator::Add:
3746 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3747 break;
3748 case BinaryOperator::Sub:
3749 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3750 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003751 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003752 case BinaryOperator::Shr:
3753 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3754 break;
3755 case BinaryOperator::LE:
3756 case BinaryOperator::LT:
3757 case BinaryOperator::GE:
3758 case BinaryOperator::GT:
3759 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3760 break;
3761 case BinaryOperator::EQ:
3762 case BinaryOperator::NE:
3763 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3764 break;
3765 case BinaryOperator::And:
3766 case BinaryOperator::Xor:
3767 case BinaryOperator::Or:
3768 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3769 break;
3770 case BinaryOperator::LAnd:
3771 case BinaryOperator::LOr:
3772 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3773 break;
3774 case BinaryOperator::MulAssign:
3775 case BinaryOperator::DivAssign:
3776 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3777 if (!CompTy.isNull())
3778 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3779 break;
3780 case BinaryOperator::RemAssign:
3781 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3782 if (!CompTy.isNull())
3783 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3784 break;
3785 case BinaryOperator::AddAssign:
3786 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3787 if (!CompTy.isNull())
3788 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3789 break;
3790 case BinaryOperator::SubAssign:
3791 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3792 if (!CompTy.isNull())
3793 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3794 break;
3795 case BinaryOperator::ShlAssign:
3796 case BinaryOperator::ShrAssign:
3797 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3798 if (!CompTy.isNull())
3799 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3800 break;
3801 case BinaryOperator::AndAssign:
3802 case BinaryOperator::XorAssign:
3803 case BinaryOperator::OrAssign:
3804 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3805 if (!CompTy.isNull())
3806 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3807 break;
3808 case BinaryOperator::Comma:
3809 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3810 break;
3811 }
3812 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003813 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003814 if (CompTy.isNull())
3815 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3816 else
3817 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00003818 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003819}
3820
Chris Lattner4b009652007-07-25 00:24:17 +00003821// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003822Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3823 tok::TokenKind Kind,
3824 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003825 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003826 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003827
Steve Naroff87d58b42007-09-16 03:34:24 +00003828 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3829 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003830
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003831 // If either expression is type-dependent, just build the AST.
3832 // FIXME: We'll need to perform some caching of the result of name
3833 // lookup for operator+.
3834 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003835 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3836 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003837 Context.DependentTy,
3838 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003839 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003840 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3841 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003842 }
3843
Sebastian Redl95216a62009-02-07 00:15:38 +00003844 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003845 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3846 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003847 // If this is one of the assignment operators, we only perform
3848 // overload resolution if the left-hand side is a class or
3849 // enumeration type (C++ [expr.ass]p3).
3850 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3851 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3852 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3853 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003854
Douglas Gregord7f915e2008-11-06 23:29:22 +00003855 // Determine which overloaded operator we're dealing with.
3856 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003857 // Overloading .* is not possible.
3858 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003859 OO_Star, OO_Slash, OO_Percent,
3860 OO_Plus, OO_Minus,
3861 OO_LessLess, OO_GreaterGreater,
3862 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3863 OO_EqualEqual, OO_ExclaimEqual,
3864 OO_Amp,
3865 OO_Caret,
3866 OO_Pipe,
3867 OO_AmpAmp,
3868 OO_PipePipe,
3869 OO_Equal, OO_StarEqual,
3870 OO_SlashEqual, OO_PercentEqual,
3871 OO_PlusEqual, OO_MinusEqual,
3872 OO_LessLessEqual, OO_GreaterGreaterEqual,
3873 OO_AmpEqual, OO_CaretEqual,
3874 OO_PipeEqual,
3875 OO_Comma
3876 };
3877 OverloadedOperatorKind OverOp = OverOps[Opc];
3878
Mike Stump9afab102009-02-19 03:04:26 +00003879 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor5ed15042008-11-18 23:14:02 +00003880 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003881 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003882 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003883 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3884 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003885
3886 // Perform overload resolution.
3887 OverloadCandidateSet::iterator Best;
3888 switch (BestViableFunction(CandidateSet, Best)) {
3889 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003890 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003891 FunctionDecl *FnDecl = Best->Function;
3892
Douglas Gregor70d26122008-11-12 17:17:38 +00003893 if (FnDecl) {
3894 // We matched an overloaded operator. Build a call to that
3895 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003896
Douglas Gregor70d26122008-11-12 17:17:38 +00003897 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3899 if (PerformObjectArgumentInitialization(lhs, Method) ||
3900 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3901 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003902 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003903 } else {
3904 // Convert the arguments.
3905 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3906 "passing") ||
3907 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3908 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003909 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003910 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003911
Douglas Gregor70d26122008-11-12 17:17:38 +00003912 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003913 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003914 = FnDecl->getType()->getAsFunctionType()->getResultType();
3915 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003916
Douglas Gregor70d26122008-11-12 17:17:38 +00003917 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003918 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3919 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003920 UsualUnaryConversions(FnExpr);
3921
Mike Stump9afab102009-02-19 03:04:26 +00003922 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003923 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003924 } else {
3925 // We matched a built-in operator. Convert the arguments, then
3926 // break out so that we will build the appropriate built-in
3927 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003928 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3929 Best->Conversions[0], "passing") ||
3930 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3931 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003932 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003933
3934 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003935 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003936 }
3937
3938 case OR_No_Viable_Function:
3939 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003940 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003941 break;
3942
3943 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003944 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3945 << BinaryOperator::getOpcodeStr(Opc)
3946 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003947 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003948 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00003949
3950 case OR_Deleted:
3951 Diag(TokLoc, diag::err_ovl_deleted_oper)
3952 << Best->Function->isDeleted()
3953 << BinaryOperator::getOpcodeStr(Opc)
3954 << lhs->getSourceRange() << rhs->getSourceRange();
3955 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3956 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003957 }
3958
Douglas Gregor70d26122008-11-12 17:17:38 +00003959 // Either we found no viable overloaded operator or we matched a
3960 // built-in operator. In either case, fall through to trying to
3961 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003962 }
3963
Douglas Gregord7f915e2008-11-06 23:29:22 +00003964 // Build a built-in binary operation.
3965 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003966}
3967
3968// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003969Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3970 tok::TokenKind Op, ExprArg input) {
3971 // FIXME: Input is modified later, but smart pointer not reassigned.
3972 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003973 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003974
3975 if (getLangOptions().CPlusPlus &&
Mike Stump9afab102009-02-19 03:04:26 +00003976 (Input->getType()->isRecordType()
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003977 || Input->getType()->isEnumeralType())) {
3978 // Determine which overloaded operator we're dealing with.
3979 static const OverloadedOperatorKind OverOps[] = {
3980 OO_None, OO_None,
3981 OO_PlusPlus, OO_MinusMinus,
3982 OO_Amp, OO_Star,
3983 OO_Plus, OO_Minus,
3984 OO_Tilde, OO_Exclaim,
3985 OO_None, OO_None,
Mike Stump9afab102009-02-19 03:04:26 +00003986 OO_None,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003987 OO_None
3988 };
3989 OverloadedOperatorKind OverOp = OverOps[Opc];
3990
Mike Stump9afab102009-02-19 03:04:26 +00003991 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003992 // to the candidate set.
3993 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003994 if (OverOp != OO_None &&
3995 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3996 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003997
3998 // Perform overload resolution.
3999 OverloadCandidateSet::iterator Best;
4000 switch (BestViableFunction(CandidateSet, Best)) {
4001 case OR_Success: {
4002 // We found a built-in operator or an overloaded operator.
4003 FunctionDecl *FnDecl = Best->Function;
4004
4005 if (FnDecl) {
4006 // We matched an overloaded operator. Build a call to that
4007 // operator.
4008
4009 // Convert the arguments.
4010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4011 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004012 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004013 } else {
4014 // Convert the arguments.
Mike Stump9afab102009-02-19 03:04:26 +00004015 if (PerformCopyInitialization(Input,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004016 FnDecl->getParamDecl(0)->getType(),
4017 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004018 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004019 }
4020
4021 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004022 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004023 = FnDecl->getType()->getAsFunctionType()->getResultType();
4024 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004025
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004026 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00004027 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004028 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004029 UsualUnaryConversions(FnExpr);
4030
Sebastian Redl8b769972009-01-19 00:08:26 +00004031 input.release();
Mike Stump9afab102009-02-19 03:04:26 +00004032 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4033 1, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004034 } else {
4035 // We matched a built-in operator. Convert the arguments, then
4036 // break out so that we will build the appropriate built-in
4037 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004038 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4039 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004040 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004041
4042 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004043 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004044 }
4045
4046 case OR_No_Viable_Function:
4047 // No viable function; fall through to handling this as a
4048 // built-in operator, which will produce an error message for us.
4049 break;
4050
4051 case OR_Ambiguous:
4052 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4053 << UnaryOperator::getOpcodeStr(Opc)
4054 << Input->getSourceRange();
4055 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004056 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004057
4058 case OR_Deleted:
4059 Diag(OpLoc, diag::err_ovl_deleted_oper)
4060 << Best->Function->isDeleted()
4061 << UnaryOperator::getOpcodeStr(Opc)
4062 << Input->getSourceRange();
4063 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4064 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004065 }
4066
4067 // Either we found no viable overloaded operator or we matched a
4068 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004069 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004070 }
4071
Chris Lattner4b009652007-07-25 00:24:17 +00004072 QualType resultType;
4073 switch (Opc) {
4074 default:
4075 assert(0 && "Unimplemented unary expr!");
4076 case UnaryOperator::PreInc:
4077 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004078 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4079 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004080 break;
Mike Stump9afab102009-02-19 03:04:26 +00004081 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004082 resultType = CheckAddressOfOperand(Input, OpLoc);
4083 break;
Mike Stump9afab102009-02-19 03:04:26 +00004084 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004085 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004086 resultType = CheckIndirectionOperand(Input, OpLoc);
4087 break;
4088 case UnaryOperator::Plus:
4089 case UnaryOperator::Minus:
4090 UsualUnaryConversions(Input);
4091 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004092 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4093 break;
4094 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4095 resultType->isEnumeralType())
4096 break;
4097 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4098 Opc == UnaryOperator::Plus &&
4099 resultType->isPointerType())
4100 break;
4101
Sebastian Redl8b769972009-01-19 00:08:26 +00004102 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4103 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004104 case UnaryOperator::Not: // bitwise complement
4105 UsualUnaryConversions(Input);
4106 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004107 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4108 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4109 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004110 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004111 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004112 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004113 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4114 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004115 break;
4116 case UnaryOperator::LNot: // logical negation
4117 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4118 DefaultFunctionArrayConversion(Input);
4119 resultType = Input->getType();
4120 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004121 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4122 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004123 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004124 // In C++, it's bool. C++ 5.3.1p8
4125 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004126 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004127 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004128 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004129 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004130 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004131 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004132 resultType = Input->getType();
4133 break;
4134 }
4135 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004136 return ExprError();
4137 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004138 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004139}
4140
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004141/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stump9afab102009-02-19 03:04:26 +00004142Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004143 SourceLocation LabLoc,
4144 IdentifierInfo *LabelII) {
4145 // Look up the record for this label identifier.
4146 LabelStmt *&LabelDecl = LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004147
Daniel Dunbar879788d2008-08-04 16:51:22 +00004148 // If we haven't seen this label yet, create a forward reference. It
4149 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004150 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004151 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004152
Chris Lattner4b009652007-07-25 00:24:17 +00004153 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004154 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4155 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004156}
4157
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004158Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004159 SourceLocation RPLoc) { // "({..})"
4160 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4161 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4162 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4163
Eli Friedmanbc941e12009-01-24 23:09:00 +00004164 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4165 if (isFileScope) {
4166 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4167 }
4168
Chris Lattner4b009652007-07-25 00:24:17 +00004169 // FIXME: there are a variety of strange constraints to enforce here, for
4170 // example, it is not possible to goto into a stmt expression apparently.
4171 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004172
Chris Lattner4b009652007-07-25 00:24:17 +00004173 // FIXME: the last statement in the compount stmt has its value used. We
4174 // should not warn about it being unused.
4175
4176 // If there are sub stmts in the compound stmt, take the type of the last one
4177 // as the type of the stmtexpr.
4178 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004179
Chris Lattner200964f2008-07-26 19:51:01 +00004180 if (!Compound->body_empty()) {
4181 Stmt *LastStmt = Compound->body_back();
4182 // If LastStmt is a label, skip down through into the body.
4183 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4184 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004185
Chris Lattner200964f2008-07-26 19:51:01 +00004186 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004187 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004188 }
Mike Stump9afab102009-02-19 03:04:26 +00004189
Steve Naroff774e4152009-01-21 00:14:39 +00004190 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004191}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004192
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004193Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4194 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004195 SourceLocation TypeLoc,
4196 TypeTy *argty,
4197 OffsetOfComponent *CompPtr,
4198 unsigned NumComponents,
4199 SourceLocation RPLoc) {
4200 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4201 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004202
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004203 // We must have at least one component that refers to the type, and the first
4204 // one is known to be a field designator. Verify that the ArgTy represents
4205 // a struct/union/class.
4206 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004207 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stump9afab102009-02-19 03:04:26 +00004208
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004209 // Otherwise, create a compound literal expression as the base, and
4210 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004211 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004212 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004213 IList->setType(ArgTy);
4214 Expr *Res =
4215 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4216
Chris Lattnerb37522e2007-08-31 21:49:13 +00004217 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4218 // GCC extension, diagnose them.
4219 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004220 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4221 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004222
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004223 for (unsigned i = 0; i != NumComponents; ++i) {
4224 const OffsetOfComponent &OC = CompPtr[i];
4225 if (OC.isBrackets) {
4226 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004227 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004228 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004229 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004230 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004231 }
Mike Stump9afab102009-02-19 03:04:26 +00004232
Chris Lattner2af6a802007-08-30 17:59:59 +00004233 // FIXME: C++: Verify that operator[] isn't overloaded.
4234
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004235 // C99 6.5.2.1p1
4236 Expr *Idx = static_cast<Expr*>(OC.U.E);
4237 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004238 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4239 << Idx->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004240
4241 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004242 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004243 continue;
4244 }
Mike Stump9afab102009-02-19 03:04:26 +00004245
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004246 const RecordType *RC = Res->getType()->getAsRecordType();
4247 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004248 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004249 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004250 }
Mike Stump9afab102009-02-19 03:04:26 +00004251
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004252 // Get the decl corresponding to this.
4253 RecordDecl *RD = RC->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00004254 FieldDecl *MemberDecl
4255 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004256 LookupMemberName)
4257 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004258 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004259 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4260 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004261
Chris Lattner2af6a802007-08-30 17:59:59 +00004262 // FIXME: C++: Verify that MemberDecl isn't a static field.
4263 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004264 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4265 // matter here.
Mike Stump9afab102009-02-19 03:04:26 +00004266 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004267 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004268 }
Mike Stump9afab102009-02-19 03:04:26 +00004269
4270 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff774e4152009-01-21 00:14:39 +00004271 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004272}
4273
4274
Mike Stump9afab102009-02-19 03:04:26 +00004275Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004276 TypeTy *arg1, TypeTy *arg2,
4277 SourceLocation RPLoc) {
4278 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4279 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004280
Steve Naroff63bad2d2007-08-01 22:05:33 +00004281 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004282
4283 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff774e4152009-01-21 00:14:39 +00004284 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004285}
4286
Mike Stump9afab102009-02-19 03:04:26 +00004287Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004288 ExprTy *expr1, ExprTy *expr2,
4289 SourceLocation RPLoc) {
4290 Expr *CondExpr = static_cast<Expr*>(cond);
4291 Expr *LHSExpr = static_cast<Expr*>(expr1);
4292 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stump9afab102009-02-19 03:04:26 +00004293
Steve Naroff93c53012007-08-03 21:21:27 +00004294 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4295
4296 // The conditional expression is required to be a constant expression.
4297 llvm::APSInt condEval(32);
4298 SourceLocation ExpLoc;
4299 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004300 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4301 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004302
4303 // If the condition is > zero, then the AST type is the same as the LSHExpr.
Mike Stump9afab102009-02-19 03:04:26 +00004304 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
Steve Naroff93c53012007-08-03 21:21:27 +00004305 RHSExpr->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004306 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00004307 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004308}
4309
Steve Naroff52a81c02008-09-03 18:15:37 +00004310//===----------------------------------------------------------------------===//
4311// Clang Extensions.
4312//===----------------------------------------------------------------------===//
4313
4314/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004315void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004316 // Analyze block parameters.
4317 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004318
Steve Naroff52a81c02008-09-03 18:15:37 +00004319 // Add BSI to CurBlock.
4320 BSI->PrevBlockInfo = CurBlock;
4321 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004322
Steve Naroff52a81c02008-09-03 18:15:37 +00004323 BSI->ReturnType = 0;
4324 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004325 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004326
Steve Naroff52059382008-10-10 01:28:17 +00004327 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004328 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004329}
4330
Mike Stumpc1fddff2009-02-04 22:31:32 +00004331void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4332 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4333
4334 if (ParamInfo.getNumTypeObjects() == 0
4335 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4336 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4337
4338 // The type is entirely optional as well, if none, use DependentTy.
4339 if (T.isNull())
4340 T = Context.DependentTy;
4341
4342 // The parameter list is optional, if there was none, assume ().
4343 if (!T->isFunctionType())
4344 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4345
4346 CurBlock->hasPrototype = true;
4347 CurBlock->isVariadic = false;
4348 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4349 .getTypePtr();
4350
4351 if (!RetTy->isDependentType())
4352 CurBlock->ReturnType = RetTy;
4353 return;
4354 }
4355
Steve Naroff52a81c02008-09-03 18:15:37 +00004356 // Analyze arguments to block.
4357 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4358 "Not a function declarator!");
4359 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004360
Steve Naroff52059382008-10-10 01:28:17 +00004361 CurBlock->hasPrototype = FTI.hasPrototype;
4362 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004363
Steve Naroff52a81c02008-09-03 18:15:37 +00004364 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4365 // no arguments, not a function that takes a single void argument.
4366 if (FTI.hasPrototype &&
4367 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4368 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4369 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4370 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004371 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004372 } else if (FTI.hasPrototype) {
4373 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004374 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4375 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004376 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4377
4378 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4379 .getTypePtr();
4380
4381 if (!RetTy->isDependentType())
4382 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004383 }
Steve Naroff52059382008-10-10 01:28:17 +00004384 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004385
Steve Naroff52059382008-10-10 01:28:17 +00004386 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4387 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4388 // If this has an identifier, add it to the scope stack.
4389 if ((*AI)->getIdentifier())
4390 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004391}
4392
4393/// ActOnBlockError - If there is an error parsing a block, this callback
4394/// is invoked to pop the information about the block from the action impl.
4395void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4396 // Ensure that CurBlock is deleted.
4397 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004398
Steve Naroff52a81c02008-09-03 18:15:37 +00004399 // Pop off CurBlock, handle nested blocks.
4400 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004401
Steve Naroff52a81c02008-09-03 18:15:37 +00004402 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stump9afab102009-02-19 03:04:26 +00004403
Steve Naroff52a81c02008-09-03 18:15:37 +00004404}
4405
4406/// ActOnBlockStmtExpr - This is called when the body of a block statement
4407/// literal was successfully completed. ^(int x){...}
4408Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4409 Scope *CurScope) {
4410 // Ensure that CurBlock is deleted.
4411 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004412 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004413
Steve Naroff52059382008-10-10 01:28:17 +00004414 PopDeclContext();
4415
Steve Naroff52a81c02008-09-03 18:15:37 +00004416 // Pop off CurBlock, handle nested blocks.
4417 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004418
Steve Naroff52a81c02008-09-03 18:15:37 +00004419 QualType RetTy = Context.VoidTy;
4420 if (BSI->ReturnType)
4421 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004422
Steve Naroff52a81c02008-09-03 18:15:37 +00004423 llvm::SmallVector<QualType, 8> ArgTypes;
4424 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4425 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004426
Steve Naroff52a81c02008-09-03 18:15:37 +00004427 QualType BlockTy;
4428 if (!BSI->hasPrototype)
4429 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4430 else
4431 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004432 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004433
Steve Naroff52a81c02008-09-03 18:15:37 +00004434 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004435
Steve Naroff95029d92008-10-08 18:44:00 +00004436 BSI->TheDecl->setBody(Body.take());
Mike Stumpae93d652009-02-19 22:01:56 +00004437 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff52a81c02008-09-03 18:15:37 +00004438}
4439
Anders Carlsson36760332007-10-15 20:28:48 +00004440Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4441 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004442 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004443 Expr *E = static_cast<Expr*>(expr);
4444 QualType T = QualType::getFromOpaquePtr(type);
4445
4446 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004447
4448 // Get the va_list type
4449 QualType VaListType = Context.getBuiltinVaListType();
4450 // Deal with implicit array decay; for example, on x86-64,
4451 // va_list is an array, but it's supposed to decay to
4452 // a pointer for va_arg.
4453 if (VaListType->isArrayType())
4454 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004455 // Make sure the input expression also decays appropriately.
4456 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004457
4458 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004459 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004460 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004461 << E->getType() << E->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004462
Anders Carlsson36760332007-10-15 20:28:48 +00004463 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004464
Steve Naroff774e4152009-01-21 00:14:39 +00004465 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004466}
4467
Douglas Gregorad4b3792008-11-29 04:51:27 +00004468Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4469 // The type of __null will be int or long, depending on the size of
4470 // pointers on the target.
4471 QualType Ty;
4472 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4473 Ty = Context.IntTy;
4474 else
4475 Ty = Context.LongTy;
4476
Steve Naroff774e4152009-01-21 00:14:39 +00004477 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004478}
4479
Chris Lattner005ed752008-01-04 18:04:52 +00004480bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4481 SourceLocation Loc,
4482 QualType DstType, QualType SrcType,
4483 Expr *SrcExpr, const char *Flavor) {
4484 // Decode the result (notice that AST's are still created for extensions).
4485 bool isInvalid = false;
4486 unsigned DiagKind;
4487 switch (ConvTy) {
4488 default: assert(0 && "Unknown conversion type");
4489 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004490 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004491 DiagKind = diag::ext_typecheck_convert_pointer_int;
4492 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004493 case IntToPointer:
4494 DiagKind = diag::ext_typecheck_convert_int_pointer;
4495 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004496 case IncompatiblePointer:
4497 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4498 break;
4499 case FunctionVoidPointer:
4500 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4501 break;
4502 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004503 // If the qualifiers lost were because we were applying the
4504 // (deprecated) C++ conversion from a string literal to a char*
4505 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4506 // Ideally, this check would be performed in
4507 // CheckPointerTypesForAssignment. However, that would require a
4508 // bit of refactoring (so that the second argument is an
4509 // expression, rather than a type), which should be done as part
4510 // of a larger effort to fix CheckPointerTypesForAssignment for
4511 // C++ semantics.
4512 if (getLangOptions().CPlusPlus &&
4513 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4514 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004515 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4516 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004517 case IntToBlockPointer:
4518 DiagKind = diag::err_int_to_block_pointer;
4519 break;
4520 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004521 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004522 break;
Steve Naroff19608432008-10-14 22:18:38 +00004523 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004524 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004525 // it can give a more specific diagnostic.
4526 DiagKind = diag::warn_incompatible_qualified_id;
4527 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004528 case IncompatibleVectors:
4529 DiagKind = diag::warn_incompatible_vectors;
4530 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004531 case Incompatible:
4532 DiagKind = diag::err_typecheck_convert_incompatible;
4533 isInvalid = true;
4534 break;
4535 }
Mike Stump9afab102009-02-19 03:04:26 +00004536
Chris Lattner271d4c22008-11-24 05:29:24 +00004537 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4538 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004539 return isInvalid;
4540}
Anders Carlssond5201b92008-11-30 19:50:32 +00004541
4542bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4543{
4544 Expr::EvalResult EvalResult;
4545
Mike Stump9afab102009-02-19 03:04:26 +00004546 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004547 EvalResult.HasSideEffects) {
4548 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4549
4550 if (EvalResult.Diag) {
4551 // We only show the note if it's not the usual "invalid subexpression"
4552 // or if it's actually in a subexpression.
4553 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4554 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4555 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4556 }
Mike Stump9afab102009-02-19 03:04:26 +00004557
Anders Carlssond5201b92008-11-30 19:50:32 +00004558 return true;
4559 }
4560
4561 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004562 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004563 E->getSourceRange();
4564
4565 // Print the reason it's not a constant.
4566 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4567 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4568 }
Mike Stump9afab102009-02-19 03:04:26 +00004569
Anders Carlssond5201b92008-11-30 19:50:32 +00004570 if (Result)
4571 *Result = EvalResult.Val.getInt();
4572 return false;
4573}