blob: c0b61bf8d7c7df469e75e39c6a36b88fdc1a3773 [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
Chris Lattner2cb744b2009-02-15 22:43:40 +000029
30/// DiagnoseUseOfDeprecatedDeclImpl - If the specified decl is deprecated or
31// unavailable, emit the corresponding diagnostics.
32void Sema::DiagnoseUseOfDeprecatedDeclImpl(NamedDecl *D, SourceLocation Loc) {
33 // See if the decl is deprecated.
34 if (D->getAttr<DeprecatedAttr>()) {
Chris Lattnerfb1bb822009-02-16 19:35:30 +000035 // Implementing deprecated stuff requires referencing depreated stuff. Don't
36 // warn if we are implementing a deprecated construct.
37 bool isSilenced = false;
38
39 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
40 // If this reference happens *in* a deprecated function or method, don't
41 // warn.
42 isSilenced = ND->getAttr<DeprecatedAttr>();
43
44 // If this is an Objective-C method implementation, check to see if the
45 // method was deprecated on the declaration, not the definition.
46 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
47 // The semantic decl context of a ObjCMethodDecl is the
48 // ObjCImplementationDecl.
49 if (ObjCImplementationDecl *Impl
50 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
51
52 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
53 MD->isInstanceMethod());
54 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
55 }
56 }
57 }
58
59 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000060 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
61 }
62
63 // See if hte decl is unavailable.
64 if (D->getAttr<UnavailableAttr>())
65 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
66}
67
Chris Lattner299b8842008-07-25 21:10:04 +000068//===----------------------------------------------------------------------===//
69// Standard Promotions and Conversions
70//===----------------------------------------------------------------------===//
71
Chris Lattner299b8842008-07-25 21:10:04 +000072/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
73void Sema::DefaultFunctionArrayConversion(Expr *&E) {
74 QualType Ty = E->getType();
75 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
76
Chris Lattner299b8842008-07-25 21:10:04 +000077 if (Ty->isFunctionType())
78 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000079 else if (Ty->isArrayType()) {
80 // In C90 mode, arrays only promote to pointers if the array expression is
81 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
82 // type 'array of type' is converted to an expression that has type 'pointer
83 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
84 // that has type 'array of type' ...". The relevant change is "an lvalue"
85 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000086 //
87 // C++ 4.2p1:
88 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
89 // T" can be converted to an rvalue of type "pointer to T".
90 //
91 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
92 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000093 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
94 }
Chris Lattner299b8842008-07-25 21:10:04 +000095}
96
97/// UsualUnaryConversions - Performs various conversions that are common to most
98/// operators (C99 6.3). The conversions of array and function types are
99/// sometimes surpressed. For example, the array->pointer conversion doesn't
100/// apply if the array is an argument to the sizeof or address (&) operators.
101/// In these instances, this routine should *not* be called.
102Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
103 QualType Ty = Expr->getType();
104 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
105
Chris Lattner299b8842008-07-25 21:10:04 +0000106 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
107 ImpCastExprToType(Expr, Context.IntTy);
108 else
109 DefaultFunctionArrayConversion(Expr);
110
111 return Expr;
112}
113
Chris Lattner9305c3d2008-07-25 22:25:12 +0000114/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
115/// do not have a prototype. Arguments that have type float are promoted to
116/// double. All other argument types are converted by UsualUnaryConversions().
117void Sema::DefaultArgumentPromotion(Expr *&Expr) {
118 QualType Ty = Expr->getType();
119 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
120
121 // If this is a 'float' (CVR qualified or typedef) promote to double.
122 if (const BuiltinType *BT = Ty->getAsBuiltinType())
123 if (BT->getKind() == BuiltinType::Float)
124 return ImpCastExprToType(Expr, Context.DoubleTy);
125
126 UsualUnaryConversions(Expr);
127}
128
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000129// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
130// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000131void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000132 DefaultArgumentPromotion(Expr);
133
134 if (!Expr->getType()->isPODType()) {
135 Diag(Expr->getLocStart(),
136 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
137 Expr->getType() << CT;
138 }
139}
140
141
Chris Lattner299b8842008-07-25 21:10:04 +0000142/// UsualArithmeticConversions - Performs various conversions that are common to
143/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
144/// routine returns the first non-arithmetic type found. The client is
145/// responsible for emitting appropriate error diagnostics.
146/// FIXME: verify the conversion rules for "complex int" are consistent with
147/// GCC.
148QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
149 bool isCompAssign) {
150 if (!isCompAssign) {
151 UsualUnaryConversions(lhsExpr);
152 UsualUnaryConversions(rhsExpr);
153 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000154
Chris Lattner299b8842008-07-25 21:10:04 +0000155 // For conversion purposes, we ignore any qualifiers.
156 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000157 QualType lhs =
158 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
159 QualType rhs =
160 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000161
162 // If both types are identical, no conversion is needed.
163 if (lhs == rhs)
164 return lhs;
165
166 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
167 // The caller can deal with this (e.g. pointer + int).
168 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
169 return lhs;
170
171 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
172 if (!isCompAssign) {
173 ImpCastExprToType(lhsExpr, destType);
174 ImpCastExprToType(rhsExpr, destType);
175 }
176 return destType;
177}
178
179QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
180 // Perform the usual unary conversions. We do this early so that
181 // integral promotions to "int" can allow us to exit early, in the
182 // lhs == rhs check. Also, for conversion purposes, we ignore any
183 // qualifiers. For example, "const float" and "float" are
184 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000185 if (lhs->isPromotableIntegerType())
186 lhs = Context.IntTy;
187 else
188 lhs = lhs.getUnqualifiedType();
189 if (rhs->isPromotableIntegerType())
190 rhs = Context.IntTy;
191 else
192 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000193
Chris Lattner299b8842008-07-25 21:10:04 +0000194 // If both types are identical, no conversion is needed.
195 if (lhs == rhs)
196 return lhs;
197
198 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
199 // The caller can deal with this (e.g. pointer + int).
200 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
201 return lhs;
202
203 // At this point, we have two different arithmetic types.
204
205 // Handle complex types first (C99 6.3.1.8p1).
206 if (lhs->isComplexType() || rhs->isComplexType()) {
207 // if we have an integer operand, the result is the complex type.
208 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
209 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000210 return lhs;
211 }
212 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
213 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000214 return rhs;
215 }
216 // This handles complex/complex, complex/float, or float/complex.
217 // When both operands are complex, the shorter operand is converted to the
218 // type of the longer, and that is the type of the result. This corresponds
219 // to what is done when combining two real floating-point operands.
220 // The fun begins when size promotion occur across type domains.
221 // From H&S 6.3.4: When one operand is complex and the other is a real
222 // floating-point type, the less precise type is converted, within it's
223 // real or complex domain, to the precision of the other type. For example,
224 // when combining a "long double" with a "double _Complex", the
225 // "double _Complex" is promoted to "long double _Complex".
226 int result = Context.getFloatingTypeOrder(lhs, rhs);
227
228 if (result > 0) { // The left side is bigger, convert rhs.
229 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000230 } else if (result < 0) { // The right side is bigger, convert lhs.
231 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000232 }
233 // At this point, lhs and rhs have the same rank/size. Now, make sure the
234 // domains match. This is a requirement for our implementation, C99
235 // does not require this promotion.
236 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
237 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000238 return rhs;
239 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000240 return lhs;
241 }
242 }
243 return lhs; // The domain/size match exactly.
244 }
245 // Now handle "real" floating types (i.e. float, double, long double).
246 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
247 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000248 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000249 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000250 return lhs;
251 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000252 if (rhs->isComplexIntegerType()) {
253 // convert rhs to the complex floating point type.
254 return Context.getComplexType(lhs);
255 }
256 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000257 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000258 return rhs;
259 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000260 if (lhs->isComplexIntegerType()) {
261 // convert lhs to the complex floating point type.
262 return Context.getComplexType(rhs);
263 }
Chris Lattner299b8842008-07-25 21:10:04 +0000264 // We have two real floating types, float/complex combos were handled above.
265 // Convert the smaller operand to the bigger result.
266 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000267 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000268 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000269 assert(result < 0 && "illegal float comparison");
270 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000271 }
272 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
273 // Handle GCC complex int extension.
274 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
275 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
276
277 if (lhsComplexInt && rhsComplexInt) {
278 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000279 rhsComplexInt->getElementType()) >= 0)
280 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000281 return rhs;
282 } else if (lhsComplexInt && rhs->isIntegerType()) {
283 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000284 return lhs;
285 } else if (rhsComplexInt && lhs->isIntegerType()) {
286 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000287 return rhs;
288 }
289 }
290 // Finally, we have two differing integer types.
291 // The rules for this case are in C99 6.3.1.8
292 int compare = Context.getIntegerTypeOrder(lhs, rhs);
293 bool lhsSigned = lhs->isSignedIntegerType(),
294 rhsSigned = rhs->isSignedIntegerType();
295 QualType destType;
296 if (lhsSigned == rhsSigned) {
297 // Same signedness; use the higher-ranked type
298 destType = compare >= 0 ? lhs : rhs;
299 } else if (compare != (lhsSigned ? 1 : -1)) {
300 // The unsigned type has greater than or equal rank to the
301 // signed type, so use the unsigned type
302 destType = lhsSigned ? rhs : lhs;
303 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
304 // The two types are different widths; if we are here, that
305 // means the signed type is larger than the unsigned type, so
306 // use the signed type.
307 destType = lhsSigned ? lhs : rhs;
308 } else {
309 // The signed type is higher-ranked than the unsigned type,
310 // but isn't actually any bigger (like unsigned int and long
311 // on most 32-bit systems). Use the unsigned type corresponding
312 // to the signed type.
313 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
314 }
Chris Lattner299b8842008-07-25 21:10:04 +0000315 return destType;
316}
317
318//===----------------------------------------------------------------------===//
319// Semantic Analysis for various Expression Types
320//===----------------------------------------------------------------------===//
321
322
Steve Naroff87d58b42007-09-16 03:34:24 +0000323/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000324/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
325/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
326/// multiple tokens. However, the common case is that StringToks points to one
327/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000328///
329Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000330Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000331 assert(NumStringToks && "Must have at least one string!");
332
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000333 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000334 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000335 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000336
337 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
338 for (unsigned i = 0; i != NumStringToks; ++i)
339 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000340
Chris Lattnera6dcce32008-02-11 00:02:17 +0000341 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000342 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000343 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000344
345 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
346 if (getLangOptions().CPlusPlus)
347 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000348
Chris Lattnera6dcce32008-02-11 00:02:17 +0000349 // Get an array type for the string, according to C99 6.4.5. This includes
350 // the nul terminator character as well as the string length for pascal
351 // strings.
352 StrTy = Context.getConstantArrayType(StrTy,
353 llvm::APInt(32, Literal.GetStringLength()+1),
354 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000355 // Allocate enough space for the StringLiteral plus an array of locations for
356 // any concatenated strings.
357 void *Mem = Context.Allocate(sizeof(StringLiteral)+
358 sizeof(SourceLocation)*(NumStringToks-1));
359
Chris Lattner4b009652007-07-25 00:24:17 +0000360 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattnerc3144742009-02-18 05:49:11 +0000361 return Owned(new (Mem) StringLiteral(Context, Literal.GetString(),
362 Literal.GetStringLength(),
363 Literal.AnyWide, StrTy,
364 &StringTokLocs[0],
365 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000366}
367
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000368/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
369/// CurBlock to VD should cause it to be snapshotted (as we do for auto
370/// variables defined outside the block) or false if this is not needed (e.g.
371/// for values inside the block or for globals).
372///
373/// FIXME: This will create BlockDeclRefExprs for global variables,
374/// function references, etc which is suboptimal :) and breaks
375/// things like "integer constant expression" tests.
376static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
377 ValueDecl *VD) {
378 // If the value is defined inside the block, we couldn't snapshot it even if
379 // we wanted to.
380 if (CurBlock->TheDecl == VD->getDeclContext())
381 return false;
382
383 // If this is an enum constant or function, it is constant, don't snapshot.
384 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
385 return false;
386
387 // If this is a reference to an extern, static, or global variable, no need to
388 // snapshot it.
389 // FIXME: What about 'const' variables in C++?
390 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
391 return Var->hasLocalStorage();
392
393 return true;
394}
395
396
397
Steve Naroff0acc9c92007-09-15 18:49:24 +0000398/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000399/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000400/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000401/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000402/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000403Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
404 IdentifierInfo &II,
405 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000406 const CXXScopeSpec *SS,
407 bool isAddressOfOperand) {
408 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000409 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000410}
411
Douglas Gregor566782a2009-01-06 05:10:23 +0000412/// BuildDeclRefExpr - Build either a DeclRefExpr or a
413/// QualifiedDeclRefExpr based on whether or not SS is a
414/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000415DeclRefExpr *
416Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
417 bool TypeDependent, bool ValueDependent,
418 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000419 if (SS && !SS->isEmpty())
420 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000421 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000422 else
423 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000424}
425
Douglas Gregor723d3332009-01-07 00:43:41 +0000426/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
427/// variable corresponding to the anonymous union or struct whose type
428/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000429static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000430 assert(Record->isAnonymousStructOrUnion() &&
431 "Record must be an anonymous struct or union!");
432
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000433 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000434 // be an O(1) operation rather than a slow walk through DeclContext's
435 // vector (which itself will be eliminated). DeclGroups might make
436 // this even better.
437 DeclContext *Ctx = Record->getDeclContext();
438 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
439 DEnd = Ctx->decls_end();
440 D != DEnd; ++D) {
441 if (*D == Record) {
442 // The object for the anonymous struct/union directly
443 // follows its type in the list of declarations.
444 ++D;
445 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000446 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000447 return *D;
448 }
449 }
450
451 assert(false && "Missing object for anonymous record");
452 return 0;
453}
454
Sebastian Redlcd883f72009-01-18 18:53:16 +0000455Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000456Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
457 FieldDecl *Field,
458 Expr *BaseObjectExpr,
459 SourceLocation OpLoc) {
460 assert(Field->getDeclContext()->isRecord() &&
461 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
462 && "Field must be stored inside an anonymous struct or union");
463
464 // Construct the sequence of field member references
465 // we'll have to perform to get to the field in the anonymous
466 // union/struct. The list of members is built from the field
467 // outward, so traverse it backwards to go from an object in
468 // the current context to the field we found.
469 llvm::SmallVector<FieldDecl *, 4> AnonFields;
470 AnonFields.push_back(Field);
471 VarDecl *BaseObject = 0;
472 DeclContext *Ctx = Field->getDeclContext();
473 do {
474 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000475 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000476 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
477 AnonFields.push_back(AnonField);
478 else {
479 BaseObject = cast<VarDecl>(AnonObject);
480 break;
481 }
482 Ctx = Ctx->getParent();
483 } while (Ctx->isRecord() &&
484 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
485
486 // Build the expression that refers to the base object, from
487 // which we will build a sequence of member references to each
488 // of the anonymous union objects and, eventually, the field we
489 // found via name lookup.
490 bool BaseObjectIsPointer = false;
491 unsigned ExtraQuals = 0;
492 if (BaseObject) {
493 // BaseObject is an anonymous struct/union variable (and is,
494 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000495 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000496 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000497 SourceLocation());
498 ExtraQuals
499 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
500 } else if (BaseObjectExpr) {
501 // The caller provided the base object expression. Determine
502 // whether its a pointer and whether it adds any qualifiers to the
503 // anonymous struct/union fields we're looking into.
504 QualType ObjectType = BaseObjectExpr->getType();
505 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
506 BaseObjectIsPointer = true;
507 ObjectType = ObjectPtr->getPointeeType();
508 }
509 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
510 } else {
511 // We've found a member of an anonymous struct/union that is
512 // inside a non-anonymous struct/union, so in a well-formed
513 // program our base object expression is "this".
514 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
515 if (!MD->isStatic()) {
516 QualType AnonFieldType
517 = Context.getTagDeclType(
518 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
519 QualType ThisType = Context.getTagDeclType(MD->getParent());
520 if ((Context.getCanonicalType(AnonFieldType)
521 == Context.getCanonicalType(ThisType)) ||
522 IsDerivedFrom(ThisType, AnonFieldType)) {
523 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000524 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000525 MD->getThisType(Context));
526 BaseObjectIsPointer = true;
527 }
528 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000529 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
530 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000531 }
532 ExtraQuals = MD->getTypeQualifiers();
533 }
534
535 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000536 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
537 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000538 }
539
540 // Build the implicit member references to the field of the
541 // anonymous struct/union.
542 Expr *Result = BaseObjectExpr;
543 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
544 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
545 FI != FIEnd; ++FI) {
546 QualType MemberType = (*FI)->getType();
547 if (!(*FI)->isMutable()) {
548 unsigned combinedQualifiers
549 = MemberType.getCVRQualifiers() | ExtraQuals;
550 MemberType = MemberType.getQualifiedType(combinedQualifiers);
551 }
Steve Naroff774e4152009-01-21 00:14:39 +0000552 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
553 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000554 BaseObjectIsPointer = false;
555 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
556 OpLoc = SourceLocation();
557 }
558
Sebastian Redlcd883f72009-01-18 18:53:16 +0000559 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000560}
561
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000562/// ActOnDeclarationNameExpr - The parser has read some kind of name
563/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
564/// performs lookup on that name and returns an expression that refers
565/// to that name. This routine isn't directly called from the parser,
566/// because the parser doesn't know about DeclarationName. Rather,
567/// this routine is called by ActOnIdentifierExpr,
568/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
569/// which form the DeclarationName from the corresponding syntactic
570/// forms.
571///
572/// HasTrailingLParen indicates whether this identifier is used in a
573/// function call context. LookupCtx is only used for a C++
574/// qualified-id (foo::bar) to indicate the class or namespace that
575/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000576///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000577/// isAddressOfOperand means that this expression is the direct operand
578/// of an address-of operator. This matters because this is the only
579/// situation where a qualified name referencing a non-static member may
580/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000581Sema::OwningExprResult
582Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
583 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000584 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000585 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000586 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000587 if (SS && SS->isInvalid())
588 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000589 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
590 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000591
Douglas Gregor09be81b2009-02-04 17:27:36 +0000592 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000593 if (Lookup.isAmbiguous()) {
594 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
595 SS && SS->isSet() ? SS->getRange()
596 : SourceRange());
597 return ExprError();
598 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000599 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000600
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000601 // If this reference is in an Objective-C method, then ivar lookup happens as
602 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000603 IdentifierInfo *II = Name.getAsIdentifierInfo();
604 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000605 // There are two cases to handle here. 1) scoped lookup could have failed,
606 // in which case we should look for an ivar. 2) scoped lookup could have
607 // found a decl, but that decl is outside the current method (i.e. a global
608 // variable). In these two cases, we do a lookup for an ivar with this
609 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000610 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000611 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000612 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000613 // Check if referencing a field with __attribute__((deprecated)).
614 DiagnoseUseOfDeprecatedDecl(IV, Loc);
615
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000616 // FIXME: This should use a new expr for a direct reference, don't turn
617 // this into Self->ivar, just return a BareIVarExpr or something.
618 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000619 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000620 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
621 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000622 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000623 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000624 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000625 }
626 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000627 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000628 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000629 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000630 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000631 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000632 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000633 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000634
635 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
636 HasTrailingLParen && D == 0) {
637 // We've seen something of the form
638 //
639 // identifier(
640 //
641 // and we did not find any entity by the name
642 // "identifier". However, this identifier is still subject to
643 // argument-dependent lookup, so keep track of the name.
644 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
645 Context.OverloadTy,
646 Loc));
647 }
648
Chris Lattner4b009652007-07-25 00:24:17 +0000649 if (D == 0) {
650 // Otherwise, this could be an implicitly declared function reference (legal
651 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000652 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000653 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000654 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000655 else {
656 // If this name wasn't predeclared and if this is not a function call,
657 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000658 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000659 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
660 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000661 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
662 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000663 return ExprError(Diag(Loc, diag::err_undeclared_use)
664 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000665 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000666 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000667 }
668 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000669
Sebastian Redl0c9da212009-02-03 20:19:35 +0000670 // If this is an expression of the form &Class::member, don't build an
671 // implicit member ref, because we want a pointer to the member in general,
672 // not any specific instance's member.
673 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000674 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000675 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000676 QualType DType;
677 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
678 DType = FD->getType().getNonReferenceType();
679 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
680 DType = Method->getType();
681 } else if (isa<OverloadedFunctionDecl>(D)) {
682 DType = Context.OverloadTy;
683 }
684 // Could be an inner type. That's diagnosed below, so ignore it here.
685 if (!DType.isNull()) {
686 // The pointer is type- and value-dependent if it points into something
687 // dependent.
688 bool Dependent = false;
689 for (; DC; DC = DC->getParent()) {
690 // FIXME: could stop early at namespace scope.
691 if (DC->isRecord()) {
692 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
693 if (Context.getTypeDeclType(Record)->isDependentType()) {
694 Dependent = true;
695 break;
696 }
697 }
698 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000699 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000700 }
701 }
702 }
703
Douglas Gregor723d3332009-01-07 00:43:41 +0000704 // We may have found a field within an anonymous union or struct
705 // (C++ [class.union]).
706 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
707 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
708 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000709
Douglas Gregor3257fb52008-12-22 05:46:06 +0000710 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
711 if (!MD->isStatic()) {
712 // C++ [class.mfct.nonstatic]p2:
713 // [...] if name lookup (3.4.1) resolves the name in the
714 // id-expression to a nonstatic nontype member of class X or of
715 // a base class of X, the id-expression is transformed into a
716 // class member access expression (5.2.5) using (*this) (9.3.2)
717 // as the postfix-expression to the left of the '.' operator.
718 DeclContext *Ctx = 0;
719 QualType MemberType;
720 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
721 Ctx = FD->getDeclContext();
722 MemberType = FD->getType();
723
724 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
725 MemberType = RefType->getPointeeType();
726 else if (!FD->isMutable()) {
727 unsigned combinedQualifiers
728 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
729 MemberType = MemberType.getQualifiedType(combinedQualifiers);
730 }
731 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
732 if (!Method->isStatic()) {
733 Ctx = Method->getParent();
734 MemberType = Method->getType();
735 }
736 } else if (OverloadedFunctionDecl *Ovl
737 = dyn_cast<OverloadedFunctionDecl>(D)) {
738 for (OverloadedFunctionDecl::function_iterator
739 Func = Ovl->function_begin(),
740 FuncEnd = Ovl->function_end();
741 Func != FuncEnd; ++Func) {
742 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
743 if (!DMethod->isStatic()) {
744 Ctx = Ovl->getDeclContext();
745 MemberType = Context.OverloadTy;
746 break;
747 }
748 }
749 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000750
751 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000752 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
753 QualType ThisType = Context.getTagDeclType(MD->getParent());
754 if ((Context.getCanonicalType(CtxType)
755 == Context.getCanonicalType(ThisType)) ||
756 IsDerivedFrom(ThisType, CtxType)) {
757 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000758 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000759 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000760 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000761 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000762 }
763 }
764 }
765 }
766
Douglas Gregor8acb7272008-12-11 16:49:14 +0000767 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000768 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
769 if (MD->isStatic())
770 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000771 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
772 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000773 }
774
Douglas Gregor3257fb52008-12-22 05:46:06 +0000775 // Any other ways we could have found the field in a well-formed
776 // program would have been turned into implicit member expressions
777 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000778 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
779 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000780 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000781
Chris Lattner4b009652007-07-25 00:24:17 +0000782 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000783 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000784 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000785 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000786 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000787 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000788
Steve Naroffd6163f32008-09-05 22:11:13 +0000789 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000790 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000791 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
792 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000793 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
794 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
795 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000796 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000797
Chris Lattnerd9037472009-02-15 01:38:09 +0000798 // Check if referencing an identifier with __attribute__((deprecated)).
Chris Lattner2cb744b2009-02-15 22:43:40 +0000799 DiagnoseUseOfDeprecatedDecl(VD, Loc);
Chris Lattnerd9037472009-02-15 01:38:09 +0000800
Douglas Gregor48840c72008-12-10 23:01:14 +0000801 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000802 // Warn about constructs like:
803 // if (void *X = foo()) { ... } else { X }.
804 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000805 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
806 Scope *CheckS = S;
807 while (CheckS) {
808 if (CheckS->isWithinElse() &&
809 CheckS->getControlParent()->isDeclScope(Var)) {
810 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000811 ExprError(Diag(Loc, diag::warn_value_always_false)
812 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000813 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000814 ExprError(Diag(Loc, diag::warn_value_always_zero)
815 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000816 break;
817 }
818
819 // Move up one more control parent to check again.
820 CheckS = CheckS->getControlParent();
821 if (CheckS)
822 CheckS = CheckS->getParent();
823 }
824 }
825 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000826
827 // Only create DeclRefExpr's for valid Decl's.
828 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000829 return ExprError();
830
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000831 // If the identifier reference is inside a block, and it refers to a value
832 // that is outside the block, create a BlockDeclRefExpr instead of a
833 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
834 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000835 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000836 // We do not do this for things like enum constants, global variables, etc,
837 // as they do not get snapshotted.
838 //
839 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000840 // The BlocksAttr indicates the variable is bound by-reference.
841 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000842 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000843 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000844
Steve Naroff52059382008-10-10 01:28:17 +0000845 // Variable will be bound by-copy, make it const within the closure.
846 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000847 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000848 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000849 }
850 // If this reference is not in a block or if the referenced variable is
851 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000852
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000853 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000854 bool ValueDependent = false;
855 if (getLangOptions().CPlusPlus) {
856 // C++ [temp.dep.expr]p3:
857 // An id-expression is type-dependent if it contains:
858 // - an identifier that was declared with a dependent type,
859 if (VD->getType()->isDependentType())
860 TypeDependent = true;
861 // - FIXME: a template-id that is dependent,
862 // - a conversion-function-id that specifies a dependent type,
863 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
864 Name.getCXXNameType()->isDependentType())
865 TypeDependent = true;
866 // - a nested-name-specifier that contains a class-name that
867 // names a dependent type.
868 else if (SS && !SS->isEmpty()) {
869 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
870 DC; DC = DC->getParent()) {
871 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000872 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000873 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
874 if (Context.getTypeDeclType(Record)->isDependentType()) {
875 TypeDependent = true;
876 break;
877 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000878 }
879 }
880 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000881
Douglas Gregora5d84612008-12-10 20:57:37 +0000882 // C++ [temp.dep.constexpr]p2:
883 //
884 // An identifier is value-dependent if it is:
885 // - a name declared with a dependent type,
886 if (TypeDependent)
887 ValueDependent = true;
888 // - the name of a non-type template parameter,
889 else if (isa<NonTypeTemplateParmDecl>(VD))
890 ValueDependent = true;
891 // - a constant with integral or enumeration type and is
892 // initialized with an expression that is value-dependent
893 // (FIXME!).
894 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000895
Sebastian Redlcd883f72009-01-18 18:53:16 +0000896 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
897 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000898}
899
Sebastian Redlcd883f72009-01-18 18:53:16 +0000900Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
901 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000902 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000903
Chris Lattner4b009652007-07-25 00:24:17 +0000904 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000905 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000906 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
907 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
908 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000909 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000910
Chris Lattner7e637512008-01-12 08:14:25 +0000911 // Pre-defined identifiers are of type char[x], where x is the length of the
912 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000913 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000914 if (FunctionDecl *FD = getCurFunctionDecl())
915 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000916 else if (ObjCMethodDecl *MD = getCurMethodDecl())
917 Length = MD->getSynthesizedMethodSize();
918 else {
919 Diag(Loc, diag::ext_predef_outside_function);
920 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
921 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
922 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000923
924
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000925 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000926 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000927 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000928 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000929}
930
Sebastian Redlcd883f72009-01-18 18:53:16 +0000931Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000932 llvm::SmallString<16> CharBuffer;
933 CharBuffer.resize(Tok.getLength());
934 const char *ThisTokBegin = &CharBuffer[0];
935 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000936
Chris Lattner4b009652007-07-25 00:24:17 +0000937 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
938 Tok.getLocation(), PP);
939 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000940 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000941
942 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
943
Sebastian Redl75324932009-01-20 22:23:13 +0000944 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
945 Literal.isWide(),
946 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000947}
948
Sebastian Redlcd883f72009-01-18 18:53:16 +0000949Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
950 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000951 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
952 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000953 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000954 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000955 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000956 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000957 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000958
Chris Lattner4b009652007-07-25 00:24:17 +0000959 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000960 // Add padding so that NumericLiteralParser can overread by one character.
961 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000962 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000963
Chris Lattner4b009652007-07-25 00:24:17 +0000964 // Get the spelling of the token, which eliminates trigraphs, etc.
965 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000966
Chris Lattner4b009652007-07-25 00:24:17 +0000967 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
968 Tok.getLocation(), PP);
969 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000970 return ExprError();
971
Chris Lattner1de66eb2007-08-26 03:42:43 +0000972 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000973
Chris Lattner1de66eb2007-08-26 03:42:43 +0000974 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000975 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000976 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000977 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000978 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000979 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000980 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000981 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000982
983 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
984
Ted Kremenekddedbe22007-11-29 00:56:49 +0000985 // isExact will be set by GetFloatValue().
986 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000987 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
988 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000989
Chris Lattner1de66eb2007-08-26 03:42:43 +0000990 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000991 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000992 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000993 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000994
Neil Booth7421e9c2007-08-29 22:00:19 +0000995 // long long is a C99 feature.
996 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000997 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000998 Diag(Tok.getLocation(), diag::ext_longlong);
999
Chris Lattner4b009652007-07-25 00:24:17 +00001000 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001001 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001002
Chris Lattner4b009652007-07-25 00:24:17 +00001003 if (Literal.GetIntegerValue(ResultVal)) {
1004 // If this value didn't fit into uintmax_t, warn and force to ull.
1005 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001006 Ty = Context.UnsignedLongLongTy;
1007 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001008 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001009 } else {
1010 // If this value fits into a ULL, try to figure out what else it fits into
1011 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001012
Chris Lattner4b009652007-07-25 00:24:17 +00001013 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1014 // be an unsigned int.
1015 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1016
1017 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001018 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001019 if (!Literal.isLong && !Literal.isLongLong) {
1020 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001021 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001022
Chris Lattner4b009652007-07-25 00:24:17 +00001023 // Does it fit in a unsigned int?
1024 if (ResultVal.isIntN(IntSize)) {
1025 // Does it fit in a signed int?
1026 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001027 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001028 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001029 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001030 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001031 }
Chris Lattner4b009652007-07-25 00:24:17 +00001032 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033
Chris Lattner4b009652007-07-25 00:24:17 +00001034 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001035 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001036 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001037
Chris Lattner4b009652007-07-25 00:24:17 +00001038 // Does it fit in a unsigned long?
1039 if (ResultVal.isIntN(LongSize)) {
1040 // Does it fit in a signed long?
1041 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001042 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001043 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001044 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001045 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001046 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001047 }
1048
Chris Lattner4b009652007-07-25 00:24:17 +00001049 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001050 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001051 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001052
Chris Lattner4b009652007-07-25 00:24:17 +00001053 // Does it fit in a unsigned long long?
1054 if (ResultVal.isIntN(LongLongSize)) {
1055 // Does it fit in a signed long long?
1056 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001057 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001058 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001059 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001060 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001061 }
1062 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001063
Chris Lattner4b009652007-07-25 00:24:17 +00001064 // If we still couldn't decide a type, we probably have something that
1065 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001066 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001067 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001068 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001069 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001070 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001071
Chris Lattnere4068872008-05-09 05:59:00 +00001072 if (ResultVal.getBitWidth() != Width)
1073 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001074 }
Sebastian Redl75324932009-01-20 22:23:13 +00001075 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001076 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001077
Chris Lattner1de66eb2007-08-26 03:42:43 +00001078 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1079 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001080 Res = new (Context) ImaginaryLiteral(Res,
1081 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001082
1083 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001084}
1085
Sebastian Redlcd883f72009-01-18 18:53:16 +00001086Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1087 SourceLocation R, ExprArg Val) {
1088 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001089 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001090 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001091}
1092
1093/// The UsualUnaryConversions() function is *not* called by this routine.
1094/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001095bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1096 SourceLocation OpLoc,
1097 const SourceRange &ExprRange,
1098 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001099 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001100 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001101 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001102 if (isSizeof)
1103 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1104 return false;
1105 }
1106
1107 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001108 Diag(OpLoc, diag::ext_sizeof_void_type)
1109 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001110 return false;
1111 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001112
Chris Lattner159fe082009-01-24 19:46:37 +00001113 return DiagnoseIncompleteType(OpLoc, exprType,
1114 isSizeof ? diag::err_sizeof_incomplete_type :
1115 diag::err_alignof_incomplete_type,
1116 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001117}
1118
Chris Lattner8d9f7962009-01-24 20:17:12 +00001119bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1120 const SourceRange &ExprRange) {
1121 E = E->IgnoreParens();
1122
1123 // alignof decl is always ok.
1124 if (isa<DeclRefExpr>(E))
1125 return false;
1126
1127 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1128 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1129 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001130 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001131 return true;
1132 }
1133 // Other fields are ok.
1134 return false;
1135 }
1136 }
1137 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1138}
1139
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001140/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1141/// the same for @c alignof and @c __alignof
1142/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001143Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001144Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1145 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001146 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001147 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001148
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001149 QualType ArgTy;
1150 SourceRange Range;
1151 if (isType) {
1152 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1153 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001154
1155 // Verify that the operand is valid.
1156 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1157 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001158 } else {
1159 // Get the end location.
1160 Expr *ArgEx = (Expr *)TyOrEx;
1161 Range = ArgEx->getSourceRange();
1162 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001163
1164 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001165 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001166 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001167 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001168 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1169 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1170 isInvalid = true;
1171 } else {
1172 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1173 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001174
1175 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001176 DeleteExpr(ArgEx);
1177 return ExprError();
1178 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001179 }
1180
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001181 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001182 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001183 Context.getSizeType(), OpLoc,
1184 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001185}
1186
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001187QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Chris Lattner03931a72007-08-24 21:16:53 +00001188 DefaultFunctionArrayConversion(V);
1189
Chris Lattnera16e42d2007-08-26 05:39:26 +00001190 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001191 if (const ComplexType *CT = V->getType()->getAsComplexType())
1192 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001193
1194 // Otherwise they pass through real integer and floating point types here.
1195 if (V->getType()->isArithmeticType())
1196 return V->getType();
1197
1198 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001199 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1200 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001201 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001202}
1203
1204
Chris Lattner4b009652007-07-25 00:24:17 +00001205
Sebastian Redl8b769972009-01-19 00:08:26 +00001206Action::OwningExprResult
1207Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1208 tok::TokenKind Kind, ExprArg Input) {
1209 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001210
Chris Lattner4b009652007-07-25 00:24:17 +00001211 UnaryOperator::Opcode Opc;
1212 switch (Kind) {
1213 default: assert(0 && "Unknown unary op!");
1214 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1215 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1216 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001217
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001218 if (getLangOptions().CPlusPlus &&
1219 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1220 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001221 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001222 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1223
1224 // C++ [over.inc]p1:
1225 //
1226 // [...] If the function is a member function with one
1227 // parameter (which shall be of type int) or a non-member
1228 // function with two parameters (the second of which shall be
1229 // of type int), it defines the postfix increment operator ++
1230 // for objects of that type. When the postfix increment is
1231 // called as a result of using the ++ operator, the int
1232 // argument will have value zero.
1233 Expr *Args[2] = {
1234 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001235 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1236 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001237 };
1238
1239 // Build the candidate set for overloading
1240 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001241 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1242 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001243
1244 // Perform overload resolution.
1245 OverloadCandidateSet::iterator Best;
1246 switch (BestViableFunction(CandidateSet, Best)) {
1247 case OR_Success: {
1248 // We found a built-in operator or an overloaded operator.
1249 FunctionDecl *FnDecl = Best->Function;
1250
1251 if (FnDecl) {
1252 // We matched an overloaded operator. Build a call to that
1253 // operator.
1254
1255 // Convert the arguments.
1256 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1257 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001258 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001259 } else {
1260 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001261 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001262 FnDecl->getParamDecl(0)->getType(),
1263 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001264 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001265 }
1266
1267 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001268 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001269 = FnDecl->getType()->getAsFunctionType()->getResultType();
1270 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001271
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001272 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001273 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001274 SourceLocation());
1275 UsualUnaryConversions(FnExpr);
1276
Sebastian Redl8b769972009-01-19 00:08:26 +00001277 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001278 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1279 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001280 } else {
1281 // We matched a built-in operator. Convert the arguments, then
1282 // break out so that we will build the appropriate built-in
1283 // operator node.
1284 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1285 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001286 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001287
1288 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001289 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001290 }
1291
1292 case OR_No_Viable_Function:
1293 // No viable function; fall through to handling this as a
1294 // built-in operator, which will produce an error message for us.
1295 break;
1296
1297 case OR_Ambiguous:
1298 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1299 << UnaryOperator::getOpcodeStr(Opc)
1300 << Arg->getSourceRange();
1301 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001302 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001303 }
1304
1305 // Either we found no viable overloaded operator or we matched a
1306 // built-in operator. In either case, fall through to trying to
1307 // build a built-in operation.
1308 }
1309
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001310 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1311 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001312 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001313 return ExprError();
1314 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001315 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001316}
1317
Sebastian Redl8b769972009-01-19 00:08:26 +00001318Action::OwningExprResult
1319Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1320 ExprArg Idx, SourceLocation RLoc) {
1321 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1322 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001323
Douglas Gregor80723c52008-11-19 17:17:41 +00001324 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001325 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001326 LHSExp->getType()->isEnumeralType() ||
1327 RHSExp->getType()->isRecordType() ||
1328 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001329 // Add the appropriate overloaded operators (C++ [over.match.oper])
1330 // to the candidate set.
1331 OverloadCandidateSet CandidateSet;
1332 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001333 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1334 SourceRange(LLoc, RLoc)))
1335 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001336
Douglas Gregor80723c52008-11-19 17:17:41 +00001337 // Perform overload resolution.
1338 OverloadCandidateSet::iterator Best;
1339 switch (BestViableFunction(CandidateSet, Best)) {
1340 case OR_Success: {
1341 // We found a built-in operator or an overloaded operator.
1342 FunctionDecl *FnDecl = Best->Function;
1343
1344 if (FnDecl) {
1345 // We matched an overloaded operator. Build a call to that
1346 // operator.
1347
1348 // Convert the arguments.
1349 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1350 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1351 PerformCopyInitialization(RHSExp,
1352 FnDecl->getParamDecl(0)->getType(),
1353 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001354 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001355 } else {
1356 // Convert the arguments.
1357 if (PerformCopyInitialization(LHSExp,
1358 FnDecl->getParamDecl(0)->getType(),
1359 "passing") ||
1360 PerformCopyInitialization(RHSExp,
1361 FnDecl->getParamDecl(1)->getType(),
1362 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001363 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001364 }
1365
1366 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001367 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001368 = FnDecl->getType()->getAsFunctionType()->getResultType();
1369 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001370
Douglas Gregor80723c52008-11-19 17:17:41 +00001371 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001372 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001373 SourceLocation());
1374 UsualUnaryConversions(FnExpr);
1375
Sebastian Redl8b769972009-01-19 00:08:26 +00001376 Base.release();
1377 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001378 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001379 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001380 } else {
1381 // We matched a built-in operator. Convert the arguments, then
1382 // break out so that we will build the appropriate built-in
1383 // operator node.
1384 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1385 "passing") ||
1386 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1387 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001388 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001389
1390 break;
1391 }
1392 }
1393
1394 case OR_No_Viable_Function:
1395 // No viable function; fall through to handling this as a
1396 // built-in operator, which will produce an error message for us.
1397 break;
1398
1399 case OR_Ambiguous:
1400 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1401 << "[]"
1402 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1403 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001404 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001405 }
1406
1407 // Either we found no viable overloaded operator or we matched a
1408 // built-in operator. In either case, fall through to trying to
1409 // build a built-in operation.
1410 }
1411
Chris Lattner4b009652007-07-25 00:24:17 +00001412 // Perform default conversions.
1413 DefaultFunctionArrayConversion(LHSExp);
1414 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001415
Chris Lattner4b009652007-07-25 00:24:17 +00001416 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1417
1418 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001419 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001420 // in the subscript position. As a result, we need to derive the array base
1421 // and index from the expression types.
1422 Expr *BaseExpr, *IndexExpr;
1423 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001424 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001425 BaseExpr = LHSExp;
1426 IndexExpr = RHSExp;
1427 // FIXME: need to deal with const...
1428 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001429 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001430 // Handle the uncommon case of "123[Ptr]".
1431 BaseExpr = RHSExp;
1432 IndexExpr = LHSExp;
1433 // FIXME: need to deal with const...
1434 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001435 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1436 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001437 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001438
Chris Lattner4b009652007-07-25 00:24:17 +00001439 // FIXME: need to deal with const...
1440 ResultType = VTy->getElementType();
1441 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001442 return ExprError(Diag(LHSExp->getLocStart(),
1443 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1444 }
Chris Lattner4b009652007-07-25 00:24:17 +00001445 // C99 6.5.2.1p1
1446 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001447 return ExprError(Diag(IndexExpr->getLocStart(),
1448 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001449
1450 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1451 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001452 // void (*)(int)) and pointers to incomplete types. Functions are not
1453 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001454 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001455 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001456 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001457 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001458
Sebastian Redl8b769972009-01-19 00:08:26 +00001459 Base.release();
1460 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001461 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1462 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001463}
1464
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001465QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001466CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001467 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001468 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001469
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001470 // The vector accessor can't exceed the number of elements.
1471 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001472
1473 // This flag determines whether or not the component is one of the four
1474 // special names that indicate a subset of exactly half the elements are
1475 // to be selected.
1476 bool HalvingSwizzle = false;
1477
1478 // This flag determines whether or not CompName has an 's' char prefix,
1479 // indicating that it is a string of hex values to be used as vector indices.
1480 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001481
1482 // Check that we've found one of the special components, or that the component
1483 // names must come from the same set.
1484 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001485 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1486 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001487 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001488 do
1489 compStr++;
1490 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001491 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001492 do
1493 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001494 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001495 }
Nate Begeman1486b502009-01-18 01:47:54 +00001496
1497 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001498 // We didn't get to the end of the string. This means the component names
1499 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001500 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1501 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001502 return QualType();
1503 }
Nate Begeman1486b502009-01-18 01:47:54 +00001504
1505 // Ensure no component accessor exceeds the width of the vector type it
1506 // operates on.
1507 if (!HalvingSwizzle) {
1508 compStr = CompName.getName();
1509
1510 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001511 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001512
1513 while (*compStr) {
1514 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1515 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1516 << baseType << SourceRange(CompLoc);
1517 return QualType();
1518 }
1519 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001520 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001521
Nate Begeman1486b502009-01-18 01:47:54 +00001522 // If this is a halving swizzle, verify that the base type has an even
1523 // number of elements.
1524 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001525 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001526 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001527 return QualType();
1528 }
1529
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001530 // The component accessor looks fine - now we need to compute the actual type.
1531 // The vector type is implied by the component accessor. For example,
1532 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001533 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001534 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001535 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1536 : CompName.getLength();
1537 if (HexSwizzle)
1538 CompSize--;
1539
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001540 if (CompSize == 1)
1541 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001542
Nate Begemanaf6ed502008-04-18 23:10:10 +00001543 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001544 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001545 // diagostics look bad. We want extended vector types to appear built-in.
1546 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1547 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1548 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001549 }
1550 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001551}
1552
Chris Lattner2cb744b2009-02-15 22:43:40 +00001553
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001554/// constructSetterName - Return the setter name for the given
1555/// identifier, i.e. "set" + Name where the initial character of Name
1556/// has been capitalized.
1557// FIXME: Merge with same routine in Parser. But where should this
1558// live?
1559static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1560 const IdentifierInfo *Name) {
1561 llvm::SmallString<100> SelectorName;
1562 SelectorName = "set";
1563 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1564 SelectorName[3] = toupper(SelectorName[3]);
1565 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1566}
1567
Sebastian Redl8b769972009-01-19 00:08:26 +00001568Action::OwningExprResult
1569Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1570 tok::TokenKind OpKind, SourceLocation MemberLoc,
1571 IdentifierInfo &Member) {
1572 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001573 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001574
1575 // Perform default conversions.
1576 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001577
Steve Naroff2cb66382007-07-26 03:11:44 +00001578 QualType BaseType = BaseExpr->getType();
1579 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001580
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001581 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1582 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001583 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001584 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001585 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001586 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001587 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1588 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001589 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001590 return ExprError(Diag(MemberLoc,
1591 diag::err_typecheck_member_reference_arrow)
1592 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001593 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001594
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001595 // Handle field access to simple records. This also handles access to fields
1596 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001597 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001598 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001599 if (DiagnoseIncompleteType(OpLoc, BaseType,
1600 diag::err_typecheck_incomplete_tag,
1601 BaseExpr->getSourceRange()))
1602 return ExprError();
1603
Steve Naroff2cb66382007-07-26 03:11:44 +00001604 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001605 // FIXME: Qualified name lookup for C++ is a bit more complicated
1606 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001607 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001608 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001609 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001610
Douglas Gregor09be81b2009-02-04 17:27:36 +00001611 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001612 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001613 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1614 << &Member << BaseExpr->getSourceRange());
1615 else if (Result.isAmbiguous()) {
1616 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1617 MemberLoc, BaseExpr->getSourceRange());
1618 return ExprError();
1619 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001620 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001621
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001622 // If the decl being referenced had an error, return an error for this
1623 // sub-expr without emitting another error, in order to avoid cascading
1624 // error cases.
1625 if (MemberDecl->isInvalidDecl())
1626 return ExprError();
Chris Lattnerb63f8132009-02-16 17:07:21 +00001627
1628 // Check if referencing a field with __attribute__((deprecated)).
1629 DiagnoseUseOfDeprecatedDecl(MemberDecl, MemberLoc);
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001630
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001631 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001632 // We may have found a field within an anonymous union or struct
1633 // (C++ [class.union]).
1634 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001635 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001636 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001637
Douglas Gregor82d44772008-12-20 23:49:58 +00001638 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1639 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001640 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001641 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1642 MemberType = Ref->getPointeeType();
1643 else {
1644 unsigned combinedQualifiers =
1645 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001646 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001647 combinedQualifiers &= ~QualType::Const;
1648 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1649 }
Eli Friedman76b49832008-02-06 22:48:16 +00001650
Steve Naroff774e4152009-01-21 00:14:39 +00001651 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1652 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001653 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001654 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001655 Var, MemberLoc,
1656 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001657 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001658 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1659 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001660 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001661 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001662 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001663 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001664 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001665 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001666 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001667 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001668 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1669 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001670
Douglas Gregor82d44772008-12-20 23:49:58 +00001671 // We found a declaration kind that we didn't expect. This is a
1672 // generic error message that tells the user that she can't refer
1673 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001674 return ExprError(Diag(MemberLoc,
1675 diag::err_typecheck_member_reference_unknown)
1676 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001677 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001678
Chris Lattnere9d71612008-07-21 04:59:05 +00001679 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1680 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001681 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001682 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001683 // If the decl being referenced had an error, return an error for this
1684 // sub-expr without emitting another error, in order to avoid cascading
1685 // error cases.
1686 if (IV->isInvalidDecl())
1687 return ExprError();
1688
Chris Lattner2a3bef92009-02-16 17:19:12 +00001689 // Check if referencing a field with __attribute__((deprecated)).
1690 DiagnoseUseOfDeprecatedDecl(IV, MemberLoc);
1691
Steve Naroff774e4152009-01-21 00:14:39 +00001692 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1693 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001694 OpKind == tok::arrow);
1695 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001696 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001697 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001698 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1699 << IFTy->getDecl()->getDeclName() << &Member
1700 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001701 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001702
Chris Lattnere9d71612008-07-21 04:59:05 +00001703 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1704 // pointer to a (potentially qualified) interface type.
1705 const PointerType *PTy;
1706 const ObjCInterfaceType *IFTy;
1707 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1708 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1709 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001710
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001711 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001712 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
1713 // Check if referencing a property with __attribute__((deprecated)).
1714 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1715
Steve Naroff774e4152009-01-21 00:14:39 +00001716 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001717 MemberLoc, BaseExpr));
1718 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001719
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001720 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001721 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1722 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001723 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1724 // Check if referencing a property with __attribute__((deprecated)).
1725 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1726
Steve Naroff774e4152009-01-21 00:14:39 +00001727 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001728 MemberLoc, BaseExpr));
1729 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001730
1731 // If that failed, look for an "implicit" property by seeing if the nullary
1732 // selector is implemented.
1733
1734 // FIXME: The logic for looking up nullary and unary selectors should be
1735 // shared with the code in ActOnInstanceMessage.
1736
1737 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1738 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001739
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001740 // If this reference is in an @implementation, check for 'private' methods.
1741 if (!Getter)
1742 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1743 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1744 if (ObjCImplementationDecl *ImpDecl =
1745 ObjCImplementations[ClassDecl->getIdentifier()])
1746 Getter = ImpDecl->getInstanceMethod(Sel);
1747
Steve Naroff04151f32008-10-22 19:16:27 +00001748 // Look through local category implementations associated with the class.
1749 if (!Getter) {
1750 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1751 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1752 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1753 }
1754 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001755 if (Getter) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001756 // Check if referencing a property with __attribute__((deprecated)).
1757 DiagnoseUseOfDeprecatedDecl(Getter, MemberLoc);
1758
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001759 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001760 // will look for the matching setter, in case it is needed.
1761 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1762 &Member);
1763 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1764 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1765 if (!Setter) {
1766 // If this reference is in an @implementation, also check for 'private'
1767 // methods.
1768 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1769 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1770 if (ObjCImplementationDecl *ImpDecl =
1771 ObjCImplementations[ClassDecl->getIdentifier()])
1772 Setter = ImpDecl->getInstanceMethod(SetterSel);
1773 }
1774 // Look through local category implementations associated with the class.
1775 if (!Setter) {
1776 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1777 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1778 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1779 }
1780 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001781
Chris Lattner51f6fb32009-02-16 18:35:08 +00001782 if (Setter)
1783 // Check if referencing a property with __attribute__((deprecated)).
1784 DiagnoseUseOfDeprecatedDecl(Setter, MemberLoc);
1785
1786
Sebastian Redl8b769972009-01-19 00:08:26 +00001787 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001788 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1789 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001790 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001791
1792 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1793 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001794 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001795 // Handle properties on qualified "id" protocols.
1796 const ObjCQualifiedIdType *QIdTy;
1797 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1798 // Check protocols on qualified interfaces.
1799 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001800 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001801 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1802 // Check if referencing a property with __attribute__((deprecated)).
1803 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1804
Steve Naroff774e4152009-01-21 00:14:39 +00001805 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001806 MemberLoc, BaseExpr));
1807 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001808 // Also must look for a getter name which uses property syntax.
1809 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1810 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001811 // Check if referencing a property with __attribute__((deprecated)).
1812 DiagnoseUseOfDeprecatedDecl(OMD, MemberLoc);
1813
Steve Naroff774e4152009-01-21 00:14:39 +00001814 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1815 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001816 }
1817 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001818
1819 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1820 << &Member << BaseType);
1821 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001822 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001823 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001824 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1825 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001826 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001827 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1828 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001829 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001830
1831 return ExprError(Diag(MemberLoc,
1832 diag::err_typecheck_member_reference_struct_union)
1833 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001834}
1835
Douglas Gregor3257fb52008-12-22 05:46:06 +00001836/// ConvertArgumentsForCall - Converts the arguments specified in
1837/// Args/NumArgs to the parameter types of the function FDecl with
1838/// function prototype Proto. Call is the call expression itself, and
1839/// Fn is the function expression. For a C++ member function, this
1840/// routine does not attempt to convert the object argument. Returns
1841/// true if the call is ill-formed.
1842bool
1843Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1844 FunctionDecl *FDecl,
1845 const FunctionTypeProto *Proto,
1846 Expr **Args, unsigned NumArgs,
1847 SourceLocation RParenLoc) {
1848 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1849 // assignment, to the types of the corresponding parameter, ...
1850 unsigned NumArgsInProto = Proto->getNumArgs();
1851 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001852 bool Invalid = false;
1853
Douglas Gregor3257fb52008-12-22 05:46:06 +00001854 // If too few arguments are available (and we don't have default
1855 // arguments for the remaining parameters), don't make the call.
1856 if (NumArgs < NumArgsInProto) {
1857 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1858 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1859 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1860 // Use default arguments for missing arguments
1861 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001862 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001863 }
1864
1865 // If too many are passed and not variadic, error on the extras and drop
1866 // them.
1867 if (NumArgs > NumArgsInProto) {
1868 if (!Proto->isVariadic()) {
1869 Diag(Args[NumArgsInProto]->getLocStart(),
1870 diag::err_typecheck_call_too_many_args)
1871 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1872 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1873 Args[NumArgs-1]->getLocEnd());
1874 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001875 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001876 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001877 }
1878 NumArgsToCheck = NumArgsInProto;
1879 }
1880
1881 // Continue to check argument types (even if we have too few/many args).
1882 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1883 QualType ProtoArgType = Proto->getArgType(i);
1884
1885 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001886 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001887 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001888
1889 // Pass the argument.
1890 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1891 return true;
1892 } else
1893 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001894 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001895 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001896
Douglas Gregor3257fb52008-12-22 05:46:06 +00001897 Call->setArg(i, Arg);
1898 }
1899
1900 // If this is a variadic call, handle args passed through "...".
1901 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001902 VariadicCallType CallType = VariadicFunction;
1903 if (Fn->getType()->isBlockPointerType())
1904 CallType = VariadicBlock; // Block
1905 else if (isa<MemberExpr>(Fn))
1906 CallType = VariadicMethod;
1907
Douglas Gregor3257fb52008-12-22 05:46:06 +00001908 // Promote the arguments (C99 6.5.2.2p7).
1909 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1910 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001911 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001912 Call->setArg(i, Arg);
1913 }
1914 }
1915
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001916 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001917}
1918
Steve Naroff87d58b42007-09-16 03:34:24 +00001919/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001920/// This provides the location of the left/right parens and a list of comma
1921/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001922Action::OwningExprResult
1923Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1924 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001925 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001926 unsigned NumArgs = args.size();
1927 Expr *Fn = static_cast<Expr *>(fn.release());
1928 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001929 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001930 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001931 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001932
Douglas Gregor3257fb52008-12-22 05:46:06 +00001933 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001934 // Determine whether this is a dependent call inside a C++ template,
1935 // in which case we won't do any semantic analysis now.
1936 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1937 bool Dependent = false;
1938 if (Fn->isTypeDependent())
1939 Dependent = true;
1940 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1941 Dependent = true;
1942
1943 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001944 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001945 Context.DependentTy, RParenLoc));
1946
1947 // Determine whether this is a call to an object (C++ [over.call.object]).
1948 if (Fn->getType()->isRecordType())
1949 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1950 CommaLocs, RParenLoc));
1951
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001952 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001953 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1954 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1955 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001956 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1957 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001958 }
1959
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001960 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001961 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001962 Expr *FnExpr = Fn;
1963 bool ADL = true;
1964 while (true) {
1965 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1966 FnExpr = IcExpr->getSubExpr();
1967 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001968 // Parentheses around a function disable ADL
1969 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001970 ADL = false;
1971 FnExpr = PExpr->getSubExpr();
1972 } else if (isa<UnaryOperator>(FnExpr) &&
1973 cast<UnaryOperator>(FnExpr)->getOpcode()
1974 == UnaryOperator::AddrOf) {
1975 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001976 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1977 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1978 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1979 break;
1980 } else if (UnresolvedFunctionNameExpr *DepName
1981 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1982 UnqualifiedName = DepName->getName();
1983 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001984 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001985 // Any kind of name that does not refer to a declaration (or
1986 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1987 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001988 break;
1989 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001990 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001991
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001992 OverloadedFunctionDecl *Ovl = 0;
1993 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001994 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001995 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1996 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001997
Douglas Gregorfcb19192009-02-11 23:02:49 +00001998 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001999 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002000 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002001 ADL = false;
2002
Douglas Gregorfcb19192009-02-11 23:02:49 +00002003 // We don't perform ADL in C.
2004 if (!getLangOptions().CPlusPlus)
2005 ADL = false;
2006
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002007 if (Ovl || ADL) {
2008 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2009 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002010 NumArgs, CommaLocs, RParenLoc, ADL);
2011 if (!FDecl)
2012 return ExprError();
2013
2014 // Update Fn to refer to the actual function selected.
2015 Expr *NewFn = 0;
2016 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002017 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002018 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2019 QDRExpr->getLocation(),
2020 false, false,
2021 QDRExpr->getSourceRange().getBegin());
2022 else
2023 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2024 Fn->getSourceRange().getBegin());
2025 Fn->Destroy(Context);
2026 Fn = NewFn;
2027 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002028 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002029
2030 // Promote the function operand.
2031 UsualUnaryConversions(Fn);
2032
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002033 // Make the call expr early, before semantic checks. This guarantees cleanup
2034 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00002035 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
2036 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002037 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2038 Args, NumArgs,
2039 Context.BoolTy,
2040 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002041
Steve Naroffd6163f32008-09-05 22:11:13 +00002042 const FunctionType *FuncT;
2043 if (!Fn->getType()->isBlockPointerType()) {
2044 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2045 // have type pointer to function".
2046 const PointerType *PT = Fn->getType()->getAsPointerType();
2047 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002048 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2049 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002050 FuncT = PT->getPointeeType()->getAsFunctionType();
2051 } else { // This is a block call.
2052 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2053 getAsFunctionType();
2054 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002055 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002056 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2057 << Fn->getType() << Fn->getSourceRange());
2058
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002059 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002060 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002061
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002062 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002063 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2064 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002065 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002066 } else {
2067 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002068
Steve Naroffdb65e052007-08-28 23:30:39 +00002069 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002070 for (unsigned i = 0; i != NumArgs; i++) {
2071 Expr *Arg = Args[i];
2072 DefaultArgumentPromotion(Arg);
2073 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002074 }
Chris Lattner4b009652007-07-25 00:24:17 +00002075 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002076
Douglas Gregor3257fb52008-12-22 05:46:06 +00002077 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2078 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002079 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2080 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002081
Chris Lattner2e64c072007-08-10 20:18:51 +00002082 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002083 if (FDecl)
2084 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002085
Sebastian Redl8b769972009-01-19 00:08:26 +00002086 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002087}
2088
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002089Action::OwningExprResult
2090Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2091 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002092 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002093 QualType literalType = QualType::getFromOpaquePtr(Ty);
2094 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002095 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002096 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002097
Eli Friedman8c2173d2008-05-20 05:22:08 +00002098 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002099 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002100 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2101 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002102 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2103 diag::err_typecheck_decl_incomplete_type,
2104 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002105 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002106
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002107 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002108 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002109 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002110
Chris Lattnere5cb5862008-12-04 23:50:19 +00002111 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002112 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002113 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002114 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002115 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002116 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002117 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2118 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002119}
2120
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002121Action::OwningExprResult
2122Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2123 InitListDesignations &Designators,
2124 SourceLocation RBraceLoc) {
2125 unsigned NumInit = initlist.size();
2126 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002127
Steve Naroff0acc9c92007-09-15 18:49:24 +00002128 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002129 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002130
Steve Naroff774e4152009-01-21 00:14:39 +00002131 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002132 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002133 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002134 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002135}
2136
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002137/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002138bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002139 UsualUnaryConversions(castExpr);
2140
2141 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2142 // type needs to be scalar.
2143 if (castType->isVoidType()) {
2144 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002145 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2146 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002147 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002148 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2149 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2150 (castType->isStructureType() || castType->isUnionType())) {
2151 // GCC struct/union extension: allow cast to self.
2152 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2153 << castType << castExpr->getSourceRange();
2154 } else if (castType->isUnionType()) {
2155 // GCC cast to union extension
2156 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2157 RecordDecl::field_iterator Field, FieldEnd;
2158 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2159 Field != FieldEnd; ++Field) {
2160 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2161 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2162 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2163 << castExpr->getSourceRange();
2164 break;
2165 }
2166 }
2167 if (Field == FieldEnd)
2168 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2169 << castExpr->getType() << castExpr->getSourceRange();
2170 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002171 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002172 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002173 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002174 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002175 } else if (!castExpr->getType()->isScalarType() &&
2176 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002177 return Diag(castExpr->getLocStart(),
2178 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002179 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002180 } else if (castExpr->getType()->isVectorType()) {
2181 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2182 return true;
2183 } else if (castType->isVectorType()) {
2184 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2185 return true;
2186 }
2187 return false;
2188}
2189
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002190bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002191 assert(VectorTy->isVectorType() && "Not a vector type!");
2192
2193 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002194 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002195 return Diag(R.getBegin(),
2196 Ty->isVectorType() ?
2197 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002198 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002199 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002200 } else
2201 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002202 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002203 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002204
2205 return false;
2206}
2207
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002208Action::OwningExprResult
2209Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2210 SourceLocation RParenLoc, ExprArg Op) {
2211 assert((Ty != 0) && (Op.get() != 0) &&
2212 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002213
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002214 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002215 QualType castType = QualType::getFromOpaquePtr(Ty);
2216
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002217 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002218 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002219 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002220 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002221}
2222
Chris Lattner98a425c2007-11-26 01:40:58 +00002223/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2224/// In that case, lex = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002225/// C99 6.5.15
2226QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2227 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002228 UsualUnaryConversions(Cond);
2229 UsualUnaryConversions(LHS);
2230 UsualUnaryConversions(RHS);
2231 QualType CondTy = Cond->getType();
2232 QualType LHSTy = LHS->getType();
2233 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002234
2235 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002236 if (!Cond->isTypeDependent()) {
2237 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2238 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2239 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002240 return QualType();
2241 }
Chris Lattner4b009652007-07-25 00:24:17 +00002242 }
Chris Lattner992ae932008-01-06 22:42:25 +00002243
2244 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002245 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002246 return Context.DependentTy;
2247
Chris Lattner992ae932008-01-06 22:42:25 +00002248 // If both operands have arithmetic type, do the usual arithmetic conversions
2249 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002250 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2251 UsualArithmeticConversions(LHS, RHS);
2252 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002253 }
Chris Lattner992ae932008-01-06 22:42:25 +00002254
2255 // If both operands are the same structure or union type, the result is that
2256 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002257 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2258 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002259 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002260 // "If both the operands have structure or union type, the result has
2261 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002262 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002263 }
Chris Lattner992ae932008-01-06 22:42:25 +00002264
2265 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002266 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002267 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2268 if (!LHSTy->isVoidType())
2269 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2270 << RHS->getSourceRange();
2271 if (!RHSTy->isVoidType())
2272 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2273 << LHS->getSourceRange();
2274 ImpCastExprToType(LHS, Context.VoidTy);
2275 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002276 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002277 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002278 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2279 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002280 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2281 Context.isObjCObjectPointerType(LHSTy)) &&
2282 RHS->isNullPointerConstant(Context)) {
2283 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2284 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002285 }
Chris Lattnere2897262009-02-18 04:28:32 +00002286 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2287 Context.isObjCObjectPointerType(RHSTy)) &&
2288 LHS->isNullPointerConstant(Context)) {
2289 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2290 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002291 }
Chris Lattner9c039b52009-02-18 04:38:20 +00002292
Chris Lattner0ac51632008-01-06 22:50:31 +00002293 // Handle the case where both operands are pointers before we handle null
2294 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002295 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2296 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002297 // get the "pointed to" types
2298 QualType lhptee = LHSPT->getPointeeType();
2299 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002300
Chris Lattner71225142007-07-31 21:27:01 +00002301 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2302 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002303 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002304 // Figure out necessary qualifiers (C99 6.5.15p6)
2305 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002306 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002307 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2308 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002309 return destType;
2310 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002311 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002312 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002313 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002314 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2315 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002316 return destType;
2317 }
Chris Lattner4b009652007-07-25 00:24:17 +00002318
Chris Lattner9c039b52009-02-18 04:38:20 +00002319 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2320 // Two identical pointers types are always compatible.
2321 return LHSTy;
2322 }
2323
Chris Lattnere2897262009-02-18 04:28:32 +00002324 QualType compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002325
2326 // If either type is an Objective-C object type then check
2327 // compatibility according to Objective-C.
Chris Lattnere2897262009-02-18 04:28:32 +00002328 if (Context.isObjCObjectPointerType(LHSTy) ||
2329 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002330 // If both operands are interfaces and either operand can be
2331 // assigned to the other, use that type as the composite
2332 // type. This allows
2333 // xxx ? (A*) a : (B*) b
2334 // where B is a subclass of A.
2335 //
2336 // Additionally, as for assignment, if either type is 'id'
2337 // allow silent coercion. Finally, if the types are
2338 // incompatible then make sure to use 'id' as the composite
2339 // type so the result is acceptable for sending messages to.
2340
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002341 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2342 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002343 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2344 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2345 if (LHSIface && RHSIface &&
2346 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002347 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002348 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002349 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002350 compositeType = RHSTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002351 } else if (Context.isObjCIdStructType(lhptee) ||
2352 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002353 compositeType = Context.getObjCIdType();
2354 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002355 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2356 << LHSTy << RHSTy
2357 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002358 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002359 ImpCastExprToType(LHS, incompatTy);
2360 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002361 return incompatTy;
2362 }
2363 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2364 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002365 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2366 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002367 // In this situation, we assume void* type. No especially good
2368 // reason, but this is what gcc does, and we do have to pick
2369 // to get a consistent AST.
2370 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002371 ImpCastExprToType(LHS, incompatTy);
2372 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002373 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002374 }
2375 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002376 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2377 // differently qualified versions of compatible types, the result type is
2378 // a pointer to an appropriately qualified version of the *composite*
2379 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002380 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002381 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002382 ImpCastExprToType(LHS, compositeType);
2383 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002384 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002385 }
Chris Lattner4b009652007-07-25 00:24:17 +00002386 }
Chris Lattner9c039b52009-02-18 04:38:20 +00002387
2388 // Selection between block pointer types is ok as long as they are the same.
2389 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2390 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2391 return LHSTy;
2392
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002393 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2394 // evaluates to "struct objc_object *" (and is handled above when comparing
2395 // id with statically typed objects).
Chris Lattnere2897262009-02-18 04:28:32 +00002396 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002397 // GCC allows qualified id and any Objective-C type to devolve to
2398 // id. Currently localizing to here until clear this should be
2399 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002400 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
2401 (LHSTy->isObjCQualifiedIdType() &&
2402 Context.isObjCObjectPointerType(RHSTy)) ||
2403 (RHSTy->isObjCQualifiedIdType() &&
2404 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002405 // FIXME: This is not the correct composite type. This only
2406 // happens to work because id can more or less be used anywhere,
2407 // however this may change the type of method sends.
2408 // FIXME: gcc adds some type-checking of the arguments and emits
2409 // (confusing) incompatible comparison warnings in some
2410 // cases. Investigate.
2411 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002412 ImpCastExprToType(LHS, compositeType);
2413 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002414 return compositeType;
2415 }
2416 }
2417
Chris Lattner992ae932008-01-06 22:42:25 +00002418 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002419 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2420 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002421 return QualType();
2422}
2423
Steve Naroff87d58b42007-09-16 03:34:24 +00002424/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002425/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002426Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2427 SourceLocation ColonLoc,
2428 ExprArg Cond, ExprArg LHS,
2429 ExprArg RHS) {
2430 Expr *CondExpr = (Expr *) Cond.get();
2431 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002432
2433 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2434 // was the condition.
2435 bool isLHSNull = LHSExpr == 0;
2436 if (isLHSNull)
2437 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002438
2439 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002440 RHSExpr, QuestionLoc);
2441 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002442 return ExprError();
2443
2444 Cond.release();
2445 LHS.release();
2446 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002447 return Owned(new (Context) ConditionalOperator(CondExpr,
2448 isLHSNull ? 0 : LHSExpr,
2449 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002450}
2451
Chris Lattner4b009652007-07-25 00:24:17 +00002452
2453// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2454// being closely modeled after the C99 spec:-). The odd characteristic of this
2455// routine is it effectively iqnores the qualifiers on the top level pointee.
2456// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2457// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002458Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002459Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2460 QualType lhptee, rhptee;
2461
2462 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002463 lhptee = lhsType->getAsPointerType()->getPointeeType();
2464 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002465
2466 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002467 lhptee = Context.getCanonicalType(lhptee);
2468 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002469
Chris Lattner005ed752008-01-04 18:04:52 +00002470 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002471
2472 // C99 6.5.16.1p1: This following citation is common to constraints
2473 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2474 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002475 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002476 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002477 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002478
2479 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2480 // incomplete type and the other is a pointer to a qualified or unqualified
2481 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002482 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002483 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002484 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002485
2486 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002487 assert(rhptee->isFunctionType());
2488 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002489 }
2490
2491 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002492 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002493 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002494
2495 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002496 assert(lhptee->isFunctionType());
2497 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002498 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002499
2500 // Check for ObjC interfaces
2501 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2502 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2503 if (LHSIface && RHSIface &&
2504 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2505 return ConvTy;
2506
2507 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002508 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002509 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002510 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002511 return ConvTy;
2512
Chris Lattner4b009652007-07-25 00:24:17 +00002513 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2514 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002515 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2516 rhptee.getUnqualifiedType()))
2517 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002518 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002519}
2520
Steve Naroff3454b6c2008-09-04 15:10:53 +00002521/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2522/// block pointer types are compatible or whether a block and normal pointer
2523/// are compatible. It is more restrict than comparing two function pointer
2524// types.
2525Sema::AssignConvertType
2526Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2527 QualType rhsType) {
2528 QualType lhptee, rhptee;
2529
2530 // get the "pointed to" type (ignoring qualifiers at the top level)
2531 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2532 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2533
2534 // make sure we operate on the canonical type
2535 lhptee = Context.getCanonicalType(lhptee);
2536 rhptee = Context.getCanonicalType(rhptee);
2537
2538 AssignConvertType ConvTy = Compatible;
2539
2540 // For blocks we enforce that qualifiers are identical.
2541 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2542 ConvTy = CompatiblePointerDiscardsQualifiers;
2543
2544 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2545 return IncompatibleBlockPointer;
2546 return ConvTy;
2547}
2548
Chris Lattner4b009652007-07-25 00:24:17 +00002549/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2550/// has code to accommodate several GCC extensions when type checking
2551/// pointers. Here are some objectionable examples that GCC considers warnings:
2552///
2553/// int a, *pint;
2554/// short *pshort;
2555/// struct foo *pfoo;
2556///
2557/// pint = pshort; // warning: assignment from incompatible pointer type
2558/// a = pint; // warning: assignment makes integer from pointer without a cast
2559/// pint = a; // warning: assignment makes pointer from integer without a cast
2560/// pint = pfoo; // warning: assignment from incompatible pointer type
2561///
2562/// As a result, the code for dealing with pointers is more complex than the
2563/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002564///
Chris Lattner005ed752008-01-04 18:04:52 +00002565Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002566Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002567 // Get canonical types. We're not formatting these types, just comparing
2568 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002569 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2570 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002571
2572 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002573 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002574
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002575 // If the left-hand side is a reference type, then we are in a
2576 // (rare!) case where we've allowed the use of references in C,
2577 // e.g., as a parameter type in a built-in function. In this case,
2578 // just make sure that the type referenced is compatible with the
2579 // right-hand side type. The caller is responsible for adjusting
2580 // lhsType so that the resulting expression does not have reference
2581 // type.
2582 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2583 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002584 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002585 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002586 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002587
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002588 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2589 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002590 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002591 // Relax integer conversions like we do for pointers below.
2592 if (rhsType->isIntegerType())
2593 return IntToPointer;
2594 if (lhsType->isIntegerType())
2595 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002596 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002597 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002598
Nate Begemanc5f0f652008-07-14 18:02:46 +00002599 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002600 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002601 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2602 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002603 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002604
Nate Begemanc5f0f652008-07-14 18:02:46 +00002605 // If we are allowing lax vector conversions, and LHS and RHS are both
2606 // vectors, the total size only needs to be the same. This is a bitcast;
2607 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002608 if (getLangOptions().LaxVectorConversions &&
2609 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002610 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002611 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002612 }
2613 return Incompatible;
2614 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002615
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002616 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002617 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002618
Chris Lattner390564e2008-04-07 06:49:41 +00002619 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002620 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002621 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002622
Chris Lattner390564e2008-04-07 06:49:41 +00002623 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002624 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002625
Steve Naroffa982c712008-09-29 18:10:17 +00002626 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002627 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002628 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002629
2630 // Treat block pointers as objects.
2631 if (getLangOptions().ObjC1 &&
2632 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2633 return Compatible;
2634 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002635 return Incompatible;
2636 }
2637
2638 if (isa<BlockPointerType>(lhsType)) {
2639 if (rhsType->isIntegerType())
2640 return IntToPointer;
2641
Steve Naroffa982c712008-09-29 18:10:17 +00002642 // Treat block pointers as objects.
2643 if (getLangOptions().ObjC1 &&
2644 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2645 return Compatible;
2646
Steve Naroff3454b6c2008-09-04 15:10:53 +00002647 if (rhsType->isBlockPointerType())
2648 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2649
2650 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2651 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002652 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002653 }
Chris Lattner1853da22008-01-04 23:18:45 +00002654 return Incompatible;
2655 }
2656
Chris Lattner390564e2008-04-07 06:49:41 +00002657 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002658 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002659 if (lhsType == Context.BoolTy)
2660 return Compatible;
2661
2662 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002663 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002664
Chris Lattner390564e2008-04-07 06:49:41 +00002665 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002666 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002667
2668 if (isa<BlockPointerType>(lhsType) &&
2669 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002670 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002671 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002672 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002673
Chris Lattner1853da22008-01-04 23:18:45 +00002674 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002675 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002676 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002677 }
2678 return Incompatible;
2679}
2680
Chris Lattner005ed752008-01-04 18:04:52 +00002681Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002682Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002683 if (getLangOptions().CPlusPlus) {
2684 if (!lhsType->isRecordType()) {
2685 // C++ 5.17p3: If the left operand is not of class type, the
2686 // expression is implicitly converted (C++ 4) to the
2687 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002688 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2689 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002690 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002691 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002692 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002693 }
2694
2695 // FIXME: Currently, we fall through and treat C++ classes like C
2696 // structures.
2697 }
2698
Steve Naroffcdee22d2007-11-27 17:58:44 +00002699 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2700 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002701 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2702 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002703 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002704 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002705 return Compatible;
2706 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002707
2708 // We don't allow conversion of non-null-pointer constants to integers.
2709 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2710 return IntToBlockPointer;
2711
Chris Lattner5f505bf2007-10-16 02:55:40 +00002712 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002713 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002714 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002715 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002716 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002717 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002718 if (!lhsType->isReferenceType())
2719 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002720
Chris Lattner005ed752008-01-04 18:04:52 +00002721 Sema::AssignConvertType result =
2722 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002723
2724 // C99 6.5.16.1p2: The value of the right operand is converted to the
2725 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002726 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2727 // so that we can use references in built-in functions even in C.
2728 // The getNonReferenceType() call makes sure that the resulting expression
2729 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002730 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002731 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002732 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002733}
2734
Chris Lattner005ed752008-01-04 18:04:52 +00002735Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002736Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2737 return CheckAssignmentConstraints(lhsType, rhsType);
2738}
2739
Chris Lattner1eafdea2008-11-18 01:30:42 +00002740QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002741 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002742 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002743 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002744 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002745}
2746
Chris Lattner1eafdea2008-11-18 01:30:42 +00002747inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002748 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002749 // For conversion purposes, we ignore any qualifiers.
2750 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002751 QualType lhsType =
2752 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2753 QualType rhsType =
2754 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002755
Nate Begemanc5f0f652008-07-14 18:02:46 +00002756 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002757 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002758 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002759
Nate Begemanc5f0f652008-07-14 18:02:46 +00002760 // Handle the case of a vector & extvector type of the same size and element
2761 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002762 if (getLangOptions().LaxVectorConversions) {
2763 // FIXME: Should we warn here?
2764 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002765 if (const VectorType *RV = rhsType->getAsVectorType())
2766 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002767 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002768 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002769 }
2770 }
2771 }
2772
Nate Begemanc5f0f652008-07-14 18:02:46 +00002773 // If the lhs is an extended vector and the rhs is a scalar of the same type
2774 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002775 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002776 QualType eltType = V->getElementType();
2777
2778 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2779 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2780 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002781 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002782 return lhsType;
2783 }
2784 }
2785
Nate Begemanc5f0f652008-07-14 18:02:46 +00002786 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002787 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002788 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002789 QualType eltType = V->getElementType();
2790
2791 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2792 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2793 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002794 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002795 return rhsType;
2796 }
2797 }
2798
Chris Lattner4b009652007-07-25 00:24:17 +00002799 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002800 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002801 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002802 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002803 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002804}
2805
Chris Lattner4b009652007-07-25 00:24:17 +00002806inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002807 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002808{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002809 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002810 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002811
Steve Naroff8f708362007-08-24 19:07:16 +00002812 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002813
Chris Lattner4b009652007-07-25 00:24:17 +00002814 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002815 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002816 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002817}
2818
2819inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002820 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002821{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002822 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2823 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2824 return CheckVectorOperands(Loc, lex, rex);
2825 return InvalidOperands(Loc, lex, rex);
2826 }
Chris Lattner4b009652007-07-25 00:24:17 +00002827
Steve Naroff8f708362007-08-24 19:07:16 +00002828 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002829
Chris Lattner4b009652007-07-25 00:24:17 +00002830 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002831 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002832 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002833}
2834
2835inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002836 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002837{
2838 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002839 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002840
Steve Naroff8f708362007-08-24 19:07:16 +00002841 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002842
Chris Lattner4b009652007-07-25 00:24:17 +00002843 // handle the common case first (both operands are arithmetic).
2844 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002845 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002846
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002847 // Put any potential pointer into PExp
2848 Expr* PExp = lex, *IExp = rex;
2849 if (IExp->getType()->isPointerType())
2850 std::swap(PExp, IExp);
2851
2852 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2853 if (IExp->getType()->isIntegerType()) {
2854 // Check for arithmetic on pointers to incomplete types
2855 if (!PTy->getPointeeType()->isObjectType()) {
2856 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002857 if (getLangOptions().CPlusPlus) {
2858 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2859 << lex->getSourceRange() << rex->getSourceRange();
2860 return QualType();
2861 }
2862
2863 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002864 Diag(Loc, diag::ext_gnu_void_ptr)
2865 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002866 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002867 if (getLangOptions().CPlusPlus) {
2868 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2869 << lex->getType() << lex->getSourceRange();
2870 return QualType();
2871 }
2872
2873 // GNU extension: arithmetic on pointer to function
2874 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002875 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002876 } else {
2877 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2878 diag::err_typecheck_arithmetic_incomplete_type,
2879 lex->getSourceRange(), SourceRange(),
2880 lex->getType());
2881 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002882 }
2883 }
2884 return PExp->getType();
2885 }
2886 }
2887
Chris Lattner1eafdea2008-11-18 01:30:42 +00002888 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002889}
2890
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002891// C99 6.5.6
2892QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002893 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002894 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002895 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002896
Steve Naroff8f708362007-08-24 19:07:16 +00002897 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002898
Chris Lattnerf6da2912007-12-09 21:53:25 +00002899 // Enforce type constraints: C99 6.5.6p3.
2900
2901 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002902 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002903 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002904
2905 // Either ptr - int or ptr - ptr.
2906 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002907 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002908
Chris Lattnerf6da2912007-12-09 21:53:25 +00002909 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002910 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002911 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002912 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002913 Diag(Loc, diag::ext_gnu_void_ptr)
2914 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002915 } else if (lpointee->isFunctionType()) {
2916 if (getLangOptions().CPlusPlus) {
2917 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2918 << lex->getType() << lex->getSourceRange();
2919 return QualType();
2920 }
2921
2922 // GNU extension: arithmetic on pointer to function
2923 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2924 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002925 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002926 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002927 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002928 return QualType();
2929 }
2930 }
2931
2932 // The result type of a pointer-int computation is the pointer type.
2933 if (rex->getType()->isIntegerType())
2934 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002935
Chris Lattnerf6da2912007-12-09 21:53:25 +00002936 // Handle pointer-pointer subtractions.
2937 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002938 QualType rpointee = RHSPTy->getPointeeType();
2939
Chris Lattnerf6da2912007-12-09 21:53:25 +00002940 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002941 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002942 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002943 if (rpointee->isVoidType()) {
2944 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002945 Diag(Loc, diag::ext_gnu_void_ptr)
2946 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002947 } else if (rpointee->isFunctionType()) {
2948 if (getLangOptions().CPlusPlus) {
2949 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2950 << rex->getType() << rex->getSourceRange();
2951 return QualType();
2952 }
2953
2954 // GNU extension: arithmetic on pointer to function
2955 if (!lpointee->isFunctionType())
2956 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2957 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002958 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002959 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002960 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002961 return QualType();
2962 }
2963 }
2964
2965 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002966 if (!Context.typesAreCompatible(
2967 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2968 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002969 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002970 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002971 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002972 return QualType();
2973 }
2974
2975 return Context.getPointerDiffType();
2976 }
2977 }
2978
Chris Lattner1eafdea2008-11-18 01:30:42 +00002979 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002980}
2981
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002982// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002983QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002984 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002985 // C99 6.5.7p2: Each of the operands shall have integer type.
2986 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002987 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002988
Chris Lattner2c8bff72007-12-12 05:47:28 +00002989 // Shifts don't perform usual arithmetic conversions, they just do integer
2990 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002991 if (!isCompAssign)
2992 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002993 UsualUnaryConversions(rex);
2994
2995 // "The type of the result is that of the promoted left operand."
2996 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002997}
2998
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002999// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003000QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003001 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003002 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003003 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003004
Chris Lattner254f3bc2007-08-26 01:18:55 +00003005 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003006 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3007 UsualArithmeticConversions(lex, rex);
3008 else {
3009 UsualUnaryConversions(lex);
3010 UsualUnaryConversions(rex);
3011 }
Chris Lattner4b009652007-07-25 00:24:17 +00003012 QualType lType = lex->getType();
3013 QualType rType = rex->getType();
3014
Ted Kremenek486509e2007-10-29 17:13:39 +00003015 // For non-floating point types, check for self-comparisons of the form
3016 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3017 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003018 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003019 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3020 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003021 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003022 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003023 }
3024
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003025 // The result of comparisons is 'bool' in C++, 'int' in C.
3026 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3027
Chris Lattner254f3bc2007-08-26 01:18:55 +00003028 if (isRelational) {
3029 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003030 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003031 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003032 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003033 if (lType->isFloatingType()) {
3034 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003035 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003036 }
3037
Chris Lattner254f3bc2007-08-26 01:18:55 +00003038 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003039 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003040 }
Chris Lattner4b009652007-07-25 00:24:17 +00003041
Chris Lattner22be8422007-08-26 01:10:14 +00003042 bool LHSIsNull = lex->isNullPointerConstant(Context);
3043 bool RHSIsNull = rex->isNullPointerConstant(Context);
3044
Chris Lattner254f3bc2007-08-26 01:18:55 +00003045 // All of the following pointer related warnings are GCC extensions, except
3046 // when handling null pointer constants. One day, we can consider making them
3047 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003048 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003049 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003050 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003051 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003052 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00003053
Steve Naroff3b435622007-11-13 14:57:38 +00003054 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003055 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3056 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003057 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003058 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003059 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003060 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003061 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003062 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003063 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003064 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003065 // Handle block pointer types.
3066 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3067 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3068 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3069
3070 if (!LHSIsNull && !RHSIsNull &&
3071 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003072 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003073 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003074 }
3075 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003076 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003077 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003078 // Allow block pointers to be compared with null pointer constants.
3079 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3080 (lType->isPointerType() && rType->isBlockPointerType())) {
3081 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003082 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003083 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003084 }
3085 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003086 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003087 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003088
Steve Naroff936c4362008-06-03 14:04:54 +00003089 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003090 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003091 const PointerType *LPT = lType->getAsPointerType();
3092 const PointerType *RPT = rType->getAsPointerType();
3093 bool LPtrToVoid = LPT ?
3094 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3095 bool RPtrToVoid = RPT ?
3096 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3097
3098 if (!LPtrToVoid && !RPtrToVoid &&
3099 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003100 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003101 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003102 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003103 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003104 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003105 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003106 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003107 }
Steve Naroff936c4362008-06-03 14:04:54 +00003108 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3109 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003110 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003111 } else {
3112 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003113 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003114 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003115 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003116 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003117 }
Steve Naroff936c4362008-06-03 14:04:54 +00003118 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003119 }
Steve Naroff936c4362008-06-03 14:04:54 +00003120 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3121 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003122 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003123 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003124 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003125 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003126 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003127 }
Steve Naroff936c4362008-06-03 14:04:54 +00003128 if (lType->isIntegerType() &&
3129 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003130 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003131 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003132 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003133 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003134 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003135 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003136 // Handle block pointers.
3137 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3138 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003139 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003140 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003141 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003142 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003143 }
3144 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3145 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003146 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003147 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003148 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003149 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003150 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003151 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003152}
3153
Nate Begemanc5f0f652008-07-14 18:02:46 +00003154/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3155/// operates on extended vector types. Instead of producing an IntTy result,
3156/// like a scalar comparison, a vector comparison produces a vector of integer
3157/// types.
3158QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003159 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003160 bool isRelational) {
3161 // Check to make sure we're operating on vectors of the same type and width,
3162 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003163 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003164 if (vType.isNull())
3165 return vType;
3166
3167 QualType lType = lex->getType();
3168 QualType rType = rex->getType();
3169
3170 // For non-floating point types, check for self-comparisons of the form
3171 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3172 // often indicate logic errors in the program.
3173 if (!lType->isFloatingType()) {
3174 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3175 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3176 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003177 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003178 }
3179
3180 // Check for comparisons of floating point operands using != and ==.
3181 if (!isRelational && lType->isFloatingType()) {
3182 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003183 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003184 }
3185
3186 // Return the type for the comparison, which is the same as vector type for
3187 // integer vectors, or an integer type of identical size and number of
3188 // elements for floating point vectors.
3189 if (lType->isIntegerType())
3190 return lType;
3191
3192 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003193 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003194 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003195 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003196 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3197 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3198
3199 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3200 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003201 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3202}
3203
Chris Lattner4b009652007-07-25 00:24:17 +00003204inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003205 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003206{
3207 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003208 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003209
Steve Naroff8f708362007-08-24 19:07:16 +00003210 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003211
3212 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003213 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003214 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003215}
3216
3217inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003218 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003219{
3220 UsualUnaryConversions(lex);
3221 UsualUnaryConversions(rex);
3222
Eli Friedmanbea3f842008-05-13 20:16:47 +00003223 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003224 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003225 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003226}
3227
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003228/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3229/// is a read-only property; return true if so. A readonly property expression
3230/// depends on various declarations and thus must be treated specially.
3231///
3232static bool IsReadonlyProperty(Expr *E, Sema &S)
3233{
3234 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3235 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3236 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3237 QualType BaseType = PropExpr->getBase()->getType();
3238 if (const PointerType *PTy = BaseType->getAsPointerType())
3239 if (const ObjCInterfaceType *IFTy =
3240 PTy->getPointeeType()->getAsObjCInterfaceType())
3241 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3242 if (S.isPropertyReadonly(PDecl, IFace))
3243 return true;
3244 }
3245 }
3246 return false;
3247}
3248
Chris Lattner4c2642c2008-11-18 01:22:49 +00003249/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3250/// emit an error and return true. If so, return false.
3251static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003252 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3253 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3254 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003255 if (IsLV == Expr::MLV_Valid)
3256 return false;
3257
3258 unsigned Diag = 0;
3259 bool NeedType = false;
3260 switch (IsLV) { // C99 6.5.16p2
3261 default: assert(0 && "Unknown result from isModifiableLvalue!");
3262 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003263 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003264 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3265 NeedType = true;
3266 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003267 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003268 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3269 NeedType = true;
3270 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003271 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003272 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3273 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003274 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003275 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3276 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003277 case Expr::MLV_IncompleteType:
3278 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003279 return S.DiagnoseIncompleteType(Loc, E->getType(),
3280 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3281 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003282 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003283 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3284 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003285 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003286 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3287 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003288 case Expr::MLV_ReadonlyProperty:
3289 Diag = diag::error_readonly_property_assignment;
3290 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003291 case Expr::MLV_NoSetterProperty:
3292 Diag = diag::error_nosetter_property_assignment;
3293 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003294 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003295
Chris Lattner4c2642c2008-11-18 01:22:49 +00003296 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003297 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003298 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003299 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003300 return true;
3301}
3302
3303
3304
3305// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003306QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3307 SourceLocation Loc,
3308 QualType CompoundType) {
3309 // Verify that LHS is a modifiable lvalue, and emit error if not.
3310 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003311 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003312
3313 QualType LHSType = LHS->getType();
3314 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003315
Chris Lattner005ed752008-01-04 18:04:52 +00003316 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003317 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003318 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003319 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003320 // Special case of NSObject attributes on c-style pointer types.
3321 if (ConvTy == IncompatiblePointer &&
3322 ((Context.isObjCNSObjectType(LHSType) &&
3323 Context.isObjCObjectPointerType(RHSType)) ||
3324 (Context.isObjCNSObjectType(RHSType) &&
3325 Context.isObjCObjectPointerType(LHSType))))
3326 ConvTy = Compatible;
3327
Chris Lattner34c85082008-08-21 18:04:13 +00003328 // If the RHS is a unary plus or minus, check to see if they = and + are
3329 // right next to each other. If so, the user may have typo'd "x =+ 4"
3330 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003331 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003332 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3333 RHSCheck = ICE->getSubExpr();
3334 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3335 if ((UO->getOpcode() == UnaryOperator::Plus ||
3336 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003337 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003338 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003339 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003340 Diag(Loc, diag::warn_not_compound_assign)
3341 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3342 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003343 }
3344 } else {
3345 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003346 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003347 }
Chris Lattner005ed752008-01-04 18:04:52 +00003348
Chris Lattner1eafdea2008-11-18 01:30:42 +00003349 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3350 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003351 return QualType();
3352
Chris Lattner4b009652007-07-25 00:24:17 +00003353 // C99 6.5.16p3: The type of an assignment expression is the type of the
3354 // left operand unless the left operand has qualified type, in which case
3355 // it is the unqualified version of the type of the left operand.
3356 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3357 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003358 // C++ 5.17p1: the type of the assignment expression is that of its left
3359 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003360 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003361}
3362
Chris Lattner1eafdea2008-11-18 01:30:42 +00003363// C99 6.5.17
3364QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3365 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003366
3367 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003368 DefaultFunctionArrayConversion(RHS);
3369 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003370}
3371
3372/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3373/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003374QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3375 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003376 QualType ResType = Op->getType();
3377 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003378
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003379 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3380 // Decrement of bool is not allowed.
3381 if (!isInc) {
3382 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3383 return QualType();
3384 }
3385 // Increment of bool sets it to true, but is deprecated.
3386 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3387 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003388 // OK!
3389 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3390 // C99 6.5.2.4p2, 6.5.6p2
3391 if (PT->getPointeeType()->isObjectType()) {
3392 // Pointer to object is ok!
3393 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003394 if (getLangOptions().CPlusPlus) {
3395 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3396 << Op->getSourceRange();
3397 return QualType();
3398 }
3399
3400 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003401 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003402 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003403 if (getLangOptions().CPlusPlus) {
3404 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3405 << Op->getType() << Op->getSourceRange();
3406 return QualType();
3407 }
3408
3409 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003410 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003411 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003412 } else {
3413 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3414 diag::err_typecheck_arithmetic_incomplete_type,
3415 Op->getSourceRange(), SourceRange(),
3416 ResType);
3417 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003418 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003419 } else if (ResType->isComplexType()) {
3420 // C99 does not support ++/-- on complex types, we allow as an extension.
3421 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003422 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003423 } else {
3424 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003425 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003426 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003427 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003428 // At this point, we know we have a real, complex or pointer type.
3429 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003430 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003431 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003432 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003433}
3434
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003435/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003436/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003437/// where the declaration is needed for type checking. We only need to
3438/// handle cases when the expression references a function designator
3439/// or is an lvalue. Here are some examples:
3440/// - &(x) => x
3441/// - &*****f => f for f a function designator.
3442/// - &s.xx => s
3443/// - &s.zz[1].yy -> s, if zz is an array
3444/// - *(x + 1) -> x, if x is an array
3445/// - &"123"[2] -> 0
3446/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003447static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003448 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003449 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003450 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003451 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003452 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003453 // Fields cannot be declared with a 'register' storage class.
3454 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003455 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003456 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003457 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003458 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003459 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003460
Douglas Gregord2baafd2008-10-21 16:13:35 +00003461 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003462 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003463 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003464 return 0;
3465 else
3466 return VD;
3467 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003468 case Stmt::UnaryOperatorClass: {
3469 UnaryOperator *UO = cast<UnaryOperator>(E);
3470
3471 switch(UO->getOpcode()) {
3472 case UnaryOperator::Deref: {
3473 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003474 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3475 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3476 if (!VD || VD->getType()->isPointerType())
3477 return 0;
3478 return VD;
3479 }
3480 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003481 }
3482 case UnaryOperator::Real:
3483 case UnaryOperator::Imag:
3484 case UnaryOperator::Extension:
3485 return getPrimaryDecl(UO->getSubExpr());
3486 default:
3487 return 0;
3488 }
3489 }
3490 case Stmt::BinaryOperatorClass: {
3491 BinaryOperator *BO = cast<BinaryOperator>(E);
3492
3493 // Handle cases involving pointer arithmetic. The result of an
3494 // Assign or AddAssign is not an lvalue so they can be ignored.
3495
3496 // (x + n) or (n + x) => x
3497 if (BO->getOpcode() == BinaryOperator::Add) {
3498 if (BO->getLHS()->getType()->isPointerType()) {
3499 return getPrimaryDecl(BO->getLHS());
3500 } else if (BO->getRHS()->getType()->isPointerType()) {
3501 return getPrimaryDecl(BO->getRHS());
3502 }
3503 }
3504
3505 return 0;
3506 }
Chris Lattner4b009652007-07-25 00:24:17 +00003507 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003508 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003509 case Stmt::ImplicitCastExprClass:
3510 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003511 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003512 default:
3513 return 0;
3514 }
3515}
3516
3517/// CheckAddressOfOperand - The operand of & must be either a function
3518/// designator or an lvalue designating an object. If it is an lvalue, the
3519/// object cannot be declared with storage class register or be a bit field.
3520/// Note: The usual conversions are *not* applied to the operand of the &
3521/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003522/// In C++, the operand might be an overloaded function name, in which case
3523/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003524QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003525 if (op->isTypeDependent())
3526 return Context.DependentTy;
3527
Steve Naroff9c6c3592008-01-13 17:10:08 +00003528 if (getLangOptions().C99) {
3529 // Implement C99-only parts of addressof rules.
3530 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3531 if (uOp->getOpcode() == UnaryOperator::Deref)
3532 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3533 // (assuming the deref expression is valid).
3534 return uOp->getSubExpr()->getType();
3535 }
3536 // Technically, there should be a check for array subscript
3537 // expressions here, but the result of one is always an lvalue anyway.
3538 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003539 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003540 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003541
Chris Lattner4b009652007-07-25 00:24:17 +00003542 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003543 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3544 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003545 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3546 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003547 return QualType();
3548 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003549 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003550 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3551 if (Field->isBitField()) {
3552 Diag(OpLoc, diag::err_typecheck_address_of)
3553 << "bit-field" << op->getSourceRange();
3554 return QualType();
3555 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003556 }
3557 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003558 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3559 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003560 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003561 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003562 return QualType();
3563 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003564 // We have an lvalue with a decl. Make sure the decl is not declared
3565 // with the register storage-class specifier.
3566 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3567 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003568 Diag(OpLoc, diag::err_typecheck_address_of)
3569 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003570 return QualType();
3571 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003572 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003573 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003574 } else if (isa<FieldDecl>(dcl)) {
3575 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003576 // Could be a pointer to member, though, if there is an explicit
3577 // scope qualifier for the class.
3578 if (isa<QualifiedDeclRefExpr>(op)) {
3579 DeclContext *Ctx = dcl->getDeclContext();
3580 if (Ctx && Ctx->isRecord())
3581 return Context.getMemberPointerType(op->getType(),
3582 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3583 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003584 } else if (isa<FunctionDecl>(dcl)) {
3585 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003586 // As above.
3587 if (isa<QualifiedDeclRefExpr>(op)) {
3588 DeclContext *Ctx = dcl->getDeclContext();
3589 if (Ctx && Ctx->isRecord())
3590 return Context.getMemberPointerType(op->getType(),
3591 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3592 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003593 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003594 else
Chris Lattner4b009652007-07-25 00:24:17 +00003595 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003596 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003597
Chris Lattner4b009652007-07-25 00:24:17 +00003598 // If the operand has type "type", the result has type "pointer to type".
3599 return Context.getPointerType(op->getType());
3600}
3601
Chris Lattnerda5c0872008-11-23 09:13:29 +00003602QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3603 UsualUnaryConversions(Op);
3604 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003605
Chris Lattnerda5c0872008-11-23 09:13:29 +00003606 // Note that per both C89 and C99, this is always legal, even if ptype is an
3607 // incomplete type or void. It would be possible to warn about dereferencing
3608 // a void pointer, but it's completely well-defined, and such a warning is
3609 // unlikely to catch any mistakes.
3610 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003611 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003612
Chris Lattner77d52da2008-11-20 06:06:08 +00003613 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003614 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003615 return QualType();
3616}
3617
3618static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3619 tok::TokenKind Kind) {
3620 BinaryOperator::Opcode Opc;
3621 switch (Kind) {
3622 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003623 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3624 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003625 case tok::star: Opc = BinaryOperator::Mul; break;
3626 case tok::slash: Opc = BinaryOperator::Div; break;
3627 case tok::percent: Opc = BinaryOperator::Rem; break;
3628 case tok::plus: Opc = BinaryOperator::Add; break;
3629 case tok::minus: Opc = BinaryOperator::Sub; break;
3630 case tok::lessless: Opc = BinaryOperator::Shl; break;
3631 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3632 case tok::lessequal: Opc = BinaryOperator::LE; break;
3633 case tok::less: Opc = BinaryOperator::LT; break;
3634 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3635 case tok::greater: Opc = BinaryOperator::GT; break;
3636 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3637 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3638 case tok::amp: Opc = BinaryOperator::And; break;
3639 case tok::caret: Opc = BinaryOperator::Xor; break;
3640 case tok::pipe: Opc = BinaryOperator::Or; break;
3641 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3642 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3643 case tok::equal: Opc = BinaryOperator::Assign; break;
3644 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3645 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3646 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3647 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3648 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3649 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3650 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3651 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3652 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3653 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3654 case tok::comma: Opc = BinaryOperator::Comma; break;
3655 }
3656 return Opc;
3657}
3658
3659static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3660 tok::TokenKind Kind) {
3661 UnaryOperator::Opcode Opc;
3662 switch (Kind) {
3663 default: assert(0 && "Unknown unary op!");
3664 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3665 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3666 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3667 case tok::star: Opc = UnaryOperator::Deref; break;
3668 case tok::plus: Opc = UnaryOperator::Plus; break;
3669 case tok::minus: Opc = UnaryOperator::Minus; break;
3670 case tok::tilde: Opc = UnaryOperator::Not; break;
3671 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003672 case tok::kw___real: Opc = UnaryOperator::Real; break;
3673 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3674 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3675 }
3676 return Opc;
3677}
3678
Douglas Gregord7f915e2008-11-06 23:29:22 +00003679/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3680/// operator @p Opc at location @c TokLoc. This routine only supports
3681/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003682Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3683 unsigned Op,
3684 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003685 QualType ResultTy; // Result type of the binary operator.
3686 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3687 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3688
3689 switch (Opc) {
3690 default:
3691 assert(0 && "Unknown binary expr!");
3692 case BinaryOperator::Assign:
3693 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3694 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003695 case BinaryOperator::PtrMemD:
3696 case BinaryOperator::PtrMemI:
3697 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3698 Opc == BinaryOperator::PtrMemI);
3699 break;
3700 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003701 case BinaryOperator::Div:
3702 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3703 break;
3704 case BinaryOperator::Rem:
3705 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3706 break;
3707 case BinaryOperator::Add:
3708 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3709 break;
3710 case BinaryOperator::Sub:
3711 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3712 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003713 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003714 case BinaryOperator::Shr:
3715 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3716 break;
3717 case BinaryOperator::LE:
3718 case BinaryOperator::LT:
3719 case BinaryOperator::GE:
3720 case BinaryOperator::GT:
3721 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3722 break;
3723 case BinaryOperator::EQ:
3724 case BinaryOperator::NE:
3725 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3726 break;
3727 case BinaryOperator::And:
3728 case BinaryOperator::Xor:
3729 case BinaryOperator::Or:
3730 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3731 break;
3732 case BinaryOperator::LAnd:
3733 case BinaryOperator::LOr:
3734 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3735 break;
3736 case BinaryOperator::MulAssign:
3737 case BinaryOperator::DivAssign:
3738 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3739 if (!CompTy.isNull())
3740 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3741 break;
3742 case BinaryOperator::RemAssign:
3743 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3744 if (!CompTy.isNull())
3745 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3746 break;
3747 case BinaryOperator::AddAssign:
3748 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3749 if (!CompTy.isNull())
3750 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3751 break;
3752 case BinaryOperator::SubAssign:
3753 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3754 if (!CompTy.isNull())
3755 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3756 break;
3757 case BinaryOperator::ShlAssign:
3758 case BinaryOperator::ShrAssign:
3759 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3760 if (!CompTy.isNull())
3761 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3762 break;
3763 case BinaryOperator::AndAssign:
3764 case BinaryOperator::XorAssign:
3765 case BinaryOperator::OrAssign:
3766 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3767 if (!CompTy.isNull())
3768 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3769 break;
3770 case BinaryOperator::Comma:
3771 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3772 break;
3773 }
3774 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003775 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003776 if (CompTy.isNull())
3777 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3778 else
3779 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003780 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003781}
3782
Chris Lattner4b009652007-07-25 00:24:17 +00003783// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003784Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3785 tok::TokenKind Kind,
3786 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003787 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003788 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003789
Steve Naroff87d58b42007-09-16 03:34:24 +00003790 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3791 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003792
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003793 // If either expression is type-dependent, just build the AST.
3794 // FIXME: We'll need to perform some caching of the result of name
3795 // lookup for operator+.
3796 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003797 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3798 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003799 Context.DependentTy,
3800 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003801 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003802 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3803 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003804 }
3805
Sebastian Redl95216a62009-02-07 00:15:38 +00003806 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003807 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3808 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003809 // If this is one of the assignment operators, we only perform
3810 // overload resolution if the left-hand side is a class or
3811 // enumeration type (C++ [expr.ass]p3).
3812 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3813 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3814 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3815 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003816
Douglas Gregord7f915e2008-11-06 23:29:22 +00003817 // Determine which overloaded operator we're dealing with.
3818 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003819 // Overloading .* is not possible.
3820 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003821 OO_Star, OO_Slash, OO_Percent,
3822 OO_Plus, OO_Minus,
3823 OO_LessLess, OO_GreaterGreater,
3824 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3825 OO_EqualEqual, OO_ExclaimEqual,
3826 OO_Amp,
3827 OO_Caret,
3828 OO_Pipe,
3829 OO_AmpAmp,
3830 OO_PipePipe,
3831 OO_Equal, OO_StarEqual,
3832 OO_SlashEqual, OO_PercentEqual,
3833 OO_PlusEqual, OO_MinusEqual,
3834 OO_LessLessEqual, OO_GreaterGreaterEqual,
3835 OO_AmpEqual, OO_CaretEqual,
3836 OO_PipeEqual,
3837 OO_Comma
3838 };
3839 OverloadedOperatorKind OverOp = OverOps[Opc];
3840
Douglas Gregor5ed15042008-11-18 23:14:02 +00003841 // Add the appropriate overloaded operators (C++ [over.match.oper])
3842 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003843 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003844 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003845 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3846 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003847
3848 // Perform overload resolution.
3849 OverloadCandidateSet::iterator Best;
3850 switch (BestViableFunction(CandidateSet, Best)) {
3851 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003852 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003853 FunctionDecl *FnDecl = Best->Function;
3854
Douglas Gregor70d26122008-11-12 17:17:38 +00003855 if (FnDecl) {
3856 // We matched an overloaded operator. Build a call to that
3857 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003858
Douglas Gregor70d26122008-11-12 17:17:38 +00003859 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003860 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3861 if (PerformObjectArgumentInitialization(lhs, Method) ||
3862 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3863 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003864 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003865 } else {
3866 // Convert the arguments.
3867 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3868 "passing") ||
3869 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3870 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003871 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003872 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003873
Douglas Gregor70d26122008-11-12 17:17:38 +00003874 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003875 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003876 = FnDecl->getType()->getAsFunctionType()->getResultType();
3877 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003878
Douglas Gregor70d26122008-11-12 17:17:38 +00003879 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003880 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3881 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003882 UsualUnaryConversions(FnExpr);
3883
Ted Kremenek362abcd2009-02-09 20:51:47 +00003884 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003885 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003886 } else {
3887 // We matched a built-in operator. Convert the arguments, then
3888 // break out so that we will build the appropriate built-in
3889 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003890 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3891 Best->Conversions[0], "passing") ||
3892 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3893 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003894 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003895
3896 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003897 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003898 }
3899
3900 case OR_No_Viable_Function:
3901 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003902 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003903 break;
3904
3905 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003906 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3907 << BinaryOperator::getOpcodeStr(Opc)
3908 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003909 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003910 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003911 }
3912
Douglas Gregor70d26122008-11-12 17:17:38 +00003913 // Either we found no viable overloaded operator or we matched a
3914 // built-in operator. In either case, fall through to trying to
3915 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003916 }
3917
Douglas Gregord7f915e2008-11-06 23:29:22 +00003918 // Build a built-in binary operation.
3919 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003920}
3921
3922// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003923Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3924 tok::TokenKind Op, ExprArg input) {
3925 // FIXME: Input is modified later, but smart pointer not reassigned.
3926 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003927 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003928
3929 if (getLangOptions().CPlusPlus &&
3930 (Input->getType()->isRecordType()
3931 || Input->getType()->isEnumeralType())) {
3932 // Determine which overloaded operator we're dealing with.
3933 static const OverloadedOperatorKind OverOps[] = {
3934 OO_None, OO_None,
3935 OO_PlusPlus, OO_MinusMinus,
3936 OO_Amp, OO_Star,
3937 OO_Plus, OO_Minus,
3938 OO_Tilde, OO_Exclaim,
3939 OO_None, OO_None,
3940 OO_None,
3941 OO_None
3942 };
3943 OverloadedOperatorKind OverOp = OverOps[Opc];
3944
3945 // Add the appropriate overloaded operators (C++ [over.match.oper])
3946 // to the candidate set.
3947 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003948 if (OverOp != OO_None &&
3949 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3950 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003951
3952 // Perform overload resolution.
3953 OverloadCandidateSet::iterator Best;
3954 switch (BestViableFunction(CandidateSet, Best)) {
3955 case OR_Success: {
3956 // We found a built-in operator or an overloaded operator.
3957 FunctionDecl *FnDecl = Best->Function;
3958
3959 if (FnDecl) {
3960 // We matched an overloaded operator. Build a call to that
3961 // operator.
3962
3963 // Convert the arguments.
3964 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3965 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003966 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003967 } else {
3968 // Convert the arguments.
3969 if (PerformCopyInitialization(Input,
3970 FnDecl->getParamDecl(0)->getType(),
3971 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003972 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003973 }
3974
3975 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003976 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003977 = FnDecl->getType()->getAsFunctionType()->getResultType();
3978 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003979
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003980 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003981 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3982 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003983 UsualUnaryConversions(FnExpr);
3984
Sebastian Redl8b769972009-01-19 00:08:26 +00003985 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003986 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003987 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003988 } else {
3989 // We matched a built-in operator. Convert the arguments, then
3990 // break out so that we will build the appropriate built-in
3991 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003992 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3993 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003994 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003995
3996 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003997 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003998 }
3999
4000 case OR_No_Viable_Function:
4001 // No viable function; fall through to handling this as a
4002 // built-in operator, which will produce an error message for us.
4003 break;
4004
4005 case OR_Ambiguous:
4006 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4007 << UnaryOperator::getOpcodeStr(Opc)
4008 << Input->getSourceRange();
4009 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004010 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004011 }
4012
4013 // Either we found no viable overloaded operator or we matched a
4014 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004015 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004016 }
4017
Chris Lattner4b009652007-07-25 00:24:17 +00004018 QualType resultType;
4019 switch (Opc) {
4020 default:
4021 assert(0 && "Unimplemented unary expr!");
4022 case UnaryOperator::PreInc:
4023 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004024 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4025 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004026 break;
4027 case UnaryOperator::AddrOf:
4028 resultType = CheckAddressOfOperand(Input, OpLoc);
4029 break;
4030 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004031 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004032 resultType = CheckIndirectionOperand(Input, OpLoc);
4033 break;
4034 case UnaryOperator::Plus:
4035 case UnaryOperator::Minus:
4036 UsualUnaryConversions(Input);
4037 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004038 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4039 break;
4040 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4041 resultType->isEnumeralType())
4042 break;
4043 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4044 Opc == UnaryOperator::Plus &&
4045 resultType->isPointerType())
4046 break;
4047
Sebastian Redl8b769972009-01-19 00:08:26 +00004048 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4049 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004050 case UnaryOperator::Not: // bitwise complement
4051 UsualUnaryConversions(Input);
4052 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004053 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4054 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4055 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004056 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004057 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004058 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004059 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4060 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004061 break;
4062 case UnaryOperator::LNot: // logical negation
4063 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4064 DefaultFunctionArrayConversion(Input);
4065 resultType = Input->getType();
4066 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004067 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4068 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004069 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004070 // In C++, it's bool. C++ 5.3.1p8
4071 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004072 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004073 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004074 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004075 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004076 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004077 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004078 resultType = Input->getType();
4079 break;
4080 }
4081 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004082 return ExprError();
4083 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004084 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004085}
4086
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004087/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4088Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004089 SourceLocation LabLoc,
4090 IdentifierInfo *LabelII) {
4091 // Look up the record for this label identifier.
4092 LabelStmt *&LabelDecl = LabelMap[LabelII];
4093
Daniel Dunbar879788d2008-08-04 16:51:22 +00004094 // If we haven't seen this label yet, create a forward reference. It
4095 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004096 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004097 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004098
4099 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004100 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4101 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004102}
4103
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004104Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004105 SourceLocation RPLoc) { // "({..})"
4106 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4107 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4108 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4109
Eli Friedmanbc941e12009-01-24 23:09:00 +00004110 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4111 if (isFileScope) {
4112 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4113 }
4114
Chris Lattner4b009652007-07-25 00:24:17 +00004115 // FIXME: there are a variety of strange constraints to enforce here, for
4116 // example, it is not possible to goto into a stmt expression apparently.
4117 // More semantic analysis is needed.
4118
4119 // FIXME: the last statement in the compount stmt has its value used. We
4120 // should not warn about it being unused.
4121
4122 // If there are sub stmts in the compound stmt, take the type of the last one
4123 // as the type of the stmtexpr.
4124 QualType Ty = Context.VoidTy;
4125
Chris Lattner200964f2008-07-26 19:51:01 +00004126 if (!Compound->body_empty()) {
4127 Stmt *LastStmt = Compound->body_back();
4128 // If LastStmt is a label, skip down through into the body.
4129 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4130 LastStmt = Label->getSubStmt();
4131
4132 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004133 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004134 }
Chris Lattner4b009652007-07-25 00:24:17 +00004135
Steve Naroff774e4152009-01-21 00:14:39 +00004136 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004137}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004138
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004139Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4140 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004141 SourceLocation TypeLoc,
4142 TypeTy *argty,
4143 OffsetOfComponent *CompPtr,
4144 unsigned NumComponents,
4145 SourceLocation RPLoc) {
4146 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4147 assert(!ArgTy.isNull() && "Missing type argument!");
4148
4149 // We must have at least one component that refers to the type, and the first
4150 // one is known to be a field designator. Verify that the ArgTy represents
4151 // a struct/union/class.
4152 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004153 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004154
4155 // Otherwise, create a compound literal expression as the base, and
4156 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004157 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004158 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004159 IList->setType(ArgTy);
4160 Expr *Res =
4161 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4162
Chris Lattnerb37522e2007-08-31 21:49:13 +00004163 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4164 // GCC extension, diagnose them.
4165 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004166 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4167 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004168
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004169 for (unsigned i = 0; i != NumComponents; ++i) {
4170 const OffsetOfComponent &OC = CompPtr[i];
4171 if (OC.isBrackets) {
4172 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004173 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004174 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004175 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004176 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004177 }
4178
Chris Lattner2af6a802007-08-30 17:59:59 +00004179 // FIXME: C++: Verify that operator[] isn't overloaded.
4180
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004181 // C99 6.5.2.1p1
4182 Expr *Idx = static_cast<Expr*>(OC.U.E);
4183 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004184 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4185 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004186
Steve Naroff774e4152009-01-21 00:14:39 +00004187 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4188 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004189 continue;
4190 }
4191
4192 const RecordType *RC = Res->getType()->getAsRecordType();
4193 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004194 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004195 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004196 }
4197
4198 // Get the decl corresponding to this.
4199 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004200 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004201 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4202 LookupMemberName)
4203 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004204 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004205 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4206 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004207
4208 // FIXME: C++: Verify that MemberDecl isn't a static field.
4209 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004210 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4211 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004212 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4213 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004214 }
4215
Steve Naroff774e4152009-01-21 00:14:39 +00004216 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4217 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004218}
4219
4220
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004221Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004222 TypeTy *arg1, TypeTy *arg2,
4223 SourceLocation RPLoc) {
4224 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4225 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4226
4227 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4228
Steve Naroff774e4152009-01-21 00:14:39 +00004229 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4230 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004231}
4232
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004233Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004234 ExprTy *expr1, ExprTy *expr2,
4235 SourceLocation RPLoc) {
4236 Expr *CondExpr = static_cast<Expr*>(cond);
4237 Expr *LHSExpr = static_cast<Expr*>(expr1);
4238 Expr *RHSExpr = static_cast<Expr*>(expr2);
4239
4240 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4241
4242 // The conditional expression is required to be a constant expression.
4243 llvm::APSInt condEval(32);
4244 SourceLocation ExpLoc;
4245 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004246 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4247 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004248
4249 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4250 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4251 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004252 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4253 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004254}
4255
Steve Naroff52a81c02008-09-03 18:15:37 +00004256//===----------------------------------------------------------------------===//
4257// Clang Extensions.
4258//===----------------------------------------------------------------------===//
4259
4260/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004261void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004262 // Analyze block parameters.
4263 BlockSemaInfo *BSI = new BlockSemaInfo();
4264
4265 // Add BSI to CurBlock.
4266 BSI->PrevBlockInfo = CurBlock;
4267 CurBlock = BSI;
4268
4269 BSI->ReturnType = 0;
4270 BSI->TheScope = BlockScope;
4271
Steve Naroff52059382008-10-10 01:28:17 +00004272 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004273 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004274}
4275
Mike Stumpc1fddff2009-02-04 22:31:32 +00004276void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4277 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4278
4279 if (ParamInfo.getNumTypeObjects() == 0
4280 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4281 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4282
4283 // The type is entirely optional as well, if none, use DependentTy.
4284 if (T.isNull())
4285 T = Context.DependentTy;
4286
4287 // The parameter list is optional, if there was none, assume ().
4288 if (!T->isFunctionType())
4289 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4290
4291 CurBlock->hasPrototype = true;
4292 CurBlock->isVariadic = false;
4293 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4294 .getTypePtr();
4295
4296 if (!RetTy->isDependentType())
4297 CurBlock->ReturnType = RetTy;
4298 return;
4299 }
4300
Steve Naroff52a81c02008-09-03 18:15:37 +00004301 // Analyze arguments to block.
4302 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4303 "Not a function declarator!");
4304 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004305
Steve Naroff52059382008-10-10 01:28:17 +00004306 CurBlock->hasPrototype = FTI.hasPrototype;
4307 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004308
4309 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4310 // no arguments, not a function that takes a single void argument.
4311 if (FTI.hasPrototype &&
4312 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4313 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4314 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4315 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004316 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004317 } else if (FTI.hasPrototype) {
4318 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004319 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4320 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004321 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4322
4323 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4324 .getTypePtr();
4325
4326 if (!RetTy->isDependentType())
4327 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004328 }
Steve Naroff52059382008-10-10 01:28:17 +00004329 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4330
4331 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4332 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4333 // If this has an identifier, add it to the scope stack.
4334 if ((*AI)->getIdentifier())
4335 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004336}
4337
4338/// ActOnBlockError - If there is an error parsing a block, this callback
4339/// is invoked to pop the information about the block from the action impl.
4340void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4341 // Ensure that CurBlock is deleted.
4342 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4343
4344 // Pop off CurBlock, handle nested blocks.
4345 CurBlock = CurBlock->PrevBlockInfo;
4346
4347 // FIXME: Delete the ParmVarDecl objects as well???
4348
4349}
4350
4351/// ActOnBlockStmtExpr - This is called when the body of a block statement
4352/// literal was successfully completed. ^(int x){...}
4353Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4354 Scope *CurScope) {
4355 // Ensure that CurBlock is deleted.
4356 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004357 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004358
Steve Naroff52059382008-10-10 01:28:17 +00004359 PopDeclContext();
4360
Steve Naroff52a81c02008-09-03 18:15:37 +00004361 // Pop off CurBlock, handle nested blocks.
4362 CurBlock = CurBlock->PrevBlockInfo;
4363
4364 QualType RetTy = Context.VoidTy;
4365 if (BSI->ReturnType)
4366 RetTy = QualType(BSI->ReturnType, 0);
4367
4368 llvm::SmallVector<QualType, 8> ArgTypes;
4369 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4370 ArgTypes.push_back(BSI->Params[i]->getType());
4371
4372 QualType BlockTy;
4373 if (!BSI->hasPrototype)
4374 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4375 else
4376 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004377 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004378
4379 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004380
Steve Naroff95029d92008-10-08 18:44:00 +00004381 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004382 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004383}
4384
Nate Begemanbd881ef2008-01-30 20:50:20 +00004385/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004386/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004387/// The number of arguments has already been validated to match the number of
4388/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004389static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4390 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004391 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004392 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004393 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4394 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004395
4396 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004397 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004398 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004399 return true;
4400}
4401
4402Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4403 SourceLocation *CommaLocs,
4404 SourceLocation BuiltinLoc,
4405 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004406 // __builtin_overload requires at least 2 arguments
4407 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004408 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4409 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004410
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004411 // The first argument is required to be a constant expression. It tells us
4412 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004413 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004414 Expr *NParamsExpr = Args[0];
4415 llvm::APSInt constEval(32);
4416 SourceLocation ExpLoc;
4417 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004418 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4419 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004420
4421 // Verify that the number of parameters is > 0
4422 unsigned NumParams = constEval.getZExtValue();
4423 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004424 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4425 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004426 // Verify that we have at least 1 + NumParams arguments to the builtin.
4427 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004428 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4429 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004430
4431 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004432 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004433 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004434 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4435 // UsualUnaryConversions will convert the function DeclRefExpr into a
4436 // pointer to function.
4437 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004438 const FunctionTypeProto *FnType = 0;
4439 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4440 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004441
4442 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4443 // parameters, and the number of parameters must match the value passed to
4444 // the builtin.
4445 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004446 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4447 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004448
4449 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004450 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004451 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004452 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004453 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004454 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4455 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004456 // Remember our match, and continue processing the remaining arguments
4457 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004458 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004459 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004460 BuiltinLoc, RParenLoc);
4461 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004462 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004463 // Return the newly created OverloadExpr node, if we succeded in matching
4464 // exactly one of the candidate functions.
4465 if (OE)
4466 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004467
4468 // If we didn't find a matching function Expr in the __builtin_overload list
4469 // the return an error.
4470 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004471 for (unsigned i = 0; i != NumParams; ++i) {
4472 if (i != 0) typeNames += ", ";
4473 typeNames += Args[i+1]->getType().getAsString();
4474 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004475
Chris Lattner77d52da2008-11-20 06:06:08 +00004476 return Diag(BuiltinLoc, diag::err_overload_no_match)
4477 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004478}
4479
Anders Carlsson36760332007-10-15 20:28:48 +00004480Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4481 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004482 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004483 Expr *E = static_cast<Expr*>(expr);
4484 QualType T = QualType::getFromOpaquePtr(type);
4485
4486 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004487
4488 // Get the va_list type
4489 QualType VaListType = Context.getBuiltinVaListType();
4490 // Deal with implicit array decay; for example, on x86-64,
4491 // va_list is an array, but it's supposed to decay to
4492 // a pointer for va_arg.
4493 if (VaListType->isArrayType())
4494 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004495 // Make sure the input expression also decays appropriately.
4496 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004497
4498 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004499 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004500 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004501 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004502
4503 // FIXME: Warn if a non-POD type is passed in.
4504
Steve Naroff774e4152009-01-21 00:14:39 +00004505 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004506}
4507
Douglas Gregorad4b3792008-11-29 04:51:27 +00004508Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4509 // The type of __null will be int or long, depending on the size of
4510 // pointers on the target.
4511 QualType Ty;
4512 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4513 Ty = Context.IntTy;
4514 else
4515 Ty = Context.LongTy;
4516
Steve Naroff774e4152009-01-21 00:14:39 +00004517 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004518}
4519
Chris Lattner005ed752008-01-04 18:04:52 +00004520bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4521 SourceLocation Loc,
4522 QualType DstType, QualType SrcType,
4523 Expr *SrcExpr, const char *Flavor) {
4524 // Decode the result (notice that AST's are still created for extensions).
4525 bool isInvalid = false;
4526 unsigned DiagKind;
4527 switch (ConvTy) {
4528 default: assert(0 && "Unknown conversion type");
4529 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004530 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004531 DiagKind = diag::ext_typecheck_convert_pointer_int;
4532 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004533 case IntToPointer:
4534 DiagKind = diag::ext_typecheck_convert_int_pointer;
4535 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004536 case IncompatiblePointer:
4537 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4538 break;
4539 case FunctionVoidPointer:
4540 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4541 break;
4542 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004543 // If the qualifiers lost were because we were applying the
4544 // (deprecated) C++ conversion from a string literal to a char*
4545 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4546 // Ideally, this check would be performed in
4547 // CheckPointerTypesForAssignment. However, that would require a
4548 // bit of refactoring (so that the second argument is an
4549 // expression, rather than a type), which should be done as part
4550 // of a larger effort to fix CheckPointerTypesForAssignment for
4551 // C++ semantics.
4552 if (getLangOptions().CPlusPlus &&
4553 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4554 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004555 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4556 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004557 case IntToBlockPointer:
4558 DiagKind = diag::err_int_to_block_pointer;
4559 break;
4560 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004561 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004562 break;
Steve Naroff19608432008-10-14 22:18:38 +00004563 case IncompatibleObjCQualifiedId:
4564 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4565 // it can give a more specific diagnostic.
4566 DiagKind = diag::warn_incompatible_qualified_id;
4567 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004568 case IncompatibleVectors:
4569 DiagKind = diag::warn_incompatible_vectors;
4570 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004571 case Incompatible:
4572 DiagKind = diag::err_typecheck_convert_incompatible;
4573 isInvalid = true;
4574 break;
4575 }
4576
Chris Lattner271d4c22008-11-24 05:29:24 +00004577 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4578 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004579 return isInvalid;
4580}
Anders Carlssond5201b92008-11-30 19:50:32 +00004581
4582bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4583{
4584 Expr::EvalResult EvalResult;
4585
4586 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4587 EvalResult.HasSideEffects) {
4588 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4589
4590 if (EvalResult.Diag) {
4591 // We only show the note if it's not the usual "invalid subexpression"
4592 // or if it's actually in a subexpression.
4593 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4594 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4595 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4596 }
4597
4598 return true;
4599 }
4600
4601 if (EvalResult.Diag) {
4602 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4603 E->getSourceRange();
4604
4605 // Print the reason it's not a constant.
4606 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4607 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4608 }
4609
4610 if (Result)
4611 *Result = EvalResult.Val.getInt();
4612 return false;
4613}