blob: 48f338e475dfeb84329a97dd985027a54fe83d8c [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.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002035 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2036 Args, NumArgs,
2037 Context.BoolTy,
2038 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002039
Douglas Gregor7f49ea22009-02-18 06:34:51 +00002040 // Check for a call to a (FIXME: deleted) or unavailable function.
2041 if (FDecl && FDecl->getAttr<UnavailableAttr>()) {
2042 Diag(Fn->getSourceRange().getBegin(), diag::err_call_deleted_function)
2043 << FDecl->getAttr<UnavailableAttr>() << FDecl->getDeclName()
2044 << Fn->getSourceRange();
2045 Diag(FDecl->getLocation(), diag::note_deleted_function_here)
2046 << FDecl->getAttr<UnavailableAttr>();
2047 return ExprError();
2048 }
2049
Steve Naroffd6163f32008-09-05 22:11:13 +00002050 const FunctionType *FuncT;
2051 if (!Fn->getType()->isBlockPointerType()) {
2052 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2053 // have type pointer to function".
2054 const PointerType *PT = Fn->getType()->getAsPointerType();
2055 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002056 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2057 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002058 FuncT = PT->getPointeeType()->getAsFunctionType();
2059 } else { // This is a block call.
2060 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2061 getAsFunctionType();
2062 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002063 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002064 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2065 << Fn->getType() << Fn->getSourceRange());
2066
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002067 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002068 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002069
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002070 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002071 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2072 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002073 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002074 } else {
2075 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002076
Steve Naroffdb65e052007-08-28 23:30:39 +00002077 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002078 for (unsigned i = 0; i != NumArgs; i++) {
2079 Expr *Arg = Args[i];
2080 DefaultArgumentPromotion(Arg);
2081 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002082 }
Chris Lattner4b009652007-07-25 00:24:17 +00002083 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002084
Douglas Gregor3257fb52008-12-22 05:46:06 +00002085 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2086 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002087 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2088 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002089
Chris Lattner2e64c072007-08-10 20:18:51 +00002090 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002091 if (FDecl)
2092 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002093
Sebastian Redl8b769972009-01-19 00:08:26 +00002094 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002095}
2096
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002097Action::OwningExprResult
2098Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2099 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002100 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002101 QualType literalType = QualType::getFromOpaquePtr(Ty);
2102 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002103 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002104 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002105
Eli Friedman8c2173d2008-05-20 05:22:08 +00002106 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002107 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002108 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2109 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002110 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2111 diag::err_typecheck_decl_incomplete_type,
2112 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002113 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002114
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002115 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002116 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002117 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002118
Chris Lattnere5cb5862008-12-04 23:50:19 +00002119 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002120 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002121 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002122 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002123 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002124 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002125 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2126 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002127}
2128
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002129Action::OwningExprResult
2130Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2131 InitListDesignations &Designators,
2132 SourceLocation RBraceLoc) {
2133 unsigned NumInit = initlist.size();
2134 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002135
Steve Naroff0acc9c92007-09-15 18:49:24 +00002136 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002137 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002138
Steve Naroff774e4152009-01-21 00:14:39 +00002139 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002140 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002141 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002142 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002143}
2144
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002145/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002146bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002147 UsualUnaryConversions(castExpr);
2148
2149 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2150 // type needs to be scalar.
2151 if (castType->isVoidType()) {
2152 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002153 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2154 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002155 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002156 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2157 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2158 (castType->isStructureType() || castType->isUnionType())) {
2159 // GCC struct/union extension: allow cast to self.
2160 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2161 << castType << castExpr->getSourceRange();
2162 } else if (castType->isUnionType()) {
2163 // GCC cast to union extension
2164 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2165 RecordDecl::field_iterator Field, FieldEnd;
2166 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2167 Field != FieldEnd; ++Field) {
2168 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2169 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2170 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2171 << castExpr->getSourceRange();
2172 break;
2173 }
2174 }
2175 if (Field == FieldEnd)
2176 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2177 << castExpr->getType() << castExpr->getSourceRange();
2178 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002179 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002180 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002181 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002182 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002183 } else if (!castExpr->getType()->isScalarType() &&
2184 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002185 return Diag(castExpr->getLocStart(),
2186 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002187 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002188 } else if (castExpr->getType()->isVectorType()) {
2189 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2190 return true;
2191 } else if (castType->isVectorType()) {
2192 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2193 return true;
2194 }
2195 return false;
2196}
2197
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002198bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002199 assert(VectorTy->isVectorType() && "Not a vector type!");
2200
2201 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002202 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002203 return Diag(R.getBegin(),
2204 Ty->isVectorType() ?
2205 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002206 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002207 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002208 } else
2209 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002210 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002211 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002212
2213 return false;
2214}
2215
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002216Action::OwningExprResult
2217Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2218 SourceLocation RParenLoc, ExprArg Op) {
2219 assert((Ty != 0) && (Op.get() != 0) &&
2220 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002221
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002222 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002223 QualType castType = QualType::getFromOpaquePtr(Ty);
2224
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002225 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002226 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002227 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002228 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002229}
2230
Chris Lattner98a425c2007-11-26 01:40:58 +00002231/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2232/// In that case, lex = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002233/// C99 6.5.15
2234QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2235 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002236 UsualUnaryConversions(Cond);
2237 UsualUnaryConversions(LHS);
2238 UsualUnaryConversions(RHS);
2239 QualType CondTy = Cond->getType();
2240 QualType LHSTy = LHS->getType();
2241 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002242
2243 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002244 if (!Cond->isTypeDependent()) {
2245 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2246 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2247 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002248 return QualType();
2249 }
Chris Lattner4b009652007-07-25 00:24:17 +00002250 }
Chris Lattner992ae932008-01-06 22:42:25 +00002251
2252 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002253 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002254 return Context.DependentTy;
2255
Chris Lattner992ae932008-01-06 22:42:25 +00002256 // If both operands have arithmetic type, do the usual arithmetic conversions
2257 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002258 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2259 UsualArithmeticConversions(LHS, RHS);
2260 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002261 }
Chris Lattner992ae932008-01-06 22:42:25 +00002262
2263 // If both operands are the same structure or union type, the result is that
2264 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002265 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2266 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002267 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002268 // "If both the operands have structure or union type, the result has
2269 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002270 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002271 }
Chris Lattner992ae932008-01-06 22:42:25 +00002272
2273 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002274 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002275 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2276 if (!LHSTy->isVoidType())
2277 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2278 << RHS->getSourceRange();
2279 if (!RHSTy->isVoidType())
2280 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2281 << LHS->getSourceRange();
2282 ImpCastExprToType(LHS, Context.VoidTy);
2283 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002284 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002285 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002286 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2287 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002288 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2289 Context.isObjCObjectPointerType(LHSTy)) &&
2290 RHS->isNullPointerConstant(Context)) {
2291 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2292 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002293 }
Chris Lattnere2897262009-02-18 04:28:32 +00002294 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2295 Context.isObjCObjectPointerType(RHSTy)) &&
2296 LHS->isNullPointerConstant(Context)) {
2297 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2298 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002299 }
Chris Lattner9c039b52009-02-18 04:38:20 +00002300
Chris Lattner0ac51632008-01-06 22:50:31 +00002301 // Handle the case where both operands are pointers before we handle null
2302 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002303 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2304 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002305 // get the "pointed to" types
2306 QualType lhptee = LHSPT->getPointeeType();
2307 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002308
Chris Lattner71225142007-07-31 21:27:01 +00002309 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2310 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002311 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002312 // Figure out necessary qualifiers (C99 6.5.15p6)
2313 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002314 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002315 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2316 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002317 return destType;
2318 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002319 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002320 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002321 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002322 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2323 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002324 return destType;
2325 }
Chris Lattner4b009652007-07-25 00:24:17 +00002326
Chris Lattner9c039b52009-02-18 04:38:20 +00002327 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2328 // Two identical pointers types are always compatible.
2329 return LHSTy;
2330 }
2331
Chris Lattnere2897262009-02-18 04:28:32 +00002332 QualType compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002333
2334 // If either type is an Objective-C object type then check
2335 // compatibility according to Objective-C.
Chris Lattnere2897262009-02-18 04:28:32 +00002336 if (Context.isObjCObjectPointerType(LHSTy) ||
2337 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002338 // If both operands are interfaces and either operand can be
2339 // assigned to the other, use that type as the composite
2340 // type. This allows
2341 // xxx ? (A*) a : (B*) b
2342 // where B is a subclass of A.
2343 //
2344 // Additionally, as for assignment, if either type is 'id'
2345 // allow silent coercion. Finally, if the types are
2346 // incompatible then make sure to use 'id' as the composite
2347 // type so the result is acceptable for sending messages to.
2348
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002349 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2350 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002351 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2352 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2353 if (LHSIface && RHSIface &&
2354 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002355 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002356 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002357 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002358 compositeType = RHSTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002359 } else if (Context.isObjCIdStructType(lhptee) ||
2360 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002361 compositeType = Context.getObjCIdType();
2362 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002363 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2364 << LHSTy << RHSTy
2365 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002366 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002367 ImpCastExprToType(LHS, incompatTy);
2368 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002369 return incompatTy;
2370 }
2371 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2372 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002373 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2374 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002375 // In this situation, we assume void* type. No especially good
2376 // reason, but this is what gcc does, and we do have to pick
2377 // to get a consistent AST.
2378 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002379 ImpCastExprToType(LHS, incompatTy);
2380 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002381 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002382 }
2383 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002384 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2385 // differently qualified versions of compatible types, the result type is
2386 // a pointer to an appropriately qualified version of the *composite*
2387 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002388 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002389 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002390 ImpCastExprToType(LHS, compositeType);
2391 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002392 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002393 }
Chris Lattner4b009652007-07-25 00:24:17 +00002394 }
Chris Lattner9c039b52009-02-18 04:38:20 +00002395
2396 // Selection between block pointer types is ok as long as they are the same.
2397 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2398 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2399 return LHSTy;
2400
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002401 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2402 // evaluates to "struct objc_object *" (and is handled above when comparing
2403 // id with statically typed objects).
Chris Lattnere2897262009-02-18 04:28:32 +00002404 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002405 // GCC allows qualified id and any Objective-C type to devolve to
2406 // id. Currently localizing to here until clear this should be
2407 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002408 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
2409 (LHSTy->isObjCQualifiedIdType() &&
2410 Context.isObjCObjectPointerType(RHSTy)) ||
2411 (RHSTy->isObjCQualifiedIdType() &&
2412 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002413 // FIXME: This is not the correct composite type. This only
2414 // happens to work because id can more or less be used anywhere,
2415 // however this may change the type of method sends.
2416 // FIXME: gcc adds some type-checking of the arguments and emits
2417 // (confusing) incompatible comparison warnings in some
2418 // cases. Investigate.
2419 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002420 ImpCastExprToType(LHS, compositeType);
2421 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002422 return compositeType;
2423 }
2424 }
2425
Chris Lattner992ae932008-01-06 22:42:25 +00002426 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002427 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2428 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002429 return QualType();
2430}
2431
Steve Naroff87d58b42007-09-16 03:34:24 +00002432/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002433/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002434Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2435 SourceLocation ColonLoc,
2436 ExprArg Cond, ExprArg LHS,
2437 ExprArg RHS) {
2438 Expr *CondExpr = (Expr *) Cond.get();
2439 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002440
2441 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2442 // was the condition.
2443 bool isLHSNull = LHSExpr == 0;
2444 if (isLHSNull)
2445 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002446
2447 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002448 RHSExpr, QuestionLoc);
2449 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002450 return ExprError();
2451
2452 Cond.release();
2453 LHS.release();
2454 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002455 return Owned(new (Context) ConditionalOperator(CondExpr,
2456 isLHSNull ? 0 : LHSExpr,
2457 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002458}
2459
Chris Lattner4b009652007-07-25 00:24:17 +00002460
2461// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2462// being closely modeled after the C99 spec:-). The odd characteristic of this
2463// routine is it effectively iqnores the qualifiers on the top level pointee.
2464// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2465// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002466Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002467Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2468 QualType lhptee, rhptee;
2469
2470 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002471 lhptee = lhsType->getAsPointerType()->getPointeeType();
2472 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002473
2474 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002475 lhptee = Context.getCanonicalType(lhptee);
2476 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002477
Chris Lattner005ed752008-01-04 18:04:52 +00002478 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002479
2480 // C99 6.5.16.1p1: This following citation is common to constraints
2481 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2482 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002483 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002484 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002485 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002486
2487 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2488 // incomplete type and the other is a pointer to a qualified or unqualified
2489 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002490 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002491 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002492 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002493
2494 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002495 assert(rhptee->isFunctionType());
2496 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002497 }
2498
2499 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002500 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002501 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002502
2503 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002504 assert(lhptee->isFunctionType());
2505 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002506 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002507
2508 // Check for ObjC interfaces
2509 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2510 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2511 if (LHSIface && RHSIface &&
2512 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2513 return ConvTy;
2514
2515 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002516 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002517 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002518 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002519 return ConvTy;
2520
Chris Lattner4b009652007-07-25 00:24:17 +00002521 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2522 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002523 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2524 rhptee.getUnqualifiedType()))
2525 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002526 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002527}
2528
Steve Naroff3454b6c2008-09-04 15:10:53 +00002529/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2530/// block pointer types are compatible or whether a block and normal pointer
2531/// are compatible. It is more restrict than comparing two function pointer
2532// types.
2533Sema::AssignConvertType
2534Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2535 QualType rhsType) {
2536 QualType lhptee, rhptee;
2537
2538 // get the "pointed to" type (ignoring qualifiers at the top level)
2539 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2540 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2541
2542 // make sure we operate on the canonical type
2543 lhptee = Context.getCanonicalType(lhptee);
2544 rhptee = Context.getCanonicalType(rhptee);
2545
2546 AssignConvertType ConvTy = Compatible;
2547
2548 // For blocks we enforce that qualifiers are identical.
2549 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2550 ConvTy = CompatiblePointerDiscardsQualifiers;
2551
2552 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2553 return IncompatibleBlockPointer;
2554 return ConvTy;
2555}
2556
Chris Lattner4b009652007-07-25 00:24:17 +00002557/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2558/// has code to accommodate several GCC extensions when type checking
2559/// pointers. Here are some objectionable examples that GCC considers warnings:
2560///
2561/// int a, *pint;
2562/// short *pshort;
2563/// struct foo *pfoo;
2564///
2565/// pint = pshort; // warning: assignment from incompatible pointer type
2566/// a = pint; // warning: assignment makes integer from pointer without a cast
2567/// pint = a; // warning: assignment makes pointer from integer without a cast
2568/// pint = pfoo; // warning: assignment from incompatible pointer type
2569///
2570/// As a result, the code for dealing with pointers is more complex than the
2571/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002572///
Chris Lattner005ed752008-01-04 18:04:52 +00002573Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002574Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002575 // Get canonical types. We're not formatting these types, just comparing
2576 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002577 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2578 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002579
2580 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002581 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002582
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002583 // If the left-hand side is a reference type, then we are in a
2584 // (rare!) case where we've allowed the use of references in C,
2585 // e.g., as a parameter type in a built-in function. In this case,
2586 // just make sure that the type referenced is compatible with the
2587 // right-hand side type. The caller is responsible for adjusting
2588 // lhsType so that the resulting expression does not have reference
2589 // type.
2590 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2591 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002592 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002593 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002594 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002595
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002596 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2597 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002598 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002599 // Relax integer conversions like we do for pointers below.
2600 if (rhsType->isIntegerType())
2601 return IntToPointer;
2602 if (lhsType->isIntegerType())
2603 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002604 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002605 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002606
Nate Begemanc5f0f652008-07-14 18:02:46 +00002607 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002608 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002609 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2610 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002611 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002612
Nate Begemanc5f0f652008-07-14 18:02:46 +00002613 // If we are allowing lax vector conversions, and LHS and RHS are both
2614 // vectors, the total size only needs to be the same. This is a bitcast;
2615 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002616 if (getLangOptions().LaxVectorConversions &&
2617 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002618 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002619 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002620 }
2621 return Incompatible;
2622 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002623
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002624 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002625 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002626
Chris Lattner390564e2008-04-07 06:49:41 +00002627 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002628 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002629 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002630
Chris Lattner390564e2008-04-07 06:49:41 +00002631 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002632 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002633
Steve Naroffa982c712008-09-29 18:10:17 +00002634 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002635 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002636 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002637
2638 // Treat block pointers as objects.
2639 if (getLangOptions().ObjC1 &&
2640 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2641 return Compatible;
2642 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002643 return Incompatible;
2644 }
2645
2646 if (isa<BlockPointerType>(lhsType)) {
2647 if (rhsType->isIntegerType())
2648 return IntToPointer;
2649
Steve Naroffa982c712008-09-29 18:10:17 +00002650 // Treat block pointers as objects.
2651 if (getLangOptions().ObjC1 &&
2652 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2653 return Compatible;
2654
Steve Naroff3454b6c2008-09-04 15:10:53 +00002655 if (rhsType->isBlockPointerType())
2656 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2657
2658 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2659 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002660 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002661 }
Chris Lattner1853da22008-01-04 23:18:45 +00002662 return Incompatible;
2663 }
2664
Chris Lattner390564e2008-04-07 06:49:41 +00002665 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002666 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002667 if (lhsType == Context.BoolTy)
2668 return Compatible;
2669
2670 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002671 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002672
Chris Lattner390564e2008-04-07 06:49:41 +00002673 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002674 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002675
2676 if (isa<BlockPointerType>(lhsType) &&
2677 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002678 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002679 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002680 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002681
Chris Lattner1853da22008-01-04 23:18:45 +00002682 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002683 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002684 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002685 }
2686 return Incompatible;
2687}
2688
Chris Lattner005ed752008-01-04 18:04:52 +00002689Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002690Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002691 if (getLangOptions().CPlusPlus) {
2692 if (!lhsType->isRecordType()) {
2693 // C++ 5.17p3: If the left operand is not of class type, the
2694 // expression is implicitly converted (C++ 4) to the
2695 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002696 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2697 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002698 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002699 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002700 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002701 }
2702
2703 // FIXME: Currently, we fall through and treat C++ classes like C
2704 // structures.
2705 }
2706
Steve Naroffcdee22d2007-11-27 17:58:44 +00002707 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2708 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002709 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2710 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002711 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002712 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002713 return Compatible;
2714 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002715
2716 // We don't allow conversion of non-null-pointer constants to integers.
2717 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2718 return IntToBlockPointer;
2719
Chris Lattner5f505bf2007-10-16 02:55:40 +00002720 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002721 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002722 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002723 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002724 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002725 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002726 if (!lhsType->isReferenceType())
2727 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002728
Chris Lattner005ed752008-01-04 18:04:52 +00002729 Sema::AssignConvertType result =
2730 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002731
2732 // C99 6.5.16.1p2: The value of the right operand is converted to the
2733 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002734 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2735 // so that we can use references in built-in functions even in C.
2736 // The getNonReferenceType() call makes sure that the resulting expression
2737 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002738 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002739 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002740 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002741}
2742
Chris Lattner005ed752008-01-04 18:04:52 +00002743Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002744Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2745 return CheckAssignmentConstraints(lhsType, rhsType);
2746}
2747
Chris Lattner1eafdea2008-11-18 01:30:42 +00002748QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002749 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002750 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002751 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002752 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002753}
2754
Chris Lattner1eafdea2008-11-18 01:30:42 +00002755inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002756 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002757 // For conversion purposes, we ignore any qualifiers.
2758 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002759 QualType lhsType =
2760 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2761 QualType rhsType =
2762 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002763
Nate Begemanc5f0f652008-07-14 18:02:46 +00002764 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002765 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002766 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002767
Nate Begemanc5f0f652008-07-14 18:02:46 +00002768 // Handle the case of a vector & extvector type of the same size and element
2769 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002770 if (getLangOptions().LaxVectorConversions) {
2771 // FIXME: Should we warn here?
2772 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002773 if (const VectorType *RV = rhsType->getAsVectorType())
2774 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002775 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002776 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002777 }
2778 }
2779 }
2780
Nate Begemanc5f0f652008-07-14 18:02:46 +00002781 // If the lhs is an extended vector and the rhs is a scalar of the same type
2782 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002783 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002784 QualType eltType = V->getElementType();
2785
2786 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2787 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2788 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002789 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002790 return lhsType;
2791 }
2792 }
2793
Nate Begemanc5f0f652008-07-14 18:02:46 +00002794 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002795 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002796 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002797 QualType eltType = V->getElementType();
2798
2799 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2800 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2801 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002802 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002803 return rhsType;
2804 }
2805 }
2806
Chris Lattner4b009652007-07-25 00:24:17 +00002807 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002808 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002809 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002810 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002811 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002812}
2813
Chris Lattner4b009652007-07-25 00:24:17 +00002814inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002815 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002816{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002817 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002818 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002819
Steve Naroff8f708362007-08-24 19:07:16 +00002820 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002821
Chris Lattner4b009652007-07-25 00:24:17 +00002822 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002823 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002824 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002825}
2826
2827inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002828 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002829{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002830 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2831 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2832 return CheckVectorOperands(Loc, lex, rex);
2833 return InvalidOperands(Loc, lex, rex);
2834 }
Chris Lattner4b009652007-07-25 00:24:17 +00002835
Steve Naroff8f708362007-08-24 19:07:16 +00002836 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002837
Chris Lattner4b009652007-07-25 00:24:17 +00002838 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002839 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002840 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002841}
2842
2843inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002844 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002845{
2846 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002847 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002848
Steve Naroff8f708362007-08-24 19:07:16 +00002849 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002850
Chris Lattner4b009652007-07-25 00:24:17 +00002851 // handle the common case first (both operands are arithmetic).
2852 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002853 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002854
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002855 // Put any potential pointer into PExp
2856 Expr* PExp = lex, *IExp = rex;
2857 if (IExp->getType()->isPointerType())
2858 std::swap(PExp, IExp);
2859
2860 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2861 if (IExp->getType()->isIntegerType()) {
2862 // Check for arithmetic on pointers to incomplete types
2863 if (!PTy->getPointeeType()->isObjectType()) {
2864 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002865 if (getLangOptions().CPlusPlus) {
2866 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2867 << lex->getSourceRange() << rex->getSourceRange();
2868 return QualType();
2869 }
2870
2871 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002872 Diag(Loc, diag::ext_gnu_void_ptr)
2873 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002874 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002875 if (getLangOptions().CPlusPlus) {
2876 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2877 << lex->getType() << lex->getSourceRange();
2878 return QualType();
2879 }
2880
2881 // GNU extension: arithmetic on pointer to function
2882 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002883 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002884 } else {
2885 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2886 diag::err_typecheck_arithmetic_incomplete_type,
2887 lex->getSourceRange(), SourceRange(),
2888 lex->getType());
2889 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002890 }
2891 }
2892 return PExp->getType();
2893 }
2894 }
2895
Chris Lattner1eafdea2008-11-18 01:30:42 +00002896 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002897}
2898
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002899// C99 6.5.6
2900QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002901 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002902 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002903 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002904
Steve Naroff8f708362007-08-24 19:07:16 +00002905 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002906
Chris Lattnerf6da2912007-12-09 21:53:25 +00002907 // Enforce type constraints: C99 6.5.6p3.
2908
2909 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002910 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002911 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002912
2913 // Either ptr - int or ptr - ptr.
2914 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002915 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002916
Chris Lattnerf6da2912007-12-09 21:53:25 +00002917 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002918 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002919 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002920 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002921 Diag(Loc, diag::ext_gnu_void_ptr)
2922 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002923 } else if (lpointee->isFunctionType()) {
2924 if (getLangOptions().CPlusPlus) {
2925 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2926 << lex->getType() << lex->getSourceRange();
2927 return QualType();
2928 }
2929
2930 // GNU extension: arithmetic on pointer to function
2931 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2932 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002933 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002934 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002935 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002936 return QualType();
2937 }
2938 }
2939
2940 // The result type of a pointer-int computation is the pointer type.
2941 if (rex->getType()->isIntegerType())
2942 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002943
Chris Lattnerf6da2912007-12-09 21:53:25 +00002944 // Handle pointer-pointer subtractions.
2945 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002946 QualType rpointee = RHSPTy->getPointeeType();
2947
Chris Lattnerf6da2912007-12-09 21:53:25 +00002948 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002949 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002950 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002951 if (rpointee->isVoidType()) {
2952 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002953 Diag(Loc, diag::ext_gnu_void_ptr)
2954 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002955 } else if (rpointee->isFunctionType()) {
2956 if (getLangOptions().CPlusPlus) {
2957 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2958 << rex->getType() << rex->getSourceRange();
2959 return QualType();
2960 }
2961
2962 // GNU extension: arithmetic on pointer to function
2963 if (!lpointee->isFunctionType())
2964 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2965 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002966 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002967 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002968 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002969 return QualType();
2970 }
2971 }
2972
2973 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002974 if (!Context.typesAreCompatible(
2975 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2976 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002977 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002978 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002979 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002980 return QualType();
2981 }
2982
2983 return Context.getPointerDiffType();
2984 }
2985 }
2986
Chris Lattner1eafdea2008-11-18 01:30:42 +00002987 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002988}
2989
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002990// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002991QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002992 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002993 // C99 6.5.7p2: Each of the operands shall have integer type.
2994 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002995 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002996
Chris Lattner2c8bff72007-12-12 05:47:28 +00002997 // Shifts don't perform usual arithmetic conversions, they just do integer
2998 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002999 if (!isCompAssign)
3000 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003001 UsualUnaryConversions(rex);
3002
3003 // "The type of the result is that of the promoted left operand."
3004 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003005}
3006
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003007// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003008QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003009 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003010 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003011 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003012
Chris Lattner254f3bc2007-08-26 01:18:55 +00003013 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003014 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3015 UsualArithmeticConversions(lex, rex);
3016 else {
3017 UsualUnaryConversions(lex);
3018 UsualUnaryConversions(rex);
3019 }
Chris Lattner4b009652007-07-25 00:24:17 +00003020 QualType lType = lex->getType();
3021 QualType rType = rex->getType();
3022
Ted Kremenek486509e2007-10-29 17:13:39 +00003023 // For non-floating point types, check for self-comparisons of the form
3024 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3025 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003026 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003027 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3028 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003029 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003030 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003031 }
3032
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003033 // The result of comparisons is 'bool' in C++, 'int' in C.
3034 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3035
Chris Lattner254f3bc2007-08-26 01:18:55 +00003036 if (isRelational) {
3037 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003038 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003039 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003040 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003041 if (lType->isFloatingType()) {
3042 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003043 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003044 }
3045
Chris Lattner254f3bc2007-08-26 01:18:55 +00003046 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003047 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003048 }
Chris Lattner4b009652007-07-25 00:24:17 +00003049
Chris Lattner22be8422007-08-26 01:10:14 +00003050 bool LHSIsNull = lex->isNullPointerConstant(Context);
3051 bool RHSIsNull = rex->isNullPointerConstant(Context);
3052
Chris Lattner254f3bc2007-08-26 01:18:55 +00003053 // All of the following pointer related warnings are GCC extensions, except
3054 // when handling null pointer constants. One day, we can consider making them
3055 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003056 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003057 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003058 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003059 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003060 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00003061
Steve Naroff3b435622007-11-13 14:57:38 +00003062 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003063 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3064 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003065 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003066 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003067 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003068 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003069 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003070 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003071 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003072 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003073 // Handle block pointer types.
3074 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3075 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3076 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3077
3078 if (!LHSIsNull && !RHSIsNull &&
3079 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003080 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003081 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003082 }
3083 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003084 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003085 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003086 // Allow block pointers to be compared with null pointer constants.
3087 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3088 (lType->isPointerType() && rType->isBlockPointerType())) {
3089 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003090 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003091 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003092 }
3093 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003094 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003095 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003096
Steve Naroff936c4362008-06-03 14:04:54 +00003097 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003098 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003099 const PointerType *LPT = lType->getAsPointerType();
3100 const PointerType *RPT = rType->getAsPointerType();
3101 bool LPtrToVoid = LPT ?
3102 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3103 bool RPtrToVoid = RPT ?
3104 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3105
3106 if (!LPtrToVoid && !RPtrToVoid &&
3107 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003108 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003109 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003110 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003111 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003112 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003113 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003114 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003115 }
Steve Naroff936c4362008-06-03 14:04:54 +00003116 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3117 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003118 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003119 } else {
3120 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003121 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003122 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003123 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003124 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003125 }
Steve Naroff936c4362008-06-03 14:04:54 +00003126 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003127 }
Steve Naroff936c4362008-06-03 14:04:54 +00003128 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3129 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003130 if (!RHSIsNull)
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(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003134 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003135 }
Steve Naroff936c4362008-06-03 14:04:54 +00003136 if (lType->isIntegerType() &&
3137 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003138 if (!LHSIsNull)
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();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003141 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003142 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003143 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003144 // Handle block pointers.
3145 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3146 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003147 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003148 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003149 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003150 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003151 }
3152 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3153 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003154 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003155 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003156 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003157 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003158 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003159 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003160}
3161
Nate Begemanc5f0f652008-07-14 18:02:46 +00003162/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3163/// operates on extended vector types. Instead of producing an IntTy result,
3164/// like a scalar comparison, a vector comparison produces a vector of integer
3165/// types.
3166QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003167 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003168 bool isRelational) {
3169 // Check to make sure we're operating on vectors of the same type and width,
3170 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003171 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003172 if (vType.isNull())
3173 return vType;
3174
3175 QualType lType = lex->getType();
3176 QualType rType = rex->getType();
3177
3178 // For non-floating point types, check for self-comparisons of the form
3179 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3180 // often indicate logic errors in the program.
3181 if (!lType->isFloatingType()) {
3182 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3183 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3184 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003185 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003186 }
3187
3188 // Check for comparisons of floating point operands using != and ==.
3189 if (!isRelational && lType->isFloatingType()) {
3190 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003191 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003192 }
3193
3194 // Return the type for the comparison, which is the same as vector type for
3195 // integer vectors, or an integer type of identical size and number of
3196 // elements for floating point vectors.
3197 if (lType->isIntegerType())
3198 return lType;
3199
3200 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003201 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003202 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003203 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003204 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3205 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3206
3207 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3208 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003209 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3210}
3211
Chris Lattner4b009652007-07-25 00:24:17 +00003212inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003213 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003214{
3215 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003216 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003217
Steve Naroff8f708362007-08-24 19:07:16 +00003218 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003219
3220 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003221 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003222 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003223}
3224
3225inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003226 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003227{
3228 UsualUnaryConversions(lex);
3229 UsualUnaryConversions(rex);
3230
Eli Friedmanbea3f842008-05-13 20:16:47 +00003231 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003232 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003233 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003234}
3235
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003236/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3237/// is a read-only property; return true if so. A readonly property expression
3238/// depends on various declarations and thus must be treated specially.
3239///
3240static bool IsReadonlyProperty(Expr *E, Sema &S)
3241{
3242 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3243 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3244 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3245 QualType BaseType = PropExpr->getBase()->getType();
3246 if (const PointerType *PTy = BaseType->getAsPointerType())
3247 if (const ObjCInterfaceType *IFTy =
3248 PTy->getPointeeType()->getAsObjCInterfaceType())
3249 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3250 if (S.isPropertyReadonly(PDecl, IFace))
3251 return true;
3252 }
3253 }
3254 return false;
3255}
3256
Chris Lattner4c2642c2008-11-18 01:22:49 +00003257/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3258/// emit an error and return true. If so, return false.
3259static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003260 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3261 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3262 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003263 if (IsLV == Expr::MLV_Valid)
3264 return false;
3265
3266 unsigned Diag = 0;
3267 bool NeedType = false;
3268 switch (IsLV) { // C99 6.5.16p2
3269 default: assert(0 && "Unknown result from isModifiableLvalue!");
3270 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003271 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003272 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3273 NeedType = true;
3274 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003275 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003276 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3277 NeedType = true;
3278 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003279 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003280 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3281 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003282 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003283 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3284 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003285 case Expr::MLV_IncompleteType:
3286 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003287 return S.DiagnoseIncompleteType(Loc, E->getType(),
3288 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3289 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003290 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003291 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3292 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003293 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003294 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3295 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003296 case Expr::MLV_ReadonlyProperty:
3297 Diag = diag::error_readonly_property_assignment;
3298 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003299 case Expr::MLV_NoSetterProperty:
3300 Diag = diag::error_nosetter_property_assignment;
3301 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003302 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003303
Chris Lattner4c2642c2008-11-18 01:22:49 +00003304 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003305 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003306 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003307 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003308 return true;
3309}
3310
3311
3312
3313// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003314QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3315 SourceLocation Loc,
3316 QualType CompoundType) {
3317 // Verify that LHS is a modifiable lvalue, and emit error if not.
3318 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003319 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003320
3321 QualType LHSType = LHS->getType();
3322 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003323
Chris Lattner005ed752008-01-04 18:04:52 +00003324 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003325 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003326 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003327 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003328 // Special case of NSObject attributes on c-style pointer types.
3329 if (ConvTy == IncompatiblePointer &&
3330 ((Context.isObjCNSObjectType(LHSType) &&
3331 Context.isObjCObjectPointerType(RHSType)) ||
3332 (Context.isObjCNSObjectType(RHSType) &&
3333 Context.isObjCObjectPointerType(LHSType))))
3334 ConvTy = Compatible;
3335
Chris Lattner34c85082008-08-21 18:04:13 +00003336 // If the RHS is a unary plus or minus, check to see if they = and + are
3337 // right next to each other. If so, the user may have typo'd "x =+ 4"
3338 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003339 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003340 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3341 RHSCheck = ICE->getSubExpr();
3342 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3343 if ((UO->getOpcode() == UnaryOperator::Plus ||
3344 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003345 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003346 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003347 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003348 Diag(Loc, diag::warn_not_compound_assign)
3349 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3350 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003351 }
3352 } else {
3353 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003354 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003355 }
Chris Lattner005ed752008-01-04 18:04:52 +00003356
Chris Lattner1eafdea2008-11-18 01:30:42 +00003357 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3358 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003359 return QualType();
3360
Chris Lattner4b009652007-07-25 00:24:17 +00003361 // C99 6.5.16p3: The type of an assignment expression is the type of the
3362 // left operand unless the left operand has qualified type, in which case
3363 // it is the unqualified version of the type of the left operand.
3364 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3365 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003366 // C++ 5.17p1: the type of the assignment expression is that of its left
3367 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003368 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003369}
3370
Chris Lattner1eafdea2008-11-18 01:30:42 +00003371// C99 6.5.17
3372QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3373 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003374
3375 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003376 DefaultFunctionArrayConversion(RHS);
3377 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003378}
3379
3380/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3381/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003382QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3383 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003384 QualType ResType = Op->getType();
3385 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003386
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003387 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3388 // Decrement of bool is not allowed.
3389 if (!isInc) {
3390 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3391 return QualType();
3392 }
3393 // Increment of bool sets it to true, but is deprecated.
3394 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3395 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003396 // OK!
3397 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3398 // C99 6.5.2.4p2, 6.5.6p2
3399 if (PT->getPointeeType()->isObjectType()) {
3400 // Pointer to object is ok!
3401 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003402 if (getLangOptions().CPlusPlus) {
3403 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3404 << Op->getSourceRange();
3405 return QualType();
3406 }
3407
3408 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003409 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003410 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003411 if (getLangOptions().CPlusPlus) {
3412 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3413 << Op->getType() << Op->getSourceRange();
3414 return QualType();
3415 }
3416
3417 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003418 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003419 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003420 } else {
3421 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3422 diag::err_typecheck_arithmetic_incomplete_type,
3423 Op->getSourceRange(), SourceRange(),
3424 ResType);
3425 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003426 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003427 } else if (ResType->isComplexType()) {
3428 // C99 does not support ++/-- on complex types, we allow as an extension.
3429 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003430 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003431 } else {
3432 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003433 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003434 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003435 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003436 // At this point, we know we have a real, complex or pointer type.
3437 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003438 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003439 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003440 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003441}
3442
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003443/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003444/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003445/// where the declaration is needed for type checking. We only need to
3446/// handle cases when the expression references a function designator
3447/// or is an lvalue. Here are some examples:
3448/// - &(x) => x
3449/// - &*****f => f for f a function designator.
3450/// - &s.xx => s
3451/// - &s.zz[1].yy -> s, if zz is an array
3452/// - *(x + 1) -> x, if x is an array
3453/// - &"123"[2] -> 0
3454/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003455static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003456 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003457 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003458 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003459 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003460 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003461 // Fields cannot be declared with a 'register' storage class.
3462 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003463 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003464 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003465 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003466 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003467 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003468
Douglas Gregord2baafd2008-10-21 16:13:35 +00003469 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003470 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003471 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003472 return 0;
3473 else
3474 return VD;
3475 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003476 case Stmt::UnaryOperatorClass: {
3477 UnaryOperator *UO = cast<UnaryOperator>(E);
3478
3479 switch(UO->getOpcode()) {
3480 case UnaryOperator::Deref: {
3481 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003482 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3483 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3484 if (!VD || VD->getType()->isPointerType())
3485 return 0;
3486 return VD;
3487 }
3488 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003489 }
3490 case UnaryOperator::Real:
3491 case UnaryOperator::Imag:
3492 case UnaryOperator::Extension:
3493 return getPrimaryDecl(UO->getSubExpr());
3494 default:
3495 return 0;
3496 }
3497 }
3498 case Stmt::BinaryOperatorClass: {
3499 BinaryOperator *BO = cast<BinaryOperator>(E);
3500
3501 // Handle cases involving pointer arithmetic. The result of an
3502 // Assign or AddAssign is not an lvalue so they can be ignored.
3503
3504 // (x + n) or (n + x) => x
3505 if (BO->getOpcode() == BinaryOperator::Add) {
3506 if (BO->getLHS()->getType()->isPointerType()) {
3507 return getPrimaryDecl(BO->getLHS());
3508 } else if (BO->getRHS()->getType()->isPointerType()) {
3509 return getPrimaryDecl(BO->getRHS());
3510 }
3511 }
3512
3513 return 0;
3514 }
Chris Lattner4b009652007-07-25 00:24:17 +00003515 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003516 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003517 case Stmt::ImplicitCastExprClass:
3518 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003519 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003520 default:
3521 return 0;
3522 }
3523}
3524
3525/// CheckAddressOfOperand - The operand of & must be either a function
3526/// designator or an lvalue designating an object. If it is an lvalue, the
3527/// object cannot be declared with storage class register or be a bit field.
3528/// Note: The usual conversions are *not* applied to the operand of the &
3529/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003530/// In C++, the operand might be an overloaded function name, in which case
3531/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003532QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003533 if (op->isTypeDependent())
3534 return Context.DependentTy;
3535
Steve Naroff9c6c3592008-01-13 17:10:08 +00003536 if (getLangOptions().C99) {
3537 // Implement C99-only parts of addressof rules.
3538 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3539 if (uOp->getOpcode() == UnaryOperator::Deref)
3540 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3541 // (assuming the deref expression is valid).
3542 return uOp->getSubExpr()->getType();
3543 }
3544 // Technically, there should be a check for array subscript
3545 // expressions here, but the result of one is always an lvalue anyway.
3546 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003547 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003548 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003549
Chris Lattner4b009652007-07-25 00:24:17 +00003550 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003551 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3552 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003553 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3554 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003555 return QualType();
3556 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003557 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003558 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3559 if (Field->isBitField()) {
3560 Diag(OpLoc, diag::err_typecheck_address_of)
3561 << "bit-field" << op->getSourceRange();
3562 return QualType();
3563 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003564 }
3565 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003566 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3567 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003568 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003569 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003570 return QualType();
3571 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003572 // We have an lvalue with a decl. Make sure the decl is not declared
3573 // with the register storage-class specifier.
3574 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3575 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003576 Diag(OpLoc, diag::err_typecheck_address_of)
3577 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003578 return QualType();
3579 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003580 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003581 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003582 } else if (isa<FieldDecl>(dcl)) {
3583 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003584 // Could be a pointer to member, though, if there is an explicit
3585 // scope qualifier for the class.
3586 if (isa<QualifiedDeclRefExpr>(op)) {
3587 DeclContext *Ctx = dcl->getDeclContext();
3588 if (Ctx && Ctx->isRecord())
3589 return Context.getMemberPointerType(op->getType(),
3590 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3591 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003592 } else if (isa<FunctionDecl>(dcl)) {
3593 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003594 // As above.
3595 if (isa<QualifiedDeclRefExpr>(op)) {
3596 DeclContext *Ctx = dcl->getDeclContext();
3597 if (Ctx && Ctx->isRecord())
3598 return Context.getMemberPointerType(op->getType(),
3599 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3600 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003601 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003602 else
Chris Lattner4b009652007-07-25 00:24:17 +00003603 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003604 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003605
Chris Lattner4b009652007-07-25 00:24:17 +00003606 // If the operand has type "type", the result has type "pointer to type".
3607 return Context.getPointerType(op->getType());
3608}
3609
Chris Lattnerda5c0872008-11-23 09:13:29 +00003610QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3611 UsualUnaryConversions(Op);
3612 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003613
Chris Lattnerda5c0872008-11-23 09:13:29 +00003614 // Note that per both C89 and C99, this is always legal, even if ptype is an
3615 // incomplete type or void. It would be possible to warn about dereferencing
3616 // a void pointer, but it's completely well-defined, and such a warning is
3617 // unlikely to catch any mistakes.
3618 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003619 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003620
Chris Lattner77d52da2008-11-20 06:06:08 +00003621 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003622 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003623 return QualType();
3624}
3625
3626static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3627 tok::TokenKind Kind) {
3628 BinaryOperator::Opcode Opc;
3629 switch (Kind) {
3630 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003631 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3632 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003633 case tok::star: Opc = BinaryOperator::Mul; break;
3634 case tok::slash: Opc = BinaryOperator::Div; break;
3635 case tok::percent: Opc = BinaryOperator::Rem; break;
3636 case tok::plus: Opc = BinaryOperator::Add; break;
3637 case tok::minus: Opc = BinaryOperator::Sub; break;
3638 case tok::lessless: Opc = BinaryOperator::Shl; break;
3639 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3640 case tok::lessequal: Opc = BinaryOperator::LE; break;
3641 case tok::less: Opc = BinaryOperator::LT; break;
3642 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3643 case tok::greater: Opc = BinaryOperator::GT; break;
3644 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3645 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3646 case tok::amp: Opc = BinaryOperator::And; break;
3647 case tok::caret: Opc = BinaryOperator::Xor; break;
3648 case tok::pipe: Opc = BinaryOperator::Or; break;
3649 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3650 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3651 case tok::equal: Opc = BinaryOperator::Assign; break;
3652 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3653 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3654 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3655 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3656 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3657 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3658 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3659 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3660 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3661 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3662 case tok::comma: Opc = BinaryOperator::Comma; break;
3663 }
3664 return Opc;
3665}
3666
3667static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3668 tok::TokenKind Kind) {
3669 UnaryOperator::Opcode Opc;
3670 switch (Kind) {
3671 default: assert(0 && "Unknown unary op!");
3672 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3673 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3674 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3675 case tok::star: Opc = UnaryOperator::Deref; break;
3676 case tok::plus: Opc = UnaryOperator::Plus; break;
3677 case tok::minus: Opc = UnaryOperator::Minus; break;
3678 case tok::tilde: Opc = UnaryOperator::Not; break;
3679 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003680 case tok::kw___real: Opc = UnaryOperator::Real; break;
3681 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3682 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3683 }
3684 return Opc;
3685}
3686
Douglas Gregord7f915e2008-11-06 23:29:22 +00003687/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3688/// operator @p Opc at location @c TokLoc. This routine only supports
3689/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003690Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3691 unsigned Op,
3692 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003693 QualType ResultTy; // Result type of the binary operator.
3694 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3695 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3696
3697 switch (Opc) {
3698 default:
3699 assert(0 && "Unknown binary expr!");
3700 case BinaryOperator::Assign:
3701 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3702 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003703 case BinaryOperator::PtrMemD:
3704 case BinaryOperator::PtrMemI:
3705 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3706 Opc == BinaryOperator::PtrMemI);
3707 break;
3708 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003709 case BinaryOperator::Div:
3710 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3711 break;
3712 case BinaryOperator::Rem:
3713 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3714 break;
3715 case BinaryOperator::Add:
3716 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3717 break;
3718 case BinaryOperator::Sub:
3719 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3720 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003721 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003722 case BinaryOperator::Shr:
3723 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3724 break;
3725 case BinaryOperator::LE:
3726 case BinaryOperator::LT:
3727 case BinaryOperator::GE:
3728 case BinaryOperator::GT:
3729 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3730 break;
3731 case BinaryOperator::EQ:
3732 case BinaryOperator::NE:
3733 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3734 break;
3735 case BinaryOperator::And:
3736 case BinaryOperator::Xor:
3737 case BinaryOperator::Or:
3738 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3739 break;
3740 case BinaryOperator::LAnd:
3741 case BinaryOperator::LOr:
3742 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3743 break;
3744 case BinaryOperator::MulAssign:
3745 case BinaryOperator::DivAssign:
3746 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3747 if (!CompTy.isNull())
3748 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3749 break;
3750 case BinaryOperator::RemAssign:
3751 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3752 if (!CompTy.isNull())
3753 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3754 break;
3755 case BinaryOperator::AddAssign:
3756 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3757 if (!CompTy.isNull())
3758 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3759 break;
3760 case BinaryOperator::SubAssign:
3761 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3762 if (!CompTy.isNull())
3763 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3764 break;
3765 case BinaryOperator::ShlAssign:
3766 case BinaryOperator::ShrAssign:
3767 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3768 if (!CompTy.isNull())
3769 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3770 break;
3771 case BinaryOperator::AndAssign:
3772 case BinaryOperator::XorAssign:
3773 case BinaryOperator::OrAssign:
3774 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3775 if (!CompTy.isNull())
3776 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3777 break;
3778 case BinaryOperator::Comma:
3779 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3780 break;
3781 }
3782 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003783 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003784 if (CompTy.isNull())
3785 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3786 else
3787 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003788 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003789}
3790
Chris Lattner4b009652007-07-25 00:24:17 +00003791// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003792Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3793 tok::TokenKind Kind,
3794 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003795 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003796 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003797
Steve Naroff87d58b42007-09-16 03:34:24 +00003798 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3799 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003800
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003801 // If either expression is type-dependent, just build the AST.
3802 // FIXME: We'll need to perform some caching of the result of name
3803 // lookup for operator+.
3804 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003805 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3806 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003807 Context.DependentTy,
3808 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003809 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003810 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3811 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003812 }
3813
Sebastian Redl95216a62009-02-07 00:15:38 +00003814 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003815 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3816 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003817 // If this is one of the assignment operators, we only perform
3818 // overload resolution if the left-hand side is a class or
3819 // enumeration type (C++ [expr.ass]p3).
3820 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3821 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3822 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3823 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003824
Douglas Gregord7f915e2008-11-06 23:29:22 +00003825 // Determine which overloaded operator we're dealing with.
3826 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003827 // Overloading .* is not possible.
3828 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003829 OO_Star, OO_Slash, OO_Percent,
3830 OO_Plus, OO_Minus,
3831 OO_LessLess, OO_GreaterGreater,
3832 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3833 OO_EqualEqual, OO_ExclaimEqual,
3834 OO_Amp,
3835 OO_Caret,
3836 OO_Pipe,
3837 OO_AmpAmp,
3838 OO_PipePipe,
3839 OO_Equal, OO_StarEqual,
3840 OO_SlashEqual, OO_PercentEqual,
3841 OO_PlusEqual, OO_MinusEqual,
3842 OO_LessLessEqual, OO_GreaterGreaterEqual,
3843 OO_AmpEqual, OO_CaretEqual,
3844 OO_PipeEqual,
3845 OO_Comma
3846 };
3847 OverloadedOperatorKind OverOp = OverOps[Opc];
3848
Douglas Gregor5ed15042008-11-18 23:14:02 +00003849 // Add the appropriate overloaded operators (C++ [over.match.oper])
3850 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003851 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003852 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003853 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3854 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003855
3856 // Perform overload resolution.
3857 OverloadCandidateSet::iterator Best;
3858 switch (BestViableFunction(CandidateSet, Best)) {
3859 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003860 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003861 FunctionDecl *FnDecl = Best->Function;
3862
Douglas Gregor70d26122008-11-12 17:17:38 +00003863 if (FnDecl) {
3864 // We matched an overloaded operator. Build a call to that
3865 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003866
Douglas Gregor70d26122008-11-12 17:17:38 +00003867 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003868 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3869 if (PerformObjectArgumentInitialization(lhs, Method) ||
3870 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3871 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003872 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003873 } else {
3874 // Convert the arguments.
3875 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3876 "passing") ||
3877 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3878 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003879 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003880 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003881
Douglas Gregor70d26122008-11-12 17:17:38 +00003882 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003883 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003884 = FnDecl->getType()->getAsFunctionType()->getResultType();
3885 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003886
Douglas Gregor70d26122008-11-12 17:17:38 +00003887 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003888 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3889 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003890 UsualUnaryConversions(FnExpr);
3891
Ted Kremenek362abcd2009-02-09 20:51:47 +00003892 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003893 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003894 } else {
3895 // We matched a built-in operator. Convert the arguments, then
3896 // break out so that we will build the appropriate built-in
3897 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003898 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3899 Best->Conversions[0], "passing") ||
3900 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3901 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003902 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003903
3904 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003905 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003906 }
3907
3908 case OR_No_Viable_Function:
3909 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003910 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003911 break;
3912
3913 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003914 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3915 << BinaryOperator::getOpcodeStr(Opc)
3916 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003917 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003918 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003919 }
3920
Douglas Gregor70d26122008-11-12 17:17:38 +00003921 // Either we found no viable overloaded operator or we matched a
3922 // built-in operator. In either case, fall through to trying to
3923 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003924 }
3925
Douglas Gregord7f915e2008-11-06 23:29:22 +00003926 // Build a built-in binary operation.
3927 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003928}
3929
3930// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003931Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3932 tok::TokenKind Op, ExprArg input) {
3933 // FIXME: Input is modified later, but smart pointer not reassigned.
3934 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003935 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003936
3937 if (getLangOptions().CPlusPlus &&
3938 (Input->getType()->isRecordType()
3939 || Input->getType()->isEnumeralType())) {
3940 // Determine which overloaded operator we're dealing with.
3941 static const OverloadedOperatorKind OverOps[] = {
3942 OO_None, OO_None,
3943 OO_PlusPlus, OO_MinusMinus,
3944 OO_Amp, OO_Star,
3945 OO_Plus, OO_Minus,
3946 OO_Tilde, OO_Exclaim,
3947 OO_None, OO_None,
3948 OO_None,
3949 OO_None
3950 };
3951 OverloadedOperatorKind OverOp = OverOps[Opc];
3952
3953 // Add the appropriate overloaded operators (C++ [over.match.oper])
3954 // to the candidate set.
3955 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003956 if (OverOp != OO_None &&
3957 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3958 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003959
3960 // Perform overload resolution.
3961 OverloadCandidateSet::iterator Best;
3962 switch (BestViableFunction(CandidateSet, Best)) {
3963 case OR_Success: {
3964 // We found a built-in operator or an overloaded operator.
3965 FunctionDecl *FnDecl = Best->Function;
3966
3967 if (FnDecl) {
3968 // We matched an overloaded operator. Build a call to that
3969 // operator.
3970
3971 // Convert the arguments.
3972 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3973 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003974 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003975 } else {
3976 // Convert the arguments.
3977 if (PerformCopyInitialization(Input,
3978 FnDecl->getParamDecl(0)->getType(),
3979 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003980 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003981 }
3982
3983 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003984 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003985 = FnDecl->getType()->getAsFunctionType()->getResultType();
3986 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003987
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003988 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003989 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3990 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003991 UsualUnaryConversions(FnExpr);
3992
Sebastian Redl8b769972009-01-19 00:08:26 +00003993 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003994 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003995 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003996 } else {
3997 // We matched a built-in operator. Convert the arguments, then
3998 // break out so that we will build the appropriate built-in
3999 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004000 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4001 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004002 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004003
4004 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004005 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004006 }
4007
4008 case OR_No_Viable_Function:
4009 // No viable function; fall through to handling this as a
4010 // built-in operator, which will produce an error message for us.
4011 break;
4012
4013 case OR_Ambiguous:
4014 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4015 << UnaryOperator::getOpcodeStr(Opc)
4016 << Input->getSourceRange();
4017 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004018 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004019 }
4020
4021 // Either we found no viable overloaded operator or we matched a
4022 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004023 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004024 }
4025
Chris Lattner4b009652007-07-25 00:24:17 +00004026 QualType resultType;
4027 switch (Opc) {
4028 default:
4029 assert(0 && "Unimplemented unary expr!");
4030 case UnaryOperator::PreInc:
4031 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004032 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4033 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004034 break;
4035 case UnaryOperator::AddrOf:
4036 resultType = CheckAddressOfOperand(Input, OpLoc);
4037 break;
4038 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004039 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004040 resultType = CheckIndirectionOperand(Input, OpLoc);
4041 break;
4042 case UnaryOperator::Plus:
4043 case UnaryOperator::Minus:
4044 UsualUnaryConversions(Input);
4045 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004046 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4047 break;
4048 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4049 resultType->isEnumeralType())
4050 break;
4051 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4052 Opc == UnaryOperator::Plus &&
4053 resultType->isPointerType())
4054 break;
4055
Sebastian Redl8b769972009-01-19 00:08:26 +00004056 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4057 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004058 case UnaryOperator::Not: // bitwise complement
4059 UsualUnaryConversions(Input);
4060 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004061 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4062 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4063 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004064 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004065 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004066 else if (!resultType->isIntegerType())
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 break;
4070 case UnaryOperator::LNot: // logical negation
4071 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4072 DefaultFunctionArrayConversion(Input);
4073 resultType = Input->getType();
4074 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004075 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4076 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004077 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004078 // In C++, it's bool. C++ 5.3.1p8
4079 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004080 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004081 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004082 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004083 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004084 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004085 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004086 resultType = Input->getType();
4087 break;
4088 }
4089 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004090 return ExprError();
4091 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004092 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004093}
4094
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004095/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4096Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004097 SourceLocation LabLoc,
4098 IdentifierInfo *LabelII) {
4099 // Look up the record for this label identifier.
4100 LabelStmt *&LabelDecl = LabelMap[LabelII];
4101
Daniel Dunbar879788d2008-08-04 16:51:22 +00004102 // If we haven't seen this label yet, create a forward reference. It
4103 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004104 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004105 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004106
4107 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004108 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4109 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004110}
4111
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004112Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004113 SourceLocation RPLoc) { // "({..})"
4114 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4115 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4116 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4117
Eli Friedmanbc941e12009-01-24 23:09:00 +00004118 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4119 if (isFileScope) {
4120 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4121 }
4122
Chris Lattner4b009652007-07-25 00:24:17 +00004123 // FIXME: there are a variety of strange constraints to enforce here, for
4124 // example, it is not possible to goto into a stmt expression apparently.
4125 // More semantic analysis is needed.
4126
4127 // FIXME: the last statement in the compount stmt has its value used. We
4128 // should not warn about it being unused.
4129
4130 // If there are sub stmts in the compound stmt, take the type of the last one
4131 // as the type of the stmtexpr.
4132 QualType Ty = Context.VoidTy;
4133
Chris Lattner200964f2008-07-26 19:51:01 +00004134 if (!Compound->body_empty()) {
4135 Stmt *LastStmt = Compound->body_back();
4136 // If LastStmt is a label, skip down through into the body.
4137 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4138 LastStmt = Label->getSubStmt();
4139
4140 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004141 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004142 }
Chris Lattner4b009652007-07-25 00:24:17 +00004143
Steve Naroff774e4152009-01-21 00:14:39 +00004144 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004145}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004146
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004147Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4148 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004149 SourceLocation TypeLoc,
4150 TypeTy *argty,
4151 OffsetOfComponent *CompPtr,
4152 unsigned NumComponents,
4153 SourceLocation RPLoc) {
4154 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4155 assert(!ArgTy.isNull() && "Missing type argument!");
4156
4157 // We must have at least one component that refers to the type, and the first
4158 // one is known to be a field designator. Verify that the ArgTy represents
4159 // a struct/union/class.
4160 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004161 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004162
4163 // Otherwise, create a compound literal expression as the base, and
4164 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004165 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004166 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004167 IList->setType(ArgTy);
4168 Expr *Res =
4169 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4170
Chris Lattnerb37522e2007-08-31 21:49:13 +00004171 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4172 // GCC extension, diagnose them.
4173 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004174 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4175 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004176
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004177 for (unsigned i = 0; i != NumComponents; ++i) {
4178 const OffsetOfComponent &OC = CompPtr[i];
4179 if (OC.isBrackets) {
4180 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004181 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004182 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004183 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004184 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004185 }
4186
Chris Lattner2af6a802007-08-30 17:59:59 +00004187 // FIXME: C++: Verify that operator[] isn't overloaded.
4188
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004189 // C99 6.5.2.1p1
4190 Expr *Idx = static_cast<Expr*>(OC.U.E);
4191 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004192 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4193 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004194
Steve Naroff774e4152009-01-21 00:14:39 +00004195 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4196 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004197 continue;
4198 }
4199
4200 const RecordType *RC = Res->getType()->getAsRecordType();
4201 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004202 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004203 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004204 }
4205
4206 // Get the decl corresponding to this.
4207 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004208 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004209 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4210 LookupMemberName)
4211 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004212 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004213 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4214 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004215
4216 // FIXME: C++: Verify that MemberDecl isn't a static field.
4217 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004218 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4219 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004220 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4221 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004222 }
4223
Steve Naroff774e4152009-01-21 00:14:39 +00004224 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4225 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004226}
4227
4228
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004229Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004230 TypeTy *arg1, TypeTy *arg2,
4231 SourceLocation RPLoc) {
4232 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4233 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4234
4235 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4236
Steve Naroff774e4152009-01-21 00:14:39 +00004237 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4238 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004239}
4240
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004241Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004242 ExprTy *expr1, ExprTy *expr2,
4243 SourceLocation RPLoc) {
4244 Expr *CondExpr = static_cast<Expr*>(cond);
4245 Expr *LHSExpr = static_cast<Expr*>(expr1);
4246 Expr *RHSExpr = static_cast<Expr*>(expr2);
4247
4248 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4249
4250 // The conditional expression is required to be a constant expression.
4251 llvm::APSInt condEval(32);
4252 SourceLocation ExpLoc;
4253 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004254 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4255 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004256
4257 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4258 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4259 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004260 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4261 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004262}
4263
Steve Naroff52a81c02008-09-03 18:15:37 +00004264//===----------------------------------------------------------------------===//
4265// Clang Extensions.
4266//===----------------------------------------------------------------------===//
4267
4268/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004269void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004270 // Analyze block parameters.
4271 BlockSemaInfo *BSI = new BlockSemaInfo();
4272
4273 // Add BSI to CurBlock.
4274 BSI->PrevBlockInfo = CurBlock;
4275 CurBlock = BSI;
4276
4277 BSI->ReturnType = 0;
4278 BSI->TheScope = BlockScope;
4279
Steve Naroff52059382008-10-10 01:28:17 +00004280 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004281 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004282}
4283
Mike Stumpc1fddff2009-02-04 22:31:32 +00004284void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4285 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4286
4287 if (ParamInfo.getNumTypeObjects() == 0
4288 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4289 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4290
4291 // The type is entirely optional as well, if none, use DependentTy.
4292 if (T.isNull())
4293 T = Context.DependentTy;
4294
4295 // The parameter list is optional, if there was none, assume ().
4296 if (!T->isFunctionType())
4297 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4298
4299 CurBlock->hasPrototype = true;
4300 CurBlock->isVariadic = false;
4301 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4302 .getTypePtr();
4303
4304 if (!RetTy->isDependentType())
4305 CurBlock->ReturnType = RetTy;
4306 return;
4307 }
4308
Steve Naroff52a81c02008-09-03 18:15:37 +00004309 // Analyze arguments to block.
4310 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4311 "Not a function declarator!");
4312 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004313
Steve Naroff52059382008-10-10 01:28:17 +00004314 CurBlock->hasPrototype = FTI.hasPrototype;
4315 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004316
4317 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4318 // no arguments, not a function that takes a single void argument.
4319 if (FTI.hasPrototype &&
4320 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4321 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4322 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4323 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004324 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004325 } else if (FTI.hasPrototype) {
4326 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004327 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4328 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004329 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4330
4331 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4332 .getTypePtr();
4333
4334 if (!RetTy->isDependentType())
4335 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004336 }
Steve Naroff52059382008-10-10 01:28:17 +00004337 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4338
4339 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4340 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4341 // If this has an identifier, add it to the scope stack.
4342 if ((*AI)->getIdentifier())
4343 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004344}
4345
4346/// ActOnBlockError - If there is an error parsing a block, this callback
4347/// is invoked to pop the information about the block from the action impl.
4348void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4349 // Ensure that CurBlock is deleted.
4350 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4351
4352 // Pop off CurBlock, handle nested blocks.
4353 CurBlock = CurBlock->PrevBlockInfo;
4354
4355 // FIXME: Delete the ParmVarDecl objects as well???
4356
4357}
4358
4359/// ActOnBlockStmtExpr - This is called when the body of a block statement
4360/// literal was successfully completed. ^(int x){...}
4361Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4362 Scope *CurScope) {
4363 // Ensure that CurBlock is deleted.
4364 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004365 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004366
Steve Naroff52059382008-10-10 01:28:17 +00004367 PopDeclContext();
4368
Steve Naroff52a81c02008-09-03 18:15:37 +00004369 // Pop off CurBlock, handle nested blocks.
4370 CurBlock = CurBlock->PrevBlockInfo;
4371
4372 QualType RetTy = Context.VoidTy;
4373 if (BSI->ReturnType)
4374 RetTy = QualType(BSI->ReturnType, 0);
4375
4376 llvm::SmallVector<QualType, 8> ArgTypes;
4377 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4378 ArgTypes.push_back(BSI->Params[i]->getType());
4379
4380 QualType BlockTy;
4381 if (!BSI->hasPrototype)
4382 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4383 else
4384 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004385 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004386
4387 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004388
Steve Naroff95029d92008-10-08 18:44:00 +00004389 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004390 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004391}
4392
Nate Begemanbd881ef2008-01-30 20:50:20 +00004393/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004394/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004395/// The number of arguments has already been validated to match the number of
4396/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004397static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4398 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004399 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004400 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004401 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4402 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004403
4404 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004405 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004406 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004407 return true;
4408}
4409
4410Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4411 SourceLocation *CommaLocs,
4412 SourceLocation BuiltinLoc,
4413 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004414 // __builtin_overload requires at least 2 arguments
4415 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004416 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4417 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004418
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004419 // The first argument is required to be a constant expression. It tells us
4420 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004421 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004422 Expr *NParamsExpr = Args[0];
4423 llvm::APSInt constEval(32);
4424 SourceLocation ExpLoc;
4425 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004426 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4427 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004428
4429 // Verify that the number of parameters is > 0
4430 unsigned NumParams = constEval.getZExtValue();
4431 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004432 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4433 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004434 // Verify that we have at least 1 + NumParams arguments to the builtin.
4435 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004436 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4437 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004438
4439 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004440 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004441 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004442 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4443 // UsualUnaryConversions will convert the function DeclRefExpr into a
4444 // pointer to function.
4445 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004446 const FunctionTypeProto *FnType = 0;
4447 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4448 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004449
4450 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4451 // parameters, and the number of parameters must match the value passed to
4452 // the builtin.
4453 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004454 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4455 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004456
4457 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004458 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004459 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004460 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004461 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004462 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4463 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004464 // Remember our match, and continue processing the remaining arguments
4465 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004466 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004467 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004468 BuiltinLoc, RParenLoc);
4469 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004470 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004471 // Return the newly created OverloadExpr node, if we succeded in matching
4472 // exactly one of the candidate functions.
4473 if (OE)
4474 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004475
4476 // If we didn't find a matching function Expr in the __builtin_overload list
4477 // the return an error.
4478 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004479 for (unsigned i = 0; i != NumParams; ++i) {
4480 if (i != 0) typeNames += ", ";
4481 typeNames += Args[i+1]->getType().getAsString();
4482 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004483
Chris Lattner77d52da2008-11-20 06:06:08 +00004484 return Diag(BuiltinLoc, diag::err_overload_no_match)
4485 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004486}
4487
Anders Carlsson36760332007-10-15 20:28:48 +00004488Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4489 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004490 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004491 Expr *E = static_cast<Expr*>(expr);
4492 QualType T = QualType::getFromOpaquePtr(type);
4493
4494 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004495
4496 // Get the va_list type
4497 QualType VaListType = Context.getBuiltinVaListType();
4498 // Deal with implicit array decay; for example, on x86-64,
4499 // va_list is an array, but it's supposed to decay to
4500 // a pointer for va_arg.
4501 if (VaListType->isArrayType())
4502 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004503 // Make sure the input expression also decays appropriately.
4504 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004505
4506 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004507 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004508 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004509 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004510
4511 // FIXME: Warn if a non-POD type is passed in.
4512
Steve Naroff774e4152009-01-21 00:14:39 +00004513 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004514}
4515
Douglas Gregorad4b3792008-11-29 04:51:27 +00004516Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4517 // The type of __null will be int or long, depending on the size of
4518 // pointers on the target.
4519 QualType Ty;
4520 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4521 Ty = Context.IntTy;
4522 else
4523 Ty = Context.LongTy;
4524
Steve Naroff774e4152009-01-21 00:14:39 +00004525 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004526}
4527
Chris Lattner005ed752008-01-04 18:04:52 +00004528bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4529 SourceLocation Loc,
4530 QualType DstType, QualType SrcType,
4531 Expr *SrcExpr, const char *Flavor) {
4532 // Decode the result (notice that AST's are still created for extensions).
4533 bool isInvalid = false;
4534 unsigned DiagKind;
4535 switch (ConvTy) {
4536 default: assert(0 && "Unknown conversion type");
4537 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004538 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004539 DiagKind = diag::ext_typecheck_convert_pointer_int;
4540 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004541 case IntToPointer:
4542 DiagKind = diag::ext_typecheck_convert_int_pointer;
4543 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004544 case IncompatiblePointer:
4545 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4546 break;
4547 case FunctionVoidPointer:
4548 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4549 break;
4550 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004551 // If the qualifiers lost were because we were applying the
4552 // (deprecated) C++ conversion from a string literal to a char*
4553 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4554 // Ideally, this check would be performed in
4555 // CheckPointerTypesForAssignment. However, that would require a
4556 // bit of refactoring (so that the second argument is an
4557 // expression, rather than a type), which should be done as part
4558 // of a larger effort to fix CheckPointerTypesForAssignment for
4559 // C++ semantics.
4560 if (getLangOptions().CPlusPlus &&
4561 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4562 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004563 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4564 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004565 case IntToBlockPointer:
4566 DiagKind = diag::err_int_to_block_pointer;
4567 break;
4568 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004569 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004570 break;
Steve Naroff19608432008-10-14 22:18:38 +00004571 case IncompatibleObjCQualifiedId:
4572 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4573 // it can give a more specific diagnostic.
4574 DiagKind = diag::warn_incompatible_qualified_id;
4575 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004576 case IncompatibleVectors:
4577 DiagKind = diag::warn_incompatible_vectors;
4578 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004579 case Incompatible:
4580 DiagKind = diag::err_typecheck_convert_incompatible;
4581 isInvalid = true;
4582 break;
4583 }
4584
Chris Lattner271d4c22008-11-24 05:29:24 +00004585 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4586 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004587 return isInvalid;
4588}
Anders Carlssond5201b92008-11-30 19:50:32 +00004589
4590bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4591{
4592 Expr::EvalResult EvalResult;
4593
4594 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4595 EvalResult.HasSideEffects) {
4596 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4597
4598 if (EvalResult.Diag) {
4599 // We only show the note if it's not the usual "invalid subexpression"
4600 // or if it's actually in a subexpression.
4601 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4602 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4603 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4604 }
4605
4606 return true;
4607 }
4608
4609 if (EvalResult.Diag) {
4610 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4611 E->getSourceRange();
4612
4613 // Print the reason it's not a constant.
4614 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4615 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4616 }
4617
4618 if (Result)
4619 *Result = EvalResult.Val.getInt();
4620 return false;
4621}