blob: 4eb29c4f94a12c77751ec4d25cc481ce9ddb5869 [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);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000355
Chris Lattner4b009652007-07-25 00:24:17 +0000356 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek4f530a92009-02-06 19:55:15 +0000357 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff774e4152009-01-21 00:14:39 +0000358 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000359 Literal.AnyWide, StrTy,
360 StringToks[0].getLocation(),
361 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000362}
363
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000364/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
365/// CurBlock to VD should cause it to be snapshotted (as we do for auto
366/// variables defined outside the block) or false if this is not needed (e.g.
367/// for values inside the block or for globals).
368///
369/// FIXME: This will create BlockDeclRefExprs for global variables,
370/// function references, etc which is suboptimal :) and breaks
371/// things like "integer constant expression" tests.
372static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
373 ValueDecl *VD) {
374 // If the value is defined inside the block, we couldn't snapshot it even if
375 // we wanted to.
376 if (CurBlock->TheDecl == VD->getDeclContext())
377 return false;
378
379 // If this is an enum constant or function, it is constant, don't snapshot.
380 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
381 return false;
382
383 // If this is a reference to an extern, static, or global variable, no need to
384 // snapshot it.
385 // FIXME: What about 'const' variables in C++?
386 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
387 return Var->hasLocalStorage();
388
389 return true;
390}
391
392
393
Steve Naroff0acc9c92007-09-15 18:49:24 +0000394/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000395/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000396/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000397/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000398/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000399Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
400 IdentifierInfo &II,
401 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000402 const CXXScopeSpec *SS,
403 bool isAddressOfOperand) {
404 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000405 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000406}
407
Douglas Gregor566782a2009-01-06 05:10:23 +0000408/// BuildDeclRefExpr - Build either a DeclRefExpr or a
409/// QualifiedDeclRefExpr based on whether or not SS is a
410/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000411DeclRefExpr *
412Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
413 bool TypeDependent, bool ValueDependent,
414 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000415 if (SS && !SS->isEmpty())
416 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000417 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000418 else
419 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000420}
421
Douglas Gregor723d3332009-01-07 00:43:41 +0000422/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
423/// variable corresponding to the anonymous union or struct whose type
424/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000425static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000426 assert(Record->isAnonymousStructOrUnion() &&
427 "Record must be an anonymous struct or union!");
428
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000429 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000430 // be an O(1) operation rather than a slow walk through DeclContext's
431 // vector (which itself will be eliminated). DeclGroups might make
432 // this even better.
433 DeclContext *Ctx = Record->getDeclContext();
434 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
435 DEnd = Ctx->decls_end();
436 D != DEnd; ++D) {
437 if (*D == Record) {
438 // The object for the anonymous struct/union directly
439 // follows its type in the list of declarations.
440 ++D;
441 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000442 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000443 return *D;
444 }
445 }
446
447 assert(false && "Missing object for anonymous record");
448 return 0;
449}
450
Sebastian Redlcd883f72009-01-18 18:53:16 +0000451Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000452Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
453 FieldDecl *Field,
454 Expr *BaseObjectExpr,
455 SourceLocation OpLoc) {
456 assert(Field->getDeclContext()->isRecord() &&
457 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
458 && "Field must be stored inside an anonymous struct or union");
459
460 // Construct the sequence of field member references
461 // we'll have to perform to get to the field in the anonymous
462 // union/struct. The list of members is built from the field
463 // outward, so traverse it backwards to go from an object in
464 // the current context to the field we found.
465 llvm::SmallVector<FieldDecl *, 4> AnonFields;
466 AnonFields.push_back(Field);
467 VarDecl *BaseObject = 0;
468 DeclContext *Ctx = Field->getDeclContext();
469 do {
470 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000471 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000472 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
473 AnonFields.push_back(AnonField);
474 else {
475 BaseObject = cast<VarDecl>(AnonObject);
476 break;
477 }
478 Ctx = Ctx->getParent();
479 } while (Ctx->isRecord() &&
480 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
481
482 // Build the expression that refers to the base object, from
483 // which we will build a sequence of member references to each
484 // of the anonymous union objects and, eventually, the field we
485 // found via name lookup.
486 bool BaseObjectIsPointer = false;
487 unsigned ExtraQuals = 0;
488 if (BaseObject) {
489 // BaseObject is an anonymous struct/union variable (and is,
490 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000491 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000492 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000493 SourceLocation());
494 ExtraQuals
495 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
496 } else if (BaseObjectExpr) {
497 // The caller provided the base object expression. Determine
498 // whether its a pointer and whether it adds any qualifiers to the
499 // anonymous struct/union fields we're looking into.
500 QualType ObjectType = BaseObjectExpr->getType();
501 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
502 BaseObjectIsPointer = true;
503 ObjectType = ObjectPtr->getPointeeType();
504 }
505 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
506 } else {
507 // We've found a member of an anonymous struct/union that is
508 // inside a non-anonymous struct/union, so in a well-formed
509 // program our base object expression is "this".
510 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
511 if (!MD->isStatic()) {
512 QualType AnonFieldType
513 = Context.getTagDeclType(
514 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
515 QualType ThisType = Context.getTagDeclType(MD->getParent());
516 if ((Context.getCanonicalType(AnonFieldType)
517 == Context.getCanonicalType(ThisType)) ||
518 IsDerivedFrom(ThisType, AnonFieldType)) {
519 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000520 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000521 MD->getThisType(Context));
522 BaseObjectIsPointer = true;
523 }
524 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000525 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
526 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000527 }
528 ExtraQuals = MD->getTypeQualifiers();
529 }
530
531 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000532 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
533 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000534 }
535
536 // Build the implicit member references to the field of the
537 // anonymous struct/union.
538 Expr *Result = BaseObjectExpr;
539 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
540 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
541 FI != FIEnd; ++FI) {
542 QualType MemberType = (*FI)->getType();
543 if (!(*FI)->isMutable()) {
544 unsigned combinedQualifiers
545 = MemberType.getCVRQualifiers() | ExtraQuals;
546 MemberType = MemberType.getQualifiedType(combinedQualifiers);
547 }
Steve Naroff774e4152009-01-21 00:14:39 +0000548 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
549 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000550 BaseObjectIsPointer = false;
551 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
552 OpLoc = SourceLocation();
553 }
554
Sebastian Redlcd883f72009-01-18 18:53:16 +0000555 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000556}
557
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000558/// ActOnDeclarationNameExpr - The parser has read some kind of name
559/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
560/// performs lookup on that name and returns an expression that refers
561/// to that name. This routine isn't directly called from the parser,
562/// because the parser doesn't know about DeclarationName. Rather,
563/// this routine is called by ActOnIdentifierExpr,
564/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
565/// which form the DeclarationName from the corresponding syntactic
566/// forms.
567///
568/// HasTrailingLParen indicates whether this identifier is used in a
569/// function call context. LookupCtx is only used for a C++
570/// qualified-id (foo::bar) to indicate the class or namespace that
571/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000572///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000573/// isAddressOfOperand means that this expression is the direct operand
574/// of an address-of operator. This matters because this is the only
575/// situation where a qualified name referencing a non-static member may
576/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000577Sema::OwningExprResult
578Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
579 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000580 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000581 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000582 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000583 if (SS && SS->isInvalid())
584 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000585 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
586 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000587
Douglas Gregor09be81b2009-02-04 17:27:36 +0000588 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000589 if (Lookup.isAmbiguous()) {
590 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
591 SS && SS->isSet() ? SS->getRange()
592 : SourceRange());
593 return ExprError();
594 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000595 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000596
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000597 // If this reference is in an Objective-C method, then ivar lookup happens as
598 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000599 IdentifierInfo *II = Name.getAsIdentifierInfo();
600 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000601 // There are two cases to handle here. 1) scoped lookup could have failed,
602 // in which case we should look for an ivar. 2) scoped lookup could have
603 // found a decl, but that decl is outside the current method (i.e. a global
604 // variable). In these two cases, we do a lookup for an ivar with this
605 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000606 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000607 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000608 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000609 // Check if referencing a field with __attribute__((deprecated)).
610 DiagnoseUseOfDeprecatedDecl(IV, Loc);
611
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000612 // FIXME: This should use a new expr for a direct reference, don't turn
613 // this into Self->ivar, just return a BareIVarExpr or something.
614 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000615 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000616 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
617 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000618 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000619 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000620 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000621 }
622 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000623 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000624 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000625 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000626 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000627 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000628 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000629 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000630
631 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
632 HasTrailingLParen && D == 0) {
633 // We've seen something of the form
634 //
635 // identifier(
636 //
637 // and we did not find any entity by the name
638 // "identifier". However, this identifier is still subject to
639 // argument-dependent lookup, so keep track of the name.
640 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
641 Context.OverloadTy,
642 Loc));
643 }
644
Chris Lattner4b009652007-07-25 00:24:17 +0000645 if (D == 0) {
646 // Otherwise, this could be an implicitly declared function reference (legal
647 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000648 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000649 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000650 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000651 else {
652 // If this name wasn't predeclared and if this is not a function call,
653 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000654 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000655 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
656 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000657 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
658 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000659 return ExprError(Diag(Loc, diag::err_undeclared_use)
660 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000661 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000662 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000663 }
664 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000665
Sebastian Redl0c9da212009-02-03 20:19:35 +0000666 // If this is an expression of the form &Class::member, don't build an
667 // implicit member ref, because we want a pointer to the member in general,
668 // not any specific instance's member.
669 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000670 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000671 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000672 QualType DType;
673 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
674 DType = FD->getType().getNonReferenceType();
675 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
676 DType = Method->getType();
677 } else if (isa<OverloadedFunctionDecl>(D)) {
678 DType = Context.OverloadTy;
679 }
680 // Could be an inner type. That's diagnosed below, so ignore it here.
681 if (!DType.isNull()) {
682 // The pointer is type- and value-dependent if it points into something
683 // dependent.
684 bool Dependent = false;
685 for (; DC; DC = DC->getParent()) {
686 // FIXME: could stop early at namespace scope.
687 if (DC->isRecord()) {
688 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
689 if (Context.getTypeDeclType(Record)->isDependentType()) {
690 Dependent = true;
691 break;
692 }
693 }
694 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000695 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000696 }
697 }
698 }
699
Douglas Gregor723d3332009-01-07 00:43:41 +0000700 // We may have found a field within an anonymous union or struct
701 // (C++ [class.union]).
702 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
703 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
704 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000705
Douglas Gregor3257fb52008-12-22 05:46:06 +0000706 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
707 if (!MD->isStatic()) {
708 // C++ [class.mfct.nonstatic]p2:
709 // [...] if name lookup (3.4.1) resolves the name in the
710 // id-expression to a nonstatic nontype member of class X or of
711 // a base class of X, the id-expression is transformed into a
712 // class member access expression (5.2.5) using (*this) (9.3.2)
713 // as the postfix-expression to the left of the '.' operator.
714 DeclContext *Ctx = 0;
715 QualType MemberType;
716 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
717 Ctx = FD->getDeclContext();
718 MemberType = FD->getType();
719
720 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
721 MemberType = RefType->getPointeeType();
722 else if (!FD->isMutable()) {
723 unsigned combinedQualifiers
724 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
725 MemberType = MemberType.getQualifiedType(combinedQualifiers);
726 }
727 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
728 if (!Method->isStatic()) {
729 Ctx = Method->getParent();
730 MemberType = Method->getType();
731 }
732 } else if (OverloadedFunctionDecl *Ovl
733 = dyn_cast<OverloadedFunctionDecl>(D)) {
734 for (OverloadedFunctionDecl::function_iterator
735 Func = Ovl->function_begin(),
736 FuncEnd = Ovl->function_end();
737 Func != FuncEnd; ++Func) {
738 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
739 if (!DMethod->isStatic()) {
740 Ctx = Ovl->getDeclContext();
741 MemberType = Context.OverloadTy;
742 break;
743 }
744 }
745 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000746
747 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000748 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
749 QualType ThisType = Context.getTagDeclType(MD->getParent());
750 if ((Context.getCanonicalType(CtxType)
751 == Context.getCanonicalType(ThisType)) ||
752 IsDerivedFrom(ThisType, CtxType)) {
753 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000754 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000755 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000756 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000757 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000758 }
759 }
760 }
761 }
762
Douglas Gregor8acb7272008-12-11 16:49:14 +0000763 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000764 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
765 if (MD->isStatic())
766 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000767 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
768 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000769 }
770
Douglas Gregor3257fb52008-12-22 05:46:06 +0000771 // Any other ways we could have found the field in a well-formed
772 // program would have been turned into implicit member expressions
773 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000774 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
775 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000776 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000777
Chris Lattner4b009652007-07-25 00:24:17 +0000778 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000779 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000780 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000781 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000782 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000783 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000784
Steve Naroffd6163f32008-09-05 22:11:13 +0000785 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000786 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000787 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
788 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000789 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
790 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
791 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000792 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000793
Chris Lattnerd9037472009-02-15 01:38:09 +0000794 // Check if referencing an identifier with __attribute__((deprecated)).
Chris Lattner2cb744b2009-02-15 22:43:40 +0000795 DiagnoseUseOfDeprecatedDecl(VD, Loc);
Chris Lattnerd9037472009-02-15 01:38:09 +0000796
Douglas Gregor48840c72008-12-10 23:01:14 +0000797 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000798 // Warn about constructs like:
799 // if (void *X = foo()) { ... } else { X }.
800 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000801 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
802 Scope *CheckS = S;
803 while (CheckS) {
804 if (CheckS->isWithinElse() &&
805 CheckS->getControlParent()->isDeclScope(Var)) {
806 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000807 ExprError(Diag(Loc, diag::warn_value_always_false)
808 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000809 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000810 ExprError(Diag(Loc, diag::warn_value_always_zero)
811 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000812 break;
813 }
814
815 // Move up one more control parent to check again.
816 CheckS = CheckS->getControlParent();
817 if (CheckS)
818 CheckS = CheckS->getParent();
819 }
820 }
821 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000822
823 // Only create DeclRefExpr's for valid Decl's.
824 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000825 return ExprError();
826
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000827 // If the identifier reference is inside a block, and it refers to a value
828 // that is outside the block, create a BlockDeclRefExpr instead of a
829 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
830 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000831 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000832 // We do not do this for things like enum constants, global variables, etc,
833 // as they do not get snapshotted.
834 //
835 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000836 // The BlocksAttr indicates the variable is bound by-reference.
837 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000838 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000839 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000840
Steve Naroff52059382008-10-10 01:28:17 +0000841 // Variable will be bound by-copy, make it const within the closure.
842 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000843 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000844 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000845 }
846 // If this reference is not in a block or if the referenced variable is
847 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000848
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000849 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000850 bool ValueDependent = false;
851 if (getLangOptions().CPlusPlus) {
852 // C++ [temp.dep.expr]p3:
853 // An id-expression is type-dependent if it contains:
854 // - an identifier that was declared with a dependent type,
855 if (VD->getType()->isDependentType())
856 TypeDependent = true;
857 // - FIXME: a template-id that is dependent,
858 // - a conversion-function-id that specifies a dependent type,
859 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
860 Name.getCXXNameType()->isDependentType())
861 TypeDependent = true;
862 // - a nested-name-specifier that contains a class-name that
863 // names a dependent type.
864 else if (SS && !SS->isEmpty()) {
865 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
866 DC; DC = DC->getParent()) {
867 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000868 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000869 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
870 if (Context.getTypeDeclType(Record)->isDependentType()) {
871 TypeDependent = true;
872 break;
873 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000874 }
875 }
876 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000877
Douglas Gregora5d84612008-12-10 20:57:37 +0000878 // C++ [temp.dep.constexpr]p2:
879 //
880 // An identifier is value-dependent if it is:
881 // - a name declared with a dependent type,
882 if (TypeDependent)
883 ValueDependent = true;
884 // - the name of a non-type template parameter,
885 else if (isa<NonTypeTemplateParmDecl>(VD))
886 ValueDependent = true;
887 // - a constant with integral or enumeration type and is
888 // initialized with an expression that is value-dependent
889 // (FIXME!).
890 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000891
Sebastian Redlcd883f72009-01-18 18:53:16 +0000892 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
893 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000894}
895
Sebastian Redlcd883f72009-01-18 18:53:16 +0000896Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
897 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000898 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000899
Chris Lattner4b009652007-07-25 00:24:17 +0000900 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000901 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000902 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
903 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
904 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000905 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000906
Chris Lattner7e637512008-01-12 08:14:25 +0000907 // Pre-defined identifiers are of type char[x], where x is the length of the
908 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000909 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000910 if (FunctionDecl *FD = getCurFunctionDecl())
911 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000912 else if (ObjCMethodDecl *MD = getCurMethodDecl())
913 Length = MD->getSynthesizedMethodSize();
914 else {
915 Diag(Loc, diag::ext_predef_outside_function);
916 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
917 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
918 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000919
920
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000921 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000922 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000923 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000924 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000925}
926
Sebastian Redlcd883f72009-01-18 18:53:16 +0000927Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000928 llvm::SmallString<16> CharBuffer;
929 CharBuffer.resize(Tok.getLength());
930 const char *ThisTokBegin = &CharBuffer[0];
931 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000932
Chris Lattner4b009652007-07-25 00:24:17 +0000933 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
934 Tok.getLocation(), PP);
935 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000936 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000937
938 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
939
Sebastian Redl75324932009-01-20 22:23:13 +0000940 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
941 Literal.isWide(),
942 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000943}
944
Sebastian Redlcd883f72009-01-18 18:53:16 +0000945Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
946 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000947 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
948 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000949 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000950 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000951 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000952 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000953 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000954
Chris Lattner4b009652007-07-25 00:24:17 +0000955 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000956 // Add padding so that NumericLiteralParser can overread by one character.
957 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000958 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000959
Chris Lattner4b009652007-07-25 00:24:17 +0000960 // Get the spelling of the token, which eliminates trigraphs, etc.
961 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000962
Chris Lattner4b009652007-07-25 00:24:17 +0000963 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
964 Tok.getLocation(), PP);
965 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000966 return ExprError();
967
Chris Lattner1de66eb2007-08-26 03:42:43 +0000968 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000969
Chris Lattner1de66eb2007-08-26 03:42:43 +0000970 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000971 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000972 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000973 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000974 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000975 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000976 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000977 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000978
979 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
980
Ted Kremenekddedbe22007-11-29 00:56:49 +0000981 // isExact will be set by GetFloatValue().
982 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000983 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
984 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000985
Chris Lattner1de66eb2007-08-26 03:42:43 +0000986 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000987 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000988 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000989 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000990
Neil Booth7421e9c2007-08-29 22:00:19 +0000991 // long long is a C99 feature.
992 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000993 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000994 Diag(Tok.getLocation(), diag::ext_longlong);
995
Chris Lattner4b009652007-07-25 00:24:17 +0000996 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000997 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000998
Chris Lattner4b009652007-07-25 00:24:17 +0000999 if (Literal.GetIntegerValue(ResultVal)) {
1000 // If this value didn't fit into uintmax_t, warn and force to ull.
1001 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001002 Ty = Context.UnsignedLongLongTy;
1003 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001004 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001005 } else {
1006 // If this value fits into a ULL, try to figure out what else it fits into
1007 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001008
Chris Lattner4b009652007-07-25 00:24:17 +00001009 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1010 // be an unsigned int.
1011 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1012
1013 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001014 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001015 if (!Literal.isLong && !Literal.isLongLong) {
1016 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001017 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001018
Chris Lattner4b009652007-07-25 00:24:17 +00001019 // Does it fit in a unsigned int?
1020 if (ResultVal.isIntN(IntSize)) {
1021 // Does it fit in a signed int?
1022 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001023 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001024 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001025 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001026 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001027 }
Chris Lattner4b009652007-07-25 00:24:17 +00001028 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001029
Chris Lattner4b009652007-07-25 00:24:17 +00001030 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001031 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001032 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033
Chris Lattner4b009652007-07-25 00:24:17 +00001034 // Does it fit in a unsigned long?
1035 if (ResultVal.isIntN(LongSize)) {
1036 // Does it fit in a signed long?
1037 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001038 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001039 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001040 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001041 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001042 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001043 }
1044
Chris Lattner4b009652007-07-25 00:24:17 +00001045 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001046 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001047 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001048
Chris Lattner4b009652007-07-25 00:24:17 +00001049 // Does it fit in a unsigned long long?
1050 if (ResultVal.isIntN(LongLongSize)) {
1051 // Does it fit in a signed long long?
1052 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001053 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001054 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001055 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001056 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001057 }
1058 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001059
Chris Lattner4b009652007-07-25 00:24:17 +00001060 // If we still couldn't decide a type, we probably have something that
1061 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001062 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001063 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001064 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001065 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001066 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001067
Chris Lattnere4068872008-05-09 05:59:00 +00001068 if (ResultVal.getBitWidth() != Width)
1069 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001070 }
Sebastian Redl75324932009-01-20 22:23:13 +00001071 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001072 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001073
Chris Lattner1de66eb2007-08-26 03:42:43 +00001074 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1075 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001076 Res = new (Context) ImaginaryLiteral(Res,
1077 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001078
1079 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001080}
1081
Sebastian Redlcd883f72009-01-18 18:53:16 +00001082Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1083 SourceLocation R, ExprArg Val) {
1084 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001085 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001086 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001087}
1088
1089/// The UsualUnaryConversions() function is *not* called by this routine.
1090/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001091bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1092 SourceLocation OpLoc,
1093 const SourceRange &ExprRange,
1094 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001095 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001096 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001097 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001098 if (isSizeof)
1099 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1100 return false;
1101 }
1102
1103 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001104 Diag(OpLoc, diag::ext_sizeof_void_type)
1105 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001106 return false;
1107 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001108
Chris Lattner159fe082009-01-24 19:46:37 +00001109 return DiagnoseIncompleteType(OpLoc, exprType,
1110 isSizeof ? diag::err_sizeof_incomplete_type :
1111 diag::err_alignof_incomplete_type,
1112 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001113}
1114
Chris Lattner8d9f7962009-01-24 20:17:12 +00001115bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1116 const SourceRange &ExprRange) {
1117 E = E->IgnoreParens();
1118
1119 // alignof decl is always ok.
1120 if (isa<DeclRefExpr>(E))
1121 return false;
1122
1123 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1124 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1125 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001126 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001127 return true;
1128 }
1129 // Other fields are ok.
1130 return false;
1131 }
1132 }
1133 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1134}
1135
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001136/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1137/// the same for @c alignof and @c __alignof
1138/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001139Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001140Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1141 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001142 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001143 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001144
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001145 QualType ArgTy;
1146 SourceRange Range;
1147 if (isType) {
1148 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1149 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001150
1151 // Verify that the operand is valid.
1152 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1153 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001154 } else {
1155 // Get the end location.
1156 Expr *ArgEx = (Expr *)TyOrEx;
1157 Range = ArgEx->getSourceRange();
1158 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001159
1160 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001161 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001162 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001163 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001164 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1165 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1166 isInvalid = true;
1167 } else {
1168 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1169 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001170
1171 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001172 DeleteExpr(ArgEx);
1173 return ExprError();
1174 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001175 }
1176
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001177 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001178 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001179 Context.getSizeType(), OpLoc,
1180 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001181}
1182
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001183QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Chris Lattner03931a72007-08-24 21:16:53 +00001184 DefaultFunctionArrayConversion(V);
1185
Chris Lattnera16e42d2007-08-26 05:39:26 +00001186 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001187 if (const ComplexType *CT = V->getType()->getAsComplexType())
1188 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001189
1190 // Otherwise they pass through real integer and floating point types here.
1191 if (V->getType()->isArithmeticType())
1192 return V->getType();
1193
1194 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001195 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1196 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001197 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001198}
1199
1200
Chris Lattner4b009652007-07-25 00:24:17 +00001201
Sebastian Redl8b769972009-01-19 00:08:26 +00001202Action::OwningExprResult
1203Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1204 tok::TokenKind Kind, ExprArg Input) {
1205 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001206
Chris Lattner4b009652007-07-25 00:24:17 +00001207 UnaryOperator::Opcode Opc;
1208 switch (Kind) {
1209 default: assert(0 && "Unknown unary op!");
1210 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1211 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1212 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001213
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001214 if (getLangOptions().CPlusPlus &&
1215 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1216 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001217 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001218 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1219
1220 // C++ [over.inc]p1:
1221 //
1222 // [...] If the function is a member function with one
1223 // parameter (which shall be of type int) or a non-member
1224 // function with two parameters (the second of which shall be
1225 // of type int), it defines the postfix increment operator ++
1226 // for objects of that type. When the postfix increment is
1227 // called as a result of using the ++ operator, the int
1228 // argument will have value zero.
1229 Expr *Args[2] = {
1230 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001231 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1232 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001233 };
1234
1235 // Build the candidate set for overloading
1236 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001237 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1238 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001239
1240 // Perform overload resolution.
1241 OverloadCandidateSet::iterator Best;
1242 switch (BestViableFunction(CandidateSet, Best)) {
1243 case OR_Success: {
1244 // We found a built-in operator or an overloaded operator.
1245 FunctionDecl *FnDecl = Best->Function;
1246
1247 if (FnDecl) {
1248 // We matched an overloaded operator. Build a call to that
1249 // operator.
1250
1251 // Convert the arguments.
1252 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1253 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001254 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001255 } else {
1256 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001257 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001258 FnDecl->getParamDecl(0)->getType(),
1259 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001260 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001261 }
1262
1263 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001264 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001265 = FnDecl->getType()->getAsFunctionType()->getResultType();
1266 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001267
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001268 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001269 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001270 SourceLocation());
1271 UsualUnaryConversions(FnExpr);
1272
Sebastian Redl8b769972009-01-19 00:08:26 +00001273 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001274 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1275 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001276 } else {
1277 // We matched a built-in operator. Convert the arguments, then
1278 // break out so that we will build the appropriate built-in
1279 // operator node.
1280 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1281 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001282 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001283
1284 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001285 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001286 }
1287
1288 case OR_No_Viable_Function:
1289 // No viable function; fall through to handling this as a
1290 // built-in operator, which will produce an error message for us.
1291 break;
1292
1293 case OR_Ambiguous:
1294 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1295 << UnaryOperator::getOpcodeStr(Opc)
1296 << Arg->getSourceRange();
1297 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001298 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001299 }
1300
1301 // Either we found no viable overloaded operator or we matched a
1302 // built-in operator. In either case, fall through to trying to
1303 // build a built-in operation.
1304 }
1305
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001306 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1307 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001308 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001309 return ExprError();
1310 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001311 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001312}
1313
Sebastian Redl8b769972009-01-19 00:08:26 +00001314Action::OwningExprResult
1315Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1316 ExprArg Idx, SourceLocation RLoc) {
1317 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1318 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001319
Douglas Gregor80723c52008-11-19 17:17:41 +00001320 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001321 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001322 LHSExp->getType()->isEnumeralType() ||
1323 RHSExp->getType()->isRecordType() ||
1324 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001325 // Add the appropriate overloaded operators (C++ [over.match.oper])
1326 // to the candidate set.
1327 OverloadCandidateSet CandidateSet;
1328 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001329 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1330 SourceRange(LLoc, RLoc)))
1331 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001332
Douglas Gregor80723c52008-11-19 17:17:41 +00001333 // Perform overload resolution.
1334 OverloadCandidateSet::iterator Best;
1335 switch (BestViableFunction(CandidateSet, Best)) {
1336 case OR_Success: {
1337 // We found a built-in operator or an overloaded operator.
1338 FunctionDecl *FnDecl = Best->Function;
1339
1340 if (FnDecl) {
1341 // We matched an overloaded operator. Build a call to that
1342 // operator.
1343
1344 // Convert the arguments.
1345 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1346 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1347 PerformCopyInitialization(RHSExp,
1348 FnDecl->getParamDecl(0)->getType(),
1349 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001350 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001351 } else {
1352 // Convert the arguments.
1353 if (PerformCopyInitialization(LHSExp,
1354 FnDecl->getParamDecl(0)->getType(),
1355 "passing") ||
1356 PerformCopyInitialization(RHSExp,
1357 FnDecl->getParamDecl(1)->getType(),
1358 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001359 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001360 }
1361
1362 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001363 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001364 = FnDecl->getType()->getAsFunctionType()->getResultType();
1365 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001366
Douglas Gregor80723c52008-11-19 17:17:41 +00001367 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001368 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001369 SourceLocation());
1370 UsualUnaryConversions(FnExpr);
1371
Sebastian Redl8b769972009-01-19 00:08:26 +00001372 Base.release();
1373 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001374 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001375 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001376 } else {
1377 // We matched a built-in operator. Convert the arguments, then
1378 // break out so that we will build the appropriate built-in
1379 // operator node.
1380 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1381 "passing") ||
1382 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1383 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001384 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001385
1386 break;
1387 }
1388 }
1389
1390 case OR_No_Viable_Function:
1391 // No viable function; fall through to handling this as a
1392 // built-in operator, which will produce an error message for us.
1393 break;
1394
1395 case OR_Ambiguous:
1396 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1397 << "[]"
1398 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1399 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001400 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001401 }
1402
1403 // Either we found no viable overloaded operator or we matched a
1404 // built-in operator. In either case, fall through to trying to
1405 // build a built-in operation.
1406 }
1407
Chris Lattner4b009652007-07-25 00:24:17 +00001408 // Perform default conversions.
1409 DefaultFunctionArrayConversion(LHSExp);
1410 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001411
Chris Lattner4b009652007-07-25 00:24:17 +00001412 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1413
1414 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001415 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001416 // in the subscript position. As a result, we need to derive the array base
1417 // and index from the expression types.
1418 Expr *BaseExpr, *IndexExpr;
1419 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001420 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001421 BaseExpr = LHSExp;
1422 IndexExpr = RHSExp;
1423 // FIXME: need to deal with const...
1424 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001425 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001426 // Handle the uncommon case of "123[Ptr]".
1427 BaseExpr = RHSExp;
1428 IndexExpr = LHSExp;
1429 // FIXME: need to deal with const...
1430 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001431 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1432 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001433 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001434
Chris Lattner4b009652007-07-25 00:24:17 +00001435 // FIXME: need to deal with const...
1436 ResultType = VTy->getElementType();
1437 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001438 return ExprError(Diag(LHSExp->getLocStart(),
1439 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1440 }
Chris Lattner4b009652007-07-25 00:24:17 +00001441 // C99 6.5.2.1p1
1442 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001443 return ExprError(Diag(IndexExpr->getLocStart(),
1444 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001445
1446 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1447 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001448 // void (*)(int)) and pointers to incomplete types. Functions are not
1449 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001450 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001451 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001452 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001453 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001454
Sebastian Redl8b769972009-01-19 00:08:26 +00001455 Base.release();
1456 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001457 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1458 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001459}
1460
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001461QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001462CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001463 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001464 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001465
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001466 // The vector accessor can't exceed the number of elements.
1467 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001468
1469 // This flag determines whether or not the component is one of the four
1470 // special names that indicate a subset of exactly half the elements are
1471 // to be selected.
1472 bool HalvingSwizzle = false;
1473
1474 // This flag determines whether or not CompName has an 's' char prefix,
1475 // indicating that it is a string of hex values to be used as vector indices.
1476 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001477
1478 // Check that we've found one of the special components, or that the component
1479 // names must come from the same set.
1480 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001481 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1482 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001483 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001484 do
1485 compStr++;
1486 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001487 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001488 do
1489 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001490 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001491 }
Nate Begeman1486b502009-01-18 01:47:54 +00001492
1493 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001494 // We didn't get to the end of the string. This means the component names
1495 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001496 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1497 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001498 return QualType();
1499 }
Nate Begeman1486b502009-01-18 01:47:54 +00001500
1501 // Ensure no component accessor exceeds the width of the vector type it
1502 // operates on.
1503 if (!HalvingSwizzle) {
1504 compStr = CompName.getName();
1505
1506 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001507 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001508
1509 while (*compStr) {
1510 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1511 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1512 << baseType << SourceRange(CompLoc);
1513 return QualType();
1514 }
1515 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001516 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001517
Nate Begeman1486b502009-01-18 01:47:54 +00001518 // If this is a halving swizzle, verify that the base type has an even
1519 // number of elements.
1520 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001521 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001522 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001523 return QualType();
1524 }
1525
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001526 // The component accessor looks fine - now we need to compute the actual type.
1527 // The vector type is implied by the component accessor. For example,
1528 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001529 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001530 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001531 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1532 : CompName.getLength();
1533 if (HexSwizzle)
1534 CompSize--;
1535
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001536 if (CompSize == 1)
1537 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001538
Nate Begemanaf6ed502008-04-18 23:10:10 +00001539 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001540 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001541 // diagostics look bad. We want extended vector types to appear built-in.
1542 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1543 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1544 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001545 }
1546 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001547}
1548
Chris Lattner2cb744b2009-02-15 22:43:40 +00001549
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001550/// constructSetterName - Return the setter name for the given
1551/// identifier, i.e. "set" + Name where the initial character of Name
1552/// has been capitalized.
1553// FIXME: Merge with same routine in Parser. But where should this
1554// live?
1555static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1556 const IdentifierInfo *Name) {
1557 llvm::SmallString<100> SelectorName;
1558 SelectorName = "set";
1559 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1560 SelectorName[3] = toupper(SelectorName[3]);
1561 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1562}
1563
Sebastian Redl8b769972009-01-19 00:08:26 +00001564Action::OwningExprResult
1565Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1566 tok::TokenKind OpKind, SourceLocation MemberLoc,
1567 IdentifierInfo &Member) {
1568 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001569 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001570
1571 // Perform default conversions.
1572 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001573
Steve Naroff2cb66382007-07-26 03:11:44 +00001574 QualType BaseType = BaseExpr->getType();
1575 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001576
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001577 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1578 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001579 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001580 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001581 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001582 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001583 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1584 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001585 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001586 return ExprError(Diag(MemberLoc,
1587 diag::err_typecheck_member_reference_arrow)
1588 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001589 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001590
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001591 // Handle field access to simple records. This also handles access to fields
1592 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001593 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001594 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001595 if (DiagnoseIncompleteType(OpLoc, BaseType,
1596 diag::err_typecheck_incomplete_tag,
1597 BaseExpr->getSourceRange()))
1598 return ExprError();
1599
Steve Naroff2cb66382007-07-26 03:11:44 +00001600 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001601 // FIXME: Qualified name lookup for C++ is a bit more complicated
1602 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001603 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001604 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001605 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001606
Douglas Gregor09be81b2009-02-04 17:27:36 +00001607 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001608 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001609 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1610 << &Member << BaseExpr->getSourceRange());
1611 else if (Result.isAmbiguous()) {
1612 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1613 MemberLoc, BaseExpr->getSourceRange());
1614 return ExprError();
1615 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001616 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001617
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001618 // If the decl being referenced had an error, return an error for this
1619 // sub-expr without emitting another error, in order to avoid cascading
1620 // error cases.
1621 if (MemberDecl->isInvalidDecl())
1622 return ExprError();
Chris Lattnerb63f8132009-02-16 17:07:21 +00001623
1624 // Check if referencing a field with __attribute__((deprecated)).
1625 DiagnoseUseOfDeprecatedDecl(MemberDecl, MemberLoc);
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001626
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001627 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001628 // We may have found a field within an anonymous union or struct
1629 // (C++ [class.union]).
1630 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001631 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001632 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001633
Douglas Gregor82d44772008-12-20 23:49:58 +00001634 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1635 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001636 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001637 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1638 MemberType = Ref->getPointeeType();
1639 else {
1640 unsigned combinedQualifiers =
1641 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001642 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001643 combinedQualifiers &= ~QualType::Const;
1644 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1645 }
Eli Friedman76b49832008-02-06 22:48:16 +00001646
Steve Naroff774e4152009-01-21 00:14:39 +00001647 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1648 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001649 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001650 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001651 Var, MemberLoc,
1652 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001653 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001654 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1655 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001656 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001657 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001658 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001659 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001660 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001661 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001662 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001663 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001664 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1665 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001666
Douglas Gregor82d44772008-12-20 23:49:58 +00001667 // We found a declaration kind that we didn't expect. This is a
1668 // generic error message that tells the user that she can't refer
1669 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001670 return ExprError(Diag(MemberLoc,
1671 diag::err_typecheck_member_reference_unknown)
1672 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001673 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001674
Chris Lattnere9d71612008-07-21 04:59:05 +00001675 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1676 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001677 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001678 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001679 // If the decl being referenced had an error, return an error for this
1680 // sub-expr without emitting another error, in order to avoid cascading
1681 // error cases.
1682 if (IV->isInvalidDecl())
1683 return ExprError();
1684
Chris Lattner2a3bef92009-02-16 17:19:12 +00001685 // Check if referencing a field with __attribute__((deprecated)).
1686 DiagnoseUseOfDeprecatedDecl(IV, MemberLoc);
1687
Steve Naroff774e4152009-01-21 00:14:39 +00001688 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1689 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001690 OpKind == tok::arrow);
1691 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001692 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001693 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001694 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1695 << IFTy->getDecl()->getDeclName() << &Member
1696 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001697 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001698
Chris Lattnere9d71612008-07-21 04:59:05 +00001699 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1700 // pointer to a (potentially qualified) interface type.
1701 const PointerType *PTy;
1702 const ObjCInterfaceType *IFTy;
1703 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1704 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1705 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001706
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001707 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001708 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
1709 // Check if referencing a property with __attribute__((deprecated)).
1710 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1711
Steve Naroff774e4152009-01-21 00:14:39 +00001712 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001713 MemberLoc, BaseExpr));
1714 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001715
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001716 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001717 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1718 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001719 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1720 // Check if referencing a property with __attribute__((deprecated)).
1721 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1722
Steve Naroff774e4152009-01-21 00:14:39 +00001723 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001724 MemberLoc, BaseExpr));
1725 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001726
1727 // If that failed, look for an "implicit" property by seeing if the nullary
1728 // selector is implemented.
1729
1730 // FIXME: The logic for looking up nullary and unary selectors should be
1731 // shared with the code in ActOnInstanceMessage.
1732
1733 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1734 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001735
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001736 // If this reference is in an @implementation, check for 'private' methods.
1737 if (!Getter)
1738 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1739 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1740 if (ObjCImplementationDecl *ImpDecl =
1741 ObjCImplementations[ClassDecl->getIdentifier()])
1742 Getter = ImpDecl->getInstanceMethod(Sel);
1743
Steve Naroff04151f32008-10-22 19:16:27 +00001744 // Look through local category implementations associated with the class.
1745 if (!Getter) {
1746 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1747 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1748 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1749 }
1750 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001751 if (Getter) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001752 // Check if referencing a property with __attribute__((deprecated)).
1753 DiagnoseUseOfDeprecatedDecl(Getter, MemberLoc);
1754
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001755 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001756 // will look for the matching setter, in case it is needed.
1757 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1758 &Member);
1759 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1760 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1761 if (!Setter) {
1762 // If this reference is in an @implementation, also check for 'private'
1763 // methods.
1764 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1765 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1766 if (ObjCImplementationDecl *ImpDecl =
1767 ObjCImplementations[ClassDecl->getIdentifier()])
1768 Setter = ImpDecl->getInstanceMethod(SetterSel);
1769 }
1770 // Look through local category implementations associated with the class.
1771 if (!Setter) {
1772 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1773 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1774 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1775 }
1776 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001777
Chris Lattner51f6fb32009-02-16 18:35:08 +00001778 if (Setter)
1779 // Check if referencing a property with __attribute__((deprecated)).
1780 DiagnoseUseOfDeprecatedDecl(Setter, MemberLoc);
1781
1782
Sebastian Redl8b769972009-01-19 00:08:26 +00001783 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001784 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1785 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001786 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001787
1788 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1789 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001790 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001791 // Handle properties on qualified "id" protocols.
1792 const ObjCQualifiedIdType *QIdTy;
1793 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1794 // Check protocols on qualified interfaces.
1795 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001796 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001797 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1798 // Check if referencing a property with __attribute__((deprecated)).
1799 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1800
Steve Naroff774e4152009-01-21 00:14:39 +00001801 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001802 MemberLoc, BaseExpr));
1803 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001804 // Also must look for a getter name which uses property syntax.
1805 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1806 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001807 // Check if referencing a property with __attribute__((deprecated)).
1808 DiagnoseUseOfDeprecatedDecl(OMD, MemberLoc);
1809
Steve Naroff774e4152009-01-21 00:14:39 +00001810 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1811 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001812 }
1813 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001814
1815 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1816 << &Member << BaseType);
1817 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001818 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001819 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001820 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1821 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001822 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001823 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1824 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001825 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001826
1827 return ExprError(Diag(MemberLoc,
1828 diag::err_typecheck_member_reference_struct_union)
1829 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001830}
1831
Douglas Gregor3257fb52008-12-22 05:46:06 +00001832/// ConvertArgumentsForCall - Converts the arguments specified in
1833/// Args/NumArgs to the parameter types of the function FDecl with
1834/// function prototype Proto. Call is the call expression itself, and
1835/// Fn is the function expression. For a C++ member function, this
1836/// routine does not attempt to convert the object argument. Returns
1837/// true if the call is ill-formed.
1838bool
1839Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1840 FunctionDecl *FDecl,
1841 const FunctionTypeProto *Proto,
1842 Expr **Args, unsigned NumArgs,
1843 SourceLocation RParenLoc) {
1844 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1845 // assignment, to the types of the corresponding parameter, ...
1846 unsigned NumArgsInProto = Proto->getNumArgs();
1847 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001848 bool Invalid = false;
1849
Douglas Gregor3257fb52008-12-22 05:46:06 +00001850 // If too few arguments are available (and we don't have default
1851 // arguments for the remaining parameters), don't make the call.
1852 if (NumArgs < NumArgsInProto) {
1853 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1854 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1855 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1856 // Use default arguments for missing arguments
1857 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001858 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001859 }
1860
1861 // If too many are passed and not variadic, error on the extras and drop
1862 // them.
1863 if (NumArgs > NumArgsInProto) {
1864 if (!Proto->isVariadic()) {
1865 Diag(Args[NumArgsInProto]->getLocStart(),
1866 diag::err_typecheck_call_too_many_args)
1867 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1868 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1869 Args[NumArgs-1]->getLocEnd());
1870 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001871 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001872 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001873 }
1874 NumArgsToCheck = NumArgsInProto;
1875 }
1876
1877 // Continue to check argument types (even if we have too few/many args).
1878 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1879 QualType ProtoArgType = Proto->getArgType(i);
1880
1881 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001882 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001883 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001884
1885 // Pass the argument.
1886 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1887 return true;
1888 } else
1889 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001890 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001891 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001892
Douglas Gregor3257fb52008-12-22 05:46:06 +00001893 Call->setArg(i, Arg);
1894 }
1895
1896 // If this is a variadic call, handle args passed through "...".
1897 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001898 VariadicCallType CallType = VariadicFunction;
1899 if (Fn->getType()->isBlockPointerType())
1900 CallType = VariadicBlock; // Block
1901 else if (isa<MemberExpr>(Fn))
1902 CallType = VariadicMethod;
1903
Douglas Gregor3257fb52008-12-22 05:46:06 +00001904 // Promote the arguments (C99 6.5.2.2p7).
1905 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1906 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001907 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001908 Call->setArg(i, Arg);
1909 }
1910 }
1911
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001912 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001913}
1914
Steve Naroff87d58b42007-09-16 03:34:24 +00001915/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001916/// This provides the location of the left/right parens and a list of comma
1917/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001918Action::OwningExprResult
1919Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1920 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001921 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001922 unsigned NumArgs = args.size();
1923 Expr *Fn = static_cast<Expr *>(fn.release());
1924 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001925 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001926 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001927 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001928
Douglas Gregor3257fb52008-12-22 05:46:06 +00001929 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001930 // Determine whether this is a dependent call inside a C++ template,
1931 // in which case we won't do any semantic analysis now.
1932 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1933 bool Dependent = false;
1934 if (Fn->isTypeDependent())
1935 Dependent = true;
1936 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1937 Dependent = true;
1938
1939 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001940 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001941 Context.DependentTy, RParenLoc));
1942
1943 // Determine whether this is a call to an object (C++ [over.call.object]).
1944 if (Fn->getType()->isRecordType())
1945 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1946 CommaLocs, RParenLoc));
1947
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001948 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001949 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1950 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1951 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001952 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1953 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001954 }
1955
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001956 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001957 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001958 Expr *FnExpr = Fn;
1959 bool ADL = true;
1960 while (true) {
1961 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1962 FnExpr = IcExpr->getSubExpr();
1963 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001964 // Parentheses around a function disable ADL
1965 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001966 ADL = false;
1967 FnExpr = PExpr->getSubExpr();
1968 } else if (isa<UnaryOperator>(FnExpr) &&
1969 cast<UnaryOperator>(FnExpr)->getOpcode()
1970 == UnaryOperator::AddrOf) {
1971 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001972 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1973 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1974 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1975 break;
1976 } else if (UnresolvedFunctionNameExpr *DepName
1977 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1978 UnqualifiedName = DepName->getName();
1979 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001980 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001981 // Any kind of name that does not refer to a declaration (or
1982 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1983 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001984 break;
1985 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001986 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001987
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001988 OverloadedFunctionDecl *Ovl = 0;
1989 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001990 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001991 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1992 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001993
Douglas Gregorfcb19192009-02-11 23:02:49 +00001994 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001995 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00001996 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001997 ADL = false;
1998
Douglas Gregorfcb19192009-02-11 23:02:49 +00001999 // We don't perform ADL in C.
2000 if (!getLangOptions().CPlusPlus)
2001 ADL = false;
2002
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002003 if (Ovl || ADL) {
2004 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2005 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002006 NumArgs, CommaLocs, RParenLoc, ADL);
2007 if (!FDecl)
2008 return ExprError();
2009
2010 // Update Fn to refer to the actual function selected.
2011 Expr *NewFn = 0;
2012 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002013 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002014 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2015 QDRExpr->getLocation(),
2016 false, false,
2017 QDRExpr->getSourceRange().getBegin());
2018 else
2019 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2020 Fn->getSourceRange().getBegin());
2021 Fn->Destroy(Context);
2022 Fn = NewFn;
2023 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002024 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002025
2026 // Promote the function operand.
2027 UsualUnaryConversions(Fn);
2028
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002029 // Make the call expr early, before semantic checks. This guarantees cleanup
2030 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00002031 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
2032 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002033 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2034 Args, NumArgs,
2035 Context.BoolTy,
2036 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002037
Steve Naroffd6163f32008-09-05 22:11:13 +00002038 const FunctionType *FuncT;
2039 if (!Fn->getType()->isBlockPointerType()) {
2040 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2041 // have type pointer to function".
2042 const PointerType *PT = Fn->getType()->getAsPointerType();
2043 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002044 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2045 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002046 FuncT = PT->getPointeeType()->getAsFunctionType();
2047 } else { // This is a block call.
2048 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2049 getAsFunctionType();
2050 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002051 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002052 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2053 << Fn->getType() << Fn->getSourceRange());
2054
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002055 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002056 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002057
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002058 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002059 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2060 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002061 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002062 } else {
2063 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002064
Steve Naroffdb65e052007-08-28 23:30:39 +00002065 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002066 for (unsigned i = 0; i != NumArgs; i++) {
2067 Expr *Arg = Args[i];
2068 DefaultArgumentPromotion(Arg);
2069 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002070 }
Chris Lattner4b009652007-07-25 00:24:17 +00002071 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002072
Douglas Gregor3257fb52008-12-22 05:46:06 +00002073 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2074 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002075 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2076 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002077
Chris Lattner2e64c072007-08-10 20:18:51 +00002078 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002079 if (FDecl)
2080 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002081
Sebastian Redl8b769972009-01-19 00:08:26 +00002082 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002083}
2084
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002085Action::OwningExprResult
2086Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2087 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002088 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002089 QualType literalType = QualType::getFromOpaquePtr(Ty);
2090 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002091 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002092 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002093
Eli Friedman8c2173d2008-05-20 05:22:08 +00002094 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002095 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002096 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2097 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002098 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2099 diag::err_typecheck_decl_incomplete_type,
2100 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002101 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002102
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002103 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002104 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002105 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002106
Chris Lattnere5cb5862008-12-04 23:50:19 +00002107 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002108 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002109 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002110 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002111 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002112 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002113 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2114 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002115}
2116
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002117Action::OwningExprResult
2118Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2119 InitListDesignations &Designators,
2120 SourceLocation RBraceLoc) {
2121 unsigned NumInit = initlist.size();
2122 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002123
Steve Naroff0acc9c92007-09-15 18:49:24 +00002124 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002125 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002126
Steve Naroff774e4152009-01-21 00:14:39 +00002127 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002128 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002129 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002130 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002131}
2132
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002133/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002134bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002135 UsualUnaryConversions(castExpr);
2136
2137 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2138 // type needs to be scalar.
2139 if (castType->isVoidType()) {
2140 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002141 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2142 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002143 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002144 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2145 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2146 (castType->isStructureType() || castType->isUnionType())) {
2147 // GCC struct/union extension: allow cast to self.
2148 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2149 << castType << castExpr->getSourceRange();
2150 } else if (castType->isUnionType()) {
2151 // GCC cast to union extension
2152 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2153 RecordDecl::field_iterator Field, FieldEnd;
2154 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2155 Field != FieldEnd; ++Field) {
2156 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2157 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2158 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2159 << castExpr->getSourceRange();
2160 break;
2161 }
2162 }
2163 if (Field == FieldEnd)
2164 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2165 << castExpr->getType() << castExpr->getSourceRange();
2166 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002167 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002168 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002169 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002170 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002171 } else if (!castExpr->getType()->isScalarType() &&
2172 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002173 return Diag(castExpr->getLocStart(),
2174 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002175 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002176 } else if (castExpr->getType()->isVectorType()) {
2177 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2178 return true;
2179 } else if (castType->isVectorType()) {
2180 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2181 return true;
2182 }
2183 return false;
2184}
2185
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002186bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002187 assert(VectorTy->isVectorType() && "Not a vector type!");
2188
2189 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002190 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002191 return Diag(R.getBegin(),
2192 Ty->isVectorType() ?
2193 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002194 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002195 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002196 } else
2197 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002198 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002199 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002200
2201 return false;
2202}
2203
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002204Action::OwningExprResult
2205Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2206 SourceLocation RParenLoc, ExprArg Op) {
2207 assert((Ty != 0) && (Op.get() != 0) &&
2208 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002209
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002210 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002211 QualType castType = QualType::getFromOpaquePtr(Ty);
2212
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002213 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002214 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002215 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002216 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002217}
2218
Chris Lattner98a425c2007-11-26 01:40:58 +00002219/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2220/// In that case, lex = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002221/// C99 6.5.15
2222QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2223 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002224 UsualUnaryConversions(Cond);
2225 UsualUnaryConversions(LHS);
2226 UsualUnaryConversions(RHS);
2227 QualType CondTy = Cond->getType();
2228 QualType LHSTy = LHS->getType();
2229 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002230
2231 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002232 if (!Cond->isTypeDependent()) {
2233 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2234 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2235 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002236 return QualType();
2237 }
Chris Lattner4b009652007-07-25 00:24:17 +00002238 }
Chris Lattner992ae932008-01-06 22:42:25 +00002239
2240 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002241 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002242 return Context.DependentTy;
2243
Chris Lattner992ae932008-01-06 22:42:25 +00002244 // If both operands have arithmetic type, do the usual arithmetic conversions
2245 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002246 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2247 UsualArithmeticConversions(LHS, RHS);
2248 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002249 }
Chris Lattner992ae932008-01-06 22:42:25 +00002250
2251 // If both operands are the same structure or union type, the result is that
2252 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002253 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2254 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002255 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002256 // "If both the operands have structure or union type, the result has
2257 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002258 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002259 }
Chris Lattner992ae932008-01-06 22:42:25 +00002260
2261 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002262 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002263 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2264 if (!LHSTy->isVoidType())
2265 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2266 << RHS->getSourceRange();
2267 if (!RHSTy->isVoidType())
2268 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2269 << LHS->getSourceRange();
2270 ImpCastExprToType(LHS, Context.VoidTy);
2271 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002272 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002273 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002274 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2275 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002276 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2277 Context.isObjCObjectPointerType(LHSTy)) &&
2278 RHS->isNullPointerConstant(Context)) {
2279 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2280 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002281 }
Chris Lattnere2897262009-02-18 04:28:32 +00002282 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2283 Context.isObjCObjectPointerType(RHSTy)) &&
2284 LHS->isNullPointerConstant(Context)) {
2285 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2286 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002287 }
Chris Lattner9c039b52009-02-18 04:38:20 +00002288
Chris Lattner0ac51632008-01-06 22:50:31 +00002289 // Handle the case where both operands are pointers before we handle null
2290 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002291 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2292 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002293 // get the "pointed to" types
2294 QualType lhptee = LHSPT->getPointeeType();
2295 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002296
Chris Lattner71225142007-07-31 21:27:01 +00002297 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2298 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002299 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002300 // Figure out necessary qualifiers (C99 6.5.15p6)
2301 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002302 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002303 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2304 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002305 return destType;
2306 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002307 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002308 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002309 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002310 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2311 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002312 return destType;
2313 }
Chris Lattner4b009652007-07-25 00:24:17 +00002314
Chris Lattner9c039b52009-02-18 04:38:20 +00002315 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2316 // Two identical pointers types are always compatible.
2317 return LHSTy;
2318 }
2319
Chris Lattnere2897262009-02-18 04:28:32 +00002320 QualType compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002321
2322 // If either type is an Objective-C object type then check
2323 // compatibility according to Objective-C.
Chris Lattnere2897262009-02-18 04:28:32 +00002324 if (Context.isObjCObjectPointerType(LHSTy) ||
2325 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002326 // If both operands are interfaces and either operand can be
2327 // assigned to the other, use that type as the composite
2328 // type. This allows
2329 // xxx ? (A*) a : (B*) b
2330 // where B is a subclass of A.
2331 //
2332 // Additionally, as for assignment, if either type is 'id'
2333 // allow silent coercion. Finally, if the types are
2334 // incompatible then make sure to use 'id' as the composite
2335 // type so the result is acceptable for sending messages to.
2336
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002337 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2338 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002339 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2340 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2341 if (LHSIface && RHSIface &&
2342 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002343 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002344 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002345 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002346 compositeType = RHSTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002347 } else if (Context.isObjCIdStructType(lhptee) ||
2348 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002349 compositeType = Context.getObjCIdType();
2350 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002351 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2352 << LHSTy << RHSTy
2353 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002354 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002355 ImpCastExprToType(LHS, incompatTy);
2356 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002357 return incompatTy;
2358 }
2359 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2360 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002361 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2362 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002363 // In this situation, we assume void* type. No especially good
2364 // reason, but this is what gcc does, and we do have to pick
2365 // to get a consistent AST.
2366 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002367 ImpCastExprToType(LHS, incompatTy);
2368 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002369 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002370 }
2371 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002372 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2373 // differently qualified versions of compatible types, the result type is
2374 // a pointer to an appropriately qualified version of the *composite*
2375 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002376 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002377 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002378 ImpCastExprToType(LHS, compositeType);
2379 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002380 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002381 }
Chris Lattner4b009652007-07-25 00:24:17 +00002382 }
Chris Lattner9c039b52009-02-18 04:38:20 +00002383
2384 // Selection between block pointer types is ok as long as they are the same.
2385 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2386 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2387 return LHSTy;
2388
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002389 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2390 // evaluates to "struct objc_object *" (and is handled above when comparing
2391 // id with statically typed objects).
Chris Lattnere2897262009-02-18 04:28:32 +00002392 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002393 // GCC allows qualified id and any Objective-C type to devolve to
2394 // id. Currently localizing to here until clear this should be
2395 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002396 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
2397 (LHSTy->isObjCQualifiedIdType() &&
2398 Context.isObjCObjectPointerType(RHSTy)) ||
2399 (RHSTy->isObjCQualifiedIdType() &&
2400 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002401 // FIXME: This is not the correct composite type. This only
2402 // happens to work because id can more or less be used anywhere,
2403 // however this may change the type of method sends.
2404 // FIXME: gcc adds some type-checking of the arguments and emits
2405 // (confusing) incompatible comparison warnings in some
2406 // cases. Investigate.
2407 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002408 ImpCastExprToType(LHS, compositeType);
2409 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002410 return compositeType;
2411 }
2412 }
2413
Chris Lattner992ae932008-01-06 22:42:25 +00002414 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002415 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2416 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002417 return QualType();
2418}
2419
Steve Naroff87d58b42007-09-16 03:34:24 +00002420/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002421/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002422Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2423 SourceLocation ColonLoc,
2424 ExprArg Cond, ExprArg LHS,
2425 ExprArg RHS) {
2426 Expr *CondExpr = (Expr *) Cond.get();
2427 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002428
2429 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2430 // was the condition.
2431 bool isLHSNull = LHSExpr == 0;
2432 if (isLHSNull)
2433 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002434
2435 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002436 RHSExpr, QuestionLoc);
2437 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002438 return ExprError();
2439
2440 Cond.release();
2441 LHS.release();
2442 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002443 return Owned(new (Context) ConditionalOperator(CondExpr,
2444 isLHSNull ? 0 : LHSExpr,
2445 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002446}
2447
Chris Lattner4b009652007-07-25 00:24:17 +00002448
2449// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2450// being closely modeled after the C99 spec:-). The odd characteristic of this
2451// routine is it effectively iqnores the qualifiers on the top level pointee.
2452// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2453// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002454Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002455Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2456 QualType lhptee, rhptee;
2457
2458 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002459 lhptee = lhsType->getAsPointerType()->getPointeeType();
2460 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002461
2462 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002463 lhptee = Context.getCanonicalType(lhptee);
2464 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002465
Chris Lattner005ed752008-01-04 18:04:52 +00002466 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002467
2468 // C99 6.5.16.1p1: This following citation is common to constraints
2469 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2470 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002471 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002472 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002473 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002474
2475 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2476 // incomplete type and the other is a pointer to a qualified or unqualified
2477 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002478 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002479 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002480 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002481
2482 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002483 assert(rhptee->isFunctionType());
2484 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002485 }
2486
2487 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002488 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002489 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002490
2491 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002492 assert(lhptee->isFunctionType());
2493 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002494 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002495
2496 // Check for ObjC interfaces
2497 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2498 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2499 if (LHSIface && RHSIface &&
2500 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2501 return ConvTy;
2502
2503 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002504 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002505 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002506 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002507 return ConvTy;
2508
Chris Lattner4b009652007-07-25 00:24:17 +00002509 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2510 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002511 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2512 rhptee.getUnqualifiedType()))
2513 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002514 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002515}
2516
Steve Naroff3454b6c2008-09-04 15:10:53 +00002517/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2518/// block pointer types are compatible or whether a block and normal pointer
2519/// are compatible. It is more restrict than comparing two function pointer
2520// types.
2521Sema::AssignConvertType
2522Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2523 QualType rhsType) {
2524 QualType lhptee, rhptee;
2525
2526 // get the "pointed to" type (ignoring qualifiers at the top level)
2527 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2528 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2529
2530 // make sure we operate on the canonical type
2531 lhptee = Context.getCanonicalType(lhptee);
2532 rhptee = Context.getCanonicalType(rhptee);
2533
2534 AssignConvertType ConvTy = Compatible;
2535
2536 // For blocks we enforce that qualifiers are identical.
2537 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2538 ConvTy = CompatiblePointerDiscardsQualifiers;
2539
2540 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2541 return IncompatibleBlockPointer;
2542 return ConvTy;
2543}
2544
Chris Lattner4b009652007-07-25 00:24:17 +00002545/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2546/// has code to accommodate several GCC extensions when type checking
2547/// pointers. Here are some objectionable examples that GCC considers warnings:
2548///
2549/// int a, *pint;
2550/// short *pshort;
2551/// struct foo *pfoo;
2552///
2553/// pint = pshort; // warning: assignment from incompatible pointer type
2554/// a = pint; // warning: assignment makes integer from pointer without a cast
2555/// pint = a; // warning: assignment makes pointer from integer without a cast
2556/// pint = pfoo; // warning: assignment from incompatible pointer type
2557///
2558/// As a result, the code for dealing with pointers is more complex than the
2559/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002560///
Chris Lattner005ed752008-01-04 18:04:52 +00002561Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002562Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002563 // Get canonical types. We're not formatting these types, just comparing
2564 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002565 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2566 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002567
2568 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002569 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002570
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002571 // If the left-hand side is a reference type, then we are in a
2572 // (rare!) case where we've allowed the use of references in C,
2573 // e.g., as a parameter type in a built-in function. In this case,
2574 // just make sure that the type referenced is compatible with the
2575 // right-hand side type. The caller is responsible for adjusting
2576 // lhsType so that the resulting expression does not have reference
2577 // type.
2578 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2579 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002580 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002581 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002582 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002583
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002584 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2585 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002586 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002587 // Relax integer conversions like we do for pointers below.
2588 if (rhsType->isIntegerType())
2589 return IntToPointer;
2590 if (lhsType->isIntegerType())
2591 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002592 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002593 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002594
Nate Begemanc5f0f652008-07-14 18:02:46 +00002595 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002596 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002597 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2598 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002599 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002600
Nate Begemanc5f0f652008-07-14 18:02:46 +00002601 // If we are allowing lax vector conversions, and LHS and RHS are both
2602 // vectors, the total size only needs to be the same. This is a bitcast;
2603 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002604 if (getLangOptions().LaxVectorConversions &&
2605 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002606 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002607 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002608 }
2609 return Incompatible;
2610 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002611
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002612 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002613 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002614
Chris Lattner390564e2008-04-07 06:49:41 +00002615 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002616 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002617 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002618
Chris Lattner390564e2008-04-07 06:49:41 +00002619 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002620 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002621
Steve Naroffa982c712008-09-29 18:10:17 +00002622 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002623 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002624 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002625
2626 // Treat block pointers as objects.
2627 if (getLangOptions().ObjC1 &&
2628 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2629 return Compatible;
2630 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002631 return Incompatible;
2632 }
2633
2634 if (isa<BlockPointerType>(lhsType)) {
2635 if (rhsType->isIntegerType())
2636 return IntToPointer;
2637
Steve Naroffa982c712008-09-29 18:10:17 +00002638 // Treat block pointers as objects.
2639 if (getLangOptions().ObjC1 &&
2640 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2641 return Compatible;
2642
Steve Naroff3454b6c2008-09-04 15:10:53 +00002643 if (rhsType->isBlockPointerType())
2644 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2645
2646 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2647 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002648 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002649 }
Chris Lattner1853da22008-01-04 23:18:45 +00002650 return Incompatible;
2651 }
2652
Chris Lattner390564e2008-04-07 06:49:41 +00002653 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002654 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002655 if (lhsType == Context.BoolTy)
2656 return Compatible;
2657
2658 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002659 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002660
Chris Lattner390564e2008-04-07 06:49:41 +00002661 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002662 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002663
2664 if (isa<BlockPointerType>(lhsType) &&
2665 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002666 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002667 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002668 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002669
Chris Lattner1853da22008-01-04 23:18:45 +00002670 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002671 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002672 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002673 }
2674 return Incompatible;
2675}
2676
Chris Lattner005ed752008-01-04 18:04:52 +00002677Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002678Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002679 if (getLangOptions().CPlusPlus) {
2680 if (!lhsType->isRecordType()) {
2681 // C++ 5.17p3: If the left operand is not of class type, the
2682 // expression is implicitly converted (C++ 4) to the
2683 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002684 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2685 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002686 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002687 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002688 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002689 }
2690
2691 // FIXME: Currently, we fall through and treat C++ classes like C
2692 // structures.
2693 }
2694
Steve Naroffcdee22d2007-11-27 17:58:44 +00002695 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2696 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002697 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2698 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002699 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002700 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002701 return Compatible;
2702 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002703
2704 // We don't allow conversion of non-null-pointer constants to integers.
2705 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2706 return IntToBlockPointer;
2707
Chris Lattner5f505bf2007-10-16 02:55:40 +00002708 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002709 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002710 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002711 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002712 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002713 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002714 if (!lhsType->isReferenceType())
2715 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002716
Chris Lattner005ed752008-01-04 18:04:52 +00002717 Sema::AssignConvertType result =
2718 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002719
2720 // C99 6.5.16.1p2: The value of the right operand is converted to the
2721 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002722 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2723 // so that we can use references in built-in functions even in C.
2724 // The getNonReferenceType() call makes sure that the resulting expression
2725 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002726 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002727 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002728 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002729}
2730
Chris Lattner005ed752008-01-04 18:04:52 +00002731Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002732Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2733 return CheckAssignmentConstraints(lhsType, rhsType);
2734}
2735
Chris Lattner1eafdea2008-11-18 01:30:42 +00002736QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002737 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002738 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002739 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002740 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002741}
2742
Chris Lattner1eafdea2008-11-18 01:30:42 +00002743inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002744 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002745 // For conversion purposes, we ignore any qualifiers.
2746 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002747 QualType lhsType =
2748 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2749 QualType rhsType =
2750 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002751
Nate Begemanc5f0f652008-07-14 18:02:46 +00002752 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002753 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002754 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002755
Nate Begemanc5f0f652008-07-14 18:02:46 +00002756 // Handle the case of a vector & extvector type of the same size and element
2757 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002758 if (getLangOptions().LaxVectorConversions) {
2759 // FIXME: Should we warn here?
2760 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002761 if (const VectorType *RV = rhsType->getAsVectorType())
2762 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002763 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002764 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002765 }
2766 }
2767 }
2768
Nate Begemanc5f0f652008-07-14 18:02:46 +00002769 // If the lhs is an extended vector and the rhs is a scalar of the same type
2770 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002771 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002772 QualType eltType = V->getElementType();
2773
2774 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2775 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2776 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002777 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002778 return lhsType;
2779 }
2780 }
2781
Nate Begemanc5f0f652008-07-14 18:02:46 +00002782 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002783 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002784 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002785 QualType eltType = V->getElementType();
2786
2787 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2788 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2789 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002790 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002791 return rhsType;
2792 }
2793 }
2794
Chris Lattner4b009652007-07-25 00:24:17 +00002795 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002796 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002797 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002798 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002799 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002800}
2801
Chris Lattner4b009652007-07-25 00:24:17 +00002802inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002803 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002804{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002805 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002806 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002807
Steve Naroff8f708362007-08-24 19:07:16 +00002808 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002809
Chris Lattner4b009652007-07-25 00:24:17 +00002810 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002811 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002812 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002813}
2814
2815inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002816 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002817{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002818 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2819 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2820 return CheckVectorOperands(Loc, lex, rex);
2821 return InvalidOperands(Loc, lex, rex);
2822 }
Chris Lattner4b009652007-07-25 00:24:17 +00002823
Steve Naroff8f708362007-08-24 19:07:16 +00002824 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002825
Chris Lattner4b009652007-07-25 00:24:17 +00002826 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002827 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002828 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002829}
2830
2831inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002832 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002833{
2834 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002835 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002836
Steve Naroff8f708362007-08-24 19:07:16 +00002837 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002838
Chris Lattner4b009652007-07-25 00:24:17 +00002839 // handle the common case first (both operands are arithmetic).
2840 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002841 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002842
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002843 // Put any potential pointer into PExp
2844 Expr* PExp = lex, *IExp = rex;
2845 if (IExp->getType()->isPointerType())
2846 std::swap(PExp, IExp);
2847
2848 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2849 if (IExp->getType()->isIntegerType()) {
2850 // Check for arithmetic on pointers to incomplete types
2851 if (!PTy->getPointeeType()->isObjectType()) {
2852 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002853 if (getLangOptions().CPlusPlus) {
2854 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2855 << lex->getSourceRange() << rex->getSourceRange();
2856 return QualType();
2857 }
2858
2859 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002860 Diag(Loc, diag::ext_gnu_void_ptr)
2861 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002862 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002863 if (getLangOptions().CPlusPlus) {
2864 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2865 << lex->getType() << lex->getSourceRange();
2866 return QualType();
2867 }
2868
2869 // GNU extension: arithmetic on pointer to function
2870 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002871 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002872 } else {
2873 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2874 diag::err_typecheck_arithmetic_incomplete_type,
2875 lex->getSourceRange(), SourceRange(),
2876 lex->getType());
2877 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002878 }
2879 }
2880 return PExp->getType();
2881 }
2882 }
2883
Chris Lattner1eafdea2008-11-18 01:30:42 +00002884 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002885}
2886
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002887// C99 6.5.6
2888QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002889 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002890 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002891 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002892
Steve Naroff8f708362007-08-24 19:07:16 +00002893 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002894
Chris Lattnerf6da2912007-12-09 21:53:25 +00002895 // Enforce type constraints: C99 6.5.6p3.
2896
2897 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002898 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002899 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002900
2901 // Either ptr - int or ptr - ptr.
2902 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002903 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002904
Chris Lattnerf6da2912007-12-09 21:53:25 +00002905 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002906 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002907 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002908 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002909 Diag(Loc, diag::ext_gnu_void_ptr)
2910 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002911 } else if (lpointee->isFunctionType()) {
2912 if (getLangOptions().CPlusPlus) {
2913 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2914 << lex->getType() << lex->getSourceRange();
2915 return QualType();
2916 }
2917
2918 // GNU extension: arithmetic on pointer to function
2919 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2920 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002921 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002922 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002923 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002924 return QualType();
2925 }
2926 }
2927
2928 // The result type of a pointer-int computation is the pointer type.
2929 if (rex->getType()->isIntegerType())
2930 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002931
Chris Lattnerf6da2912007-12-09 21:53:25 +00002932 // Handle pointer-pointer subtractions.
2933 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002934 QualType rpointee = RHSPTy->getPointeeType();
2935
Chris Lattnerf6da2912007-12-09 21:53:25 +00002936 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002937 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002938 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002939 if (rpointee->isVoidType()) {
2940 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002941 Diag(Loc, diag::ext_gnu_void_ptr)
2942 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002943 } else if (rpointee->isFunctionType()) {
2944 if (getLangOptions().CPlusPlus) {
2945 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2946 << rex->getType() << rex->getSourceRange();
2947 return QualType();
2948 }
2949
2950 // GNU extension: arithmetic on pointer to function
2951 if (!lpointee->isFunctionType())
2952 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2953 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002954 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002955 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002956 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002957 return QualType();
2958 }
2959 }
2960
2961 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002962 if (!Context.typesAreCompatible(
2963 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2964 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002965 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002966 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002967 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002968 return QualType();
2969 }
2970
2971 return Context.getPointerDiffType();
2972 }
2973 }
2974
Chris Lattner1eafdea2008-11-18 01:30:42 +00002975 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002976}
2977
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002978// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002979QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002980 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002981 // C99 6.5.7p2: Each of the operands shall have integer type.
2982 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002983 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002984
Chris Lattner2c8bff72007-12-12 05:47:28 +00002985 // Shifts don't perform usual arithmetic conversions, they just do integer
2986 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002987 if (!isCompAssign)
2988 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002989 UsualUnaryConversions(rex);
2990
2991 // "The type of the result is that of the promoted left operand."
2992 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002993}
2994
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002995// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002996QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002997 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002998 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002999 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003000
Chris Lattner254f3bc2007-08-26 01:18:55 +00003001 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003002 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3003 UsualArithmeticConversions(lex, rex);
3004 else {
3005 UsualUnaryConversions(lex);
3006 UsualUnaryConversions(rex);
3007 }
Chris Lattner4b009652007-07-25 00:24:17 +00003008 QualType lType = lex->getType();
3009 QualType rType = rex->getType();
3010
Ted Kremenek486509e2007-10-29 17:13:39 +00003011 // For non-floating point types, check for self-comparisons of the form
3012 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3013 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003014 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003015 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3016 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003017 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003018 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003019 }
3020
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003021 // The result of comparisons is 'bool' in C++, 'int' in C.
3022 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3023
Chris Lattner254f3bc2007-08-26 01:18:55 +00003024 if (isRelational) {
3025 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003026 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003027 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003028 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003029 if (lType->isFloatingType()) {
3030 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003031 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003032 }
3033
Chris Lattner254f3bc2007-08-26 01:18:55 +00003034 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003035 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003036 }
Chris Lattner4b009652007-07-25 00:24:17 +00003037
Chris Lattner22be8422007-08-26 01:10:14 +00003038 bool LHSIsNull = lex->isNullPointerConstant(Context);
3039 bool RHSIsNull = rex->isNullPointerConstant(Context);
3040
Chris Lattner254f3bc2007-08-26 01:18:55 +00003041 // All of the following pointer related warnings are GCC extensions, except
3042 // when handling null pointer constants. One day, we can consider making them
3043 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003044 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003045 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003046 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003047 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003048 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00003049
Steve Naroff3b435622007-11-13 14:57:38 +00003050 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003051 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3052 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003053 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003054 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003055 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003056 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003057 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003058 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003059 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003060 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003061 // Handle block pointer types.
3062 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3063 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3064 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3065
3066 if (!LHSIsNull && !RHSIsNull &&
3067 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003068 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003069 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003070 }
3071 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003072 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003073 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003074 // Allow block pointers to be compared with null pointer constants.
3075 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3076 (lType->isPointerType() && rType->isBlockPointerType())) {
3077 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003078 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003079 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003080 }
3081 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003082 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003083 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003084
Steve Naroff936c4362008-06-03 14:04:54 +00003085 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003086 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003087 const PointerType *LPT = lType->getAsPointerType();
3088 const PointerType *RPT = rType->getAsPointerType();
3089 bool LPtrToVoid = LPT ?
3090 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3091 bool RPtrToVoid = RPT ?
3092 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3093
3094 if (!LPtrToVoid && !RPtrToVoid &&
3095 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003096 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003097 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003098 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003099 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003100 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003101 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003102 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003103 }
Steve Naroff936c4362008-06-03 14:04:54 +00003104 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3105 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003106 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003107 } else {
3108 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003109 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003110 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003111 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003112 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003113 }
Steve Naroff936c4362008-06-03 14:04:54 +00003114 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003115 }
Steve Naroff936c4362008-06-03 14:04:54 +00003116 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3117 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003118 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003119 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003120 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003121 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003122 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003123 }
Steve Naroff936c4362008-06-03 14:04:54 +00003124 if (lType->isIntegerType() &&
3125 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003126 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003127 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003128 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003129 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003130 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003131 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003132 // Handle block pointers.
3133 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3134 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003135 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003136 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003137 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003138 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003139 }
3140 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3141 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003142 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003143 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003144 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003145 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003146 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003147 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003148}
3149
Nate Begemanc5f0f652008-07-14 18:02:46 +00003150/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3151/// operates on extended vector types. Instead of producing an IntTy result,
3152/// like a scalar comparison, a vector comparison produces a vector of integer
3153/// types.
3154QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003155 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003156 bool isRelational) {
3157 // Check to make sure we're operating on vectors of the same type and width,
3158 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003159 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003160 if (vType.isNull())
3161 return vType;
3162
3163 QualType lType = lex->getType();
3164 QualType rType = rex->getType();
3165
3166 // For non-floating point types, check for self-comparisons of the form
3167 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3168 // often indicate logic errors in the program.
3169 if (!lType->isFloatingType()) {
3170 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3171 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3172 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003173 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003174 }
3175
3176 // Check for comparisons of floating point operands using != and ==.
3177 if (!isRelational && lType->isFloatingType()) {
3178 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003179 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003180 }
3181
3182 // Return the type for the comparison, which is the same as vector type for
3183 // integer vectors, or an integer type of identical size and number of
3184 // elements for floating point vectors.
3185 if (lType->isIntegerType())
3186 return lType;
3187
3188 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003189 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003190 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003191 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003192 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3193 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3194
3195 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3196 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003197 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3198}
3199
Chris Lattner4b009652007-07-25 00:24:17 +00003200inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003201 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003202{
3203 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003204 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003205
Steve Naroff8f708362007-08-24 19:07:16 +00003206 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003207
3208 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003209 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003210 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003211}
3212
3213inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003214 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003215{
3216 UsualUnaryConversions(lex);
3217 UsualUnaryConversions(rex);
3218
Eli Friedmanbea3f842008-05-13 20:16:47 +00003219 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003220 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003221 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003222}
3223
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003224/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3225/// is a read-only property; return true if so. A readonly property expression
3226/// depends on various declarations and thus must be treated specially.
3227///
3228static bool IsReadonlyProperty(Expr *E, Sema &S)
3229{
3230 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3231 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3232 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3233 QualType BaseType = PropExpr->getBase()->getType();
3234 if (const PointerType *PTy = BaseType->getAsPointerType())
3235 if (const ObjCInterfaceType *IFTy =
3236 PTy->getPointeeType()->getAsObjCInterfaceType())
3237 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3238 if (S.isPropertyReadonly(PDecl, IFace))
3239 return true;
3240 }
3241 }
3242 return false;
3243}
3244
Chris Lattner4c2642c2008-11-18 01:22:49 +00003245/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3246/// emit an error and return true. If so, return false.
3247static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003248 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3249 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3250 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003251 if (IsLV == Expr::MLV_Valid)
3252 return false;
3253
3254 unsigned Diag = 0;
3255 bool NeedType = false;
3256 switch (IsLV) { // C99 6.5.16p2
3257 default: assert(0 && "Unknown result from isModifiableLvalue!");
3258 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003259 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003260 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3261 NeedType = true;
3262 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003263 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003264 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3265 NeedType = true;
3266 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003267 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003268 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3269 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003270 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003271 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3272 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003273 case Expr::MLV_IncompleteType:
3274 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003275 return S.DiagnoseIncompleteType(Loc, E->getType(),
3276 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3277 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003278 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003279 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3280 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003281 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003282 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3283 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003284 case Expr::MLV_ReadonlyProperty:
3285 Diag = diag::error_readonly_property_assignment;
3286 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003287 case Expr::MLV_NoSetterProperty:
3288 Diag = diag::error_nosetter_property_assignment;
3289 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003290 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003291
Chris Lattner4c2642c2008-11-18 01:22:49 +00003292 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003293 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003294 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003295 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003296 return true;
3297}
3298
3299
3300
3301// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003302QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3303 SourceLocation Loc,
3304 QualType CompoundType) {
3305 // Verify that LHS is a modifiable lvalue, and emit error if not.
3306 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003307 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003308
3309 QualType LHSType = LHS->getType();
3310 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003311
Chris Lattner005ed752008-01-04 18:04:52 +00003312 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003313 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003314 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003315 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003316 // Special case of NSObject attributes on c-style pointer types.
3317 if (ConvTy == IncompatiblePointer &&
3318 ((Context.isObjCNSObjectType(LHSType) &&
3319 Context.isObjCObjectPointerType(RHSType)) ||
3320 (Context.isObjCNSObjectType(RHSType) &&
3321 Context.isObjCObjectPointerType(LHSType))))
3322 ConvTy = Compatible;
3323
Chris Lattner34c85082008-08-21 18:04:13 +00003324 // If the RHS is a unary plus or minus, check to see if they = and + are
3325 // right next to each other. If so, the user may have typo'd "x =+ 4"
3326 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003327 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003328 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3329 RHSCheck = ICE->getSubExpr();
3330 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3331 if ((UO->getOpcode() == UnaryOperator::Plus ||
3332 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003333 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003334 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003335 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003336 Diag(Loc, diag::warn_not_compound_assign)
3337 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3338 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003339 }
3340 } else {
3341 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003342 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003343 }
Chris Lattner005ed752008-01-04 18:04:52 +00003344
Chris Lattner1eafdea2008-11-18 01:30:42 +00003345 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3346 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003347 return QualType();
3348
Chris Lattner4b009652007-07-25 00:24:17 +00003349 // C99 6.5.16p3: The type of an assignment expression is the type of the
3350 // left operand unless the left operand has qualified type, in which case
3351 // it is the unqualified version of the type of the left operand.
3352 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3353 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003354 // C++ 5.17p1: the type of the assignment expression is that of its left
3355 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003356 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003357}
3358
Chris Lattner1eafdea2008-11-18 01:30:42 +00003359// C99 6.5.17
3360QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3361 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003362
3363 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003364 DefaultFunctionArrayConversion(RHS);
3365 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003366}
3367
3368/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3369/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003370QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3371 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003372 QualType ResType = Op->getType();
3373 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003374
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003375 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3376 // Decrement of bool is not allowed.
3377 if (!isInc) {
3378 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3379 return QualType();
3380 }
3381 // Increment of bool sets it to true, but is deprecated.
3382 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3383 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003384 // OK!
3385 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3386 // C99 6.5.2.4p2, 6.5.6p2
3387 if (PT->getPointeeType()->isObjectType()) {
3388 // Pointer to object is ok!
3389 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003390 if (getLangOptions().CPlusPlus) {
3391 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3392 << Op->getSourceRange();
3393 return QualType();
3394 }
3395
3396 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003397 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003398 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003399 if (getLangOptions().CPlusPlus) {
3400 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3401 << Op->getType() << Op->getSourceRange();
3402 return QualType();
3403 }
3404
3405 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003406 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003407 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003408 } else {
3409 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3410 diag::err_typecheck_arithmetic_incomplete_type,
3411 Op->getSourceRange(), SourceRange(),
3412 ResType);
3413 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003414 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003415 } else if (ResType->isComplexType()) {
3416 // C99 does not support ++/-- on complex types, we allow as an extension.
3417 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003418 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003419 } else {
3420 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003421 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003422 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003423 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003424 // At this point, we know we have a real, complex or pointer type.
3425 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003426 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003427 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003428 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003429}
3430
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003431/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003432/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003433/// where the declaration is needed for type checking. We only need to
3434/// handle cases when the expression references a function designator
3435/// or is an lvalue. Here are some examples:
3436/// - &(x) => x
3437/// - &*****f => f for f a function designator.
3438/// - &s.xx => s
3439/// - &s.zz[1].yy -> s, if zz is an array
3440/// - *(x + 1) -> x, if x is an array
3441/// - &"123"[2] -> 0
3442/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003443static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003444 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003445 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003446 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003447 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003448 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003449 // Fields cannot be declared with a 'register' storage class.
3450 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003451 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003452 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003453 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003454 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003455 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003456
Douglas Gregord2baafd2008-10-21 16:13:35 +00003457 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003458 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003459 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003460 return 0;
3461 else
3462 return VD;
3463 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003464 case Stmt::UnaryOperatorClass: {
3465 UnaryOperator *UO = cast<UnaryOperator>(E);
3466
3467 switch(UO->getOpcode()) {
3468 case UnaryOperator::Deref: {
3469 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003470 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3471 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3472 if (!VD || VD->getType()->isPointerType())
3473 return 0;
3474 return VD;
3475 }
3476 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003477 }
3478 case UnaryOperator::Real:
3479 case UnaryOperator::Imag:
3480 case UnaryOperator::Extension:
3481 return getPrimaryDecl(UO->getSubExpr());
3482 default:
3483 return 0;
3484 }
3485 }
3486 case Stmt::BinaryOperatorClass: {
3487 BinaryOperator *BO = cast<BinaryOperator>(E);
3488
3489 // Handle cases involving pointer arithmetic. The result of an
3490 // Assign or AddAssign is not an lvalue so they can be ignored.
3491
3492 // (x + n) or (n + x) => x
3493 if (BO->getOpcode() == BinaryOperator::Add) {
3494 if (BO->getLHS()->getType()->isPointerType()) {
3495 return getPrimaryDecl(BO->getLHS());
3496 } else if (BO->getRHS()->getType()->isPointerType()) {
3497 return getPrimaryDecl(BO->getRHS());
3498 }
3499 }
3500
3501 return 0;
3502 }
Chris Lattner4b009652007-07-25 00:24:17 +00003503 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003504 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003505 case Stmt::ImplicitCastExprClass:
3506 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003507 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003508 default:
3509 return 0;
3510 }
3511}
3512
3513/// CheckAddressOfOperand - The operand of & must be either a function
3514/// designator or an lvalue designating an object. If it is an lvalue, the
3515/// object cannot be declared with storage class register or be a bit field.
3516/// Note: The usual conversions are *not* applied to the operand of the &
3517/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003518/// In C++, the operand might be an overloaded function name, in which case
3519/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003520QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003521 if (op->isTypeDependent())
3522 return Context.DependentTy;
3523
Steve Naroff9c6c3592008-01-13 17:10:08 +00003524 if (getLangOptions().C99) {
3525 // Implement C99-only parts of addressof rules.
3526 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3527 if (uOp->getOpcode() == UnaryOperator::Deref)
3528 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3529 // (assuming the deref expression is valid).
3530 return uOp->getSubExpr()->getType();
3531 }
3532 // Technically, there should be a check for array subscript
3533 // expressions here, but the result of one is always an lvalue anyway.
3534 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003535 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003536 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003537
Chris Lattner4b009652007-07-25 00:24:17 +00003538 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003539 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3540 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003541 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3542 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003543 return QualType();
3544 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003545 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003546 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3547 if (Field->isBitField()) {
3548 Diag(OpLoc, diag::err_typecheck_address_of)
3549 << "bit-field" << op->getSourceRange();
3550 return QualType();
3551 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003552 }
3553 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003554 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3555 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003556 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003557 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003558 return QualType();
3559 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003560 // We have an lvalue with a decl. Make sure the decl is not declared
3561 // with the register storage-class specifier.
3562 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3563 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003564 Diag(OpLoc, diag::err_typecheck_address_of)
3565 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003566 return QualType();
3567 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003568 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003569 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003570 } else if (isa<FieldDecl>(dcl)) {
3571 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003572 // Could be a pointer to member, though, if there is an explicit
3573 // scope qualifier for the class.
3574 if (isa<QualifiedDeclRefExpr>(op)) {
3575 DeclContext *Ctx = dcl->getDeclContext();
3576 if (Ctx && Ctx->isRecord())
3577 return Context.getMemberPointerType(op->getType(),
3578 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3579 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003580 } else if (isa<FunctionDecl>(dcl)) {
3581 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003582 // As above.
3583 if (isa<QualifiedDeclRefExpr>(op)) {
3584 DeclContext *Ctx = dcl->getDeclContext();
3585 if (Ctx && Ctx->isRecord())
3586 return Context.getMemberPointerType(op->getType(),
3587 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3588 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003589 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003590 else
Chris Lattner4b009652007-07-25 00:24:17 +00003591 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003592 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003593
Chris Lattner4b009652007-07-25 00:24:17 +00003594 // If the operand has type "type", the result has type "pointer to type".
3595 return Context.getPointerType(op->getType());
3596}
3597
Chris Lattnerda5c0872008-11-23 09:13:29 +00003598QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3599 UsualUnaryConversions(Op);
3600 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003601
Chris Lattnerda5c0872008-11-23 09:13:29 +00003602 // Note that per both C89 and C99, this is always legal, even if ptype is an
3603 // incomplete type or void. It would be possible to warn about dereferencing
3604 // a void pointer, but it's completely well-defined, and such a warning is
3605 // unlikely to catch any mistakes.
3606 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003607 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003608
Chris Lattner77d52da2008-11-20 06:06:08 +00003609 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003610 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003611 return QualType();
3612}
3613
3614static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3615 tok::TokenKind Kind) {
3616 BinaryOperator::Opcode Opc;
3617 switch (Kind) {
3618 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003619 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3620 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003621 case tok::star: Opc = BinaryOperator::Mul; break;
3622 case tok::slash: Opc = BinaryOperator::Div; break;
3623 case tok::percent: Opc = BinaryOperator::Rem; break;
3624 case tok::plus: Opc = BinaryOperator::Add; break;
3625 case tok::minus: Opc = BinaryOperator::Sub; break;
3626 case tok::lessless: Opc = BinaryOperator::Shl; break;
3627 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3628 case tok::lessequal: Opc = BinaryOperator::LE; break;
3629 case tok::less: Opc = BinaryOperator::LT; break;
3630 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3631 case tok::greater: Opc = BinaryOperator::GT; break;
3632 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3633 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3634 case tok::amp: Opc = BinaryOperator::And; break;
3635 case tok::caret: Opc = BinaryOperator::Xor; break;
3636 case tok::pipe: Opc = BinaryOperator::Or; break;
3637 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3638 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3639 case tok::equal: Opc = BinaryOperator::Assign; break;
3640 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3641 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3642 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3643 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3644 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3645 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3646 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3647 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3648 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3649 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3650 case tok::comma: Opc = BinaryOperator::Comma; break;
3651 }
3652 return Opc;
3653}
3654
3655static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3656 tok::TokenKind Kind) {
3657 UnaryOperator::Opcode Opc;
3658 switch (Kind) {
3659 default: assert(0 && "Unknown unary op!");
3660 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3661 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3662 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3663 case tok::star: Opc = UnaryOperator::Deref; break;
3664 case tok::plus: Opc = UnaryOperator::Plus; break;
3665 case tok::minus: Opc = UnaryOperator::Minus; break;
3666 case tok::tilde: Opc = UnaryOperator::Not; break;
3667 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003668 case tok::kw___real: Opc = UnaryOperator::Real; break;
3669 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3670 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3671 }
3672 return Opc;
3673}
3674
Douglas Gregord7f915e2008-11-06 23:29:22 +00003675/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3676/// operator @p Opc at location @c TokLoc. This routine only supports
3677/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003678Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3679 unsigned Op,
3680 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003681 QualType ResultTy; // Result type of the binary operator.
3682 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3683 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3684
3685 switch (Opc) {
3686 default:
3687 assert(0 && "Unknown binary expr!");
3688 case BinaryOperator::Assign:
3689 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3690 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003691 case BinaryOperator::PtrMemD:
3692 case BinaryOperator::PtrMemI:
3693 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3694 Opc == BinaryOperator::PtrMemI);
3695 break;
3696 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003697 case BinaryOperator::Div:
3698 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3699 break;
3700 case BinaryOperator::Rem:
3701 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3702 break;
3703 case BinaryOperator::Add:
3704 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3705 break;
3706 case BinaryOperator::Sub:
3707 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3708 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003709 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003710 case BinaryOperator::Shr:
3711 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3712 break;
3713 case BinaryOperator::LE:
3714 case BinaryOperator::LT:
3715 case BinaryOperator::GE:
3716 case BinaryOperator::GT:
3717 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3718 break;
3719 case BinaryOperator::EQ:
3720 case BinaryOperator::NE:
3721 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3722 break;
3723 case BinaryOperator::And:
3724 case BinaryOperator::Xor:
3725 case BinaryOperator::Or:
3726 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3727 break;
3728 case BinaryOperator::LAnd:
3729 case BinaryOperator::LOr:
3730 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3731 break;
3732 case BinaryOperator::MulAssign:
3733 case BinaryOperator::DivAssign:
3734 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3735 if (!CompTy.isNull())
3736 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3737 break;
3738 case BinaryOperator::RemAssign:
3739 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3740 if (!CompTy.isNull())
3741 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3742 break;
3743 case BinaryOperator::AddAssign:
3744 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3745 if (!CompTy.isNull())
3746 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3747 break;
3748 case BinaryOperator::SubAssign:
3749 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3750 if (!CompTy.isNull())
3751 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3752 break;
3753 case BinaryOperator::ShlAssign:
3754 case BinaryOperator::ShrAssign:
3755 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3756 if (!CompTy.isNull())
3757 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3758 break;
3759 case BinaryOperator::AndAssign:
3760 case BinaryOperator::XorAssign:
3761 case BinaryOperator::OrAssign:
3762 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3763 if (!CompTy.isNull())
3764 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3765 break;
3766 case BinaryOperator::Comma:
3767 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3768 break;
3769 }
3770 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003771 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003772 if (CompTy.isNull())
3773 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3774 else
3775 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003776 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003777}
3778
Chris Lattner4b009652007-07-25 00:24:17 +00003779// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003780Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3781 tok::TokenKind Kind,
3782 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003783 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003784 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003785
Steve Naroff87d58b42007-09-16 03:34:24 +00003786 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3787 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003788
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003789 // If either expression is type-dependent, just build the AST.
3790 // FIXME: We'll need to perform some caching of the result of name
3791 // lookup for operator+.
3792 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003793 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3794 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003795 Context.DependentTy,
3796 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003797 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003798 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3799 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003800 }
3801
Sebastian Redl95216a62009-02-07 00:15:38 +00003802 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003803 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3804 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003805 // If this is one of the assignment operators, we only perform
3806 // overload resolution if the left-hand side is a class or
3807 // enumeration type (C++ [expr.ass]p3).
3808 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3809 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3810 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3811 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003812
Douglas Gregord7f915e2008-11-06 23:29:22 +00003813 // Determine which overloaded operator we're dealing with.
3814 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003815 // Overloading .* is not possible.
3816 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003817 OO_Star, OO_Slash, OO_Percent,
3818 OO_Plus, OO_Minus,
3819 OO_LessLess, OO_GreaterGreater,
3820 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3821 OO_EqualEqual, OO_ExclaimEqual,
3822 OO_Amp,
3823 OO_Caret,
3824 OO_Pipe,
3825 OO_AmpAmp,
3826 OO_PipePipe,
3827 OO_Equal, OO_StarEqual,
3828 OO_SlashEqual, OO_PercentEqual,
3829 OO_PlusEqual, OO_MinusEqual,
3830 OO_LessLessEqual, OO_GreaterGreaterEqual,
3831 OO_AmpEqual, OO_CaretEqual,
3832 OO_PipeEqual,
3833 OO_Comma
3834 };
3835 OverloadedOperatorKind OverOp = OverOps[Opc];
3836
Douglas Gregor5ed15042008-11-18 23:14:02 +00003837 // Add the appropriate overloaded operators (C++ [over.match.oper])
3838 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003839 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003840 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003841 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3842 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003843
3844 // Perform overload resolution.
3845 OverloadCandidateSet::iterator Best;
3846 switch (BestViableFunction(CandidateSet, Best)) {
3847 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003848 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003849 FunctionDecl *FnDecl = Best->Function;
3850
Douglas Gregor70d26122008-11-12 17:17:38 +00003851 if (FnDecl) {
3852 // We matched an overloaded operator. Build a call to that
3853 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003854
Douglas Gregor70d26122008-11-12 17:17:38 +00003855 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003856 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3857 if (PerformObjectArgumentInitialization(lhs, Method) ||
3858 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3859 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003860 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003861 } else {
3862 // Convert the arguments.
3863 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3864 "passing") ||
3865 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3866 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003867 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003868 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003869
Douglas Gregor70d26122008-11-12 17:17:38 +00003870 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003871 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003872 = FnDecl->getType()->getAsFunctionType()->getResultType();
3873 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003874
Douglas Gregor70d26122008-11-12 17:17:38 +00003875 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003876 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3877 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003878 UsualUnaryConversions(FnExpr);
3879
Ted Kremenek362abcd2009-02-09 20:51:47 +00003880 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003881 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003882 } else {
3883 // We matched a built-in operator. Convert the arguments, then
3884 // break out so that we will build the appropriate built-in
3885 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003886 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3887 Best->Conversions[0], "passing") ||
3888 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3889 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003890 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003891
3892 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003893 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003894 }
3895
3896 case OR_No_Viable_Function:
3897 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003898 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003899 break;
3900
3901 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003902 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3903 << BinaryOperator::getOpcodeStr(Opc)
3904 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003905 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003906 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003907 }
3908
Douglas Gregor70d26122008-11-12 17:17:38 +00003909 // Either we found no viable overloaded operator or we matched a
3910 // built-in operator. In either case, fall through to trying to
3911 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003912 }
3913
Douglas Gregord7f915e2008-11-06 23:29:22 +00003914 // Build a built-in binary operation.
3915 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003916}
3917
3918// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003919Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3920 tok::TokenKind Op, ExprArg input) {
3921 // FIXME: Input is modified later, but smart pointer not reassigned.
3922 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003923 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003924
3925 if (getLangOptions().CPlusPlus &&
3926 (Input->getType()->isRecordType()
3927 || Input->getType()->isEnumeralType())) {
3928 // Determine which overloaded operator we're dealing with.
3929 static const OverloadedOperatorKind OverOps[] = {
3930 OO_None, OO_None,
3931 OO_PlusPlus, OO_MinusMinus,
3932 OO_Amp, OO_Star,
3933 OO_Plus, OO_Minus,
3934 OO_Tilde, OO_Exclaim,
3935 OO_None, OO_None,
3936 OO_None,
3937 OO_None
3938 };
3939 OverloadedOperatorKind OverOp = OverOps[Opc];
3940
3941 // Add the appropriate overloaded operators (C++ [over.match.oper])
3942 // to the candidate set.
3943 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003944 if (OverOp != OO_None &&
3945 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3946 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003947
3948 // Perform overload resolution.
3949 OverloadCandidateSet::iterator Best;
3950 switch (BestViableFunction(CandidateSet, Best)) {
3951 case OR_Success: {
3952 // We found a built-in operator or an overloaded operator.
3953 FunctionDecl *FnDecl = Best->Function;
3954
3955 if (FnDecl) {
3956 // We matched an overloaded operator. Build a call to that
3957 // operator.
3958
3959 // Convert the arguments.
3960 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3961 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003962 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003963 } else {
3964 // Convert the arguments.
3965 if (PerformCopyInitialization(Input,
3966 FnDecl->getParamDecl(0)->getType(),
3967 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003968 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003969 }
3970
3971 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003972 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003973 = FnDecl->getType()->getAsFunctionType()->getResultType();
3974 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003975
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003976 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003977 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3978 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003979 UsualUnaryConversions(FnExpr);
3980
Sebastian Redl8b769972009-01-19 00:08:26 +00003981 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003982 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003983 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003984 } else {
3985 // We matched a built-in operator. Convert the arguments, then
3986 // break out so that we will build the appropriate built-in
3987 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003988 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3989 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003990 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003991
3992 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003993 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003994 }
3995
3996 case OR_No_Viable_Function:
3997 // No viable function; fall through to handling this as a
3998 // built-in operator, which will produce an error message for us.
3999 break;
4000
4001 case OR_Ambiguous:
4002 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4003 << UnaryOperator::getOpcodeStr(Opc)
4004 << Input->getSourceRange();
4005 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004006 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004007 }
4008
4009 // Either we found no viable overloaded operator or we matched a
4010 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004011 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004012 }
4013
Chris Lattner4b009652007-07-25 00:24:17 +00004014 QualType resultType;
4015 switch (Opc) {
4016 default:
4017 assert(0 && "Unimplemented unary expr!");
4018 case UnaryOperator::PreInc:
4019 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004020 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4021 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004022 break;
4023 case UnaryOperator::AddrOf:
4024 resultType = CheckAddressOfOperand(Input, OpLoc);
4025 break;
4026 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004027 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004028 resultType = CheckIndirectionOperand(Input, OpLoc);
4029 break;
4030 case UnaryOperator::Plus:
4031 case UnaryOperator::Minus:
4032 UsualUnaryConversions(Input);
4033 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004034 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4035 break;
4036 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4037 resultType->isEnumeralType())
4038 break;
4039 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4040 Opc == UnaryOperator::Plus &&
4041 resultType->isPointerType())
4042 break;
4043
Sebastian Redl8b769972009-01-19 00:08:26 +00004044 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4045 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004046 case UnaryOperator::Not: // bitwise complement
4047 UsualUnaryConversions(Input);
4048 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004049 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4050 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4051 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004052 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004053 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004054 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004055 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4056 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004057 break;
4058 case UnaryOperator::LNot: // logical negation
4059 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4060 DefaultFunctionArrayConversion(Input);
4061 resultType = Input->getType();
4062 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004063 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4064 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004065 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004066 // In C++, it's bool. C++ 5.3.1p8
4067 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004068 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004069 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004070 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004071 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004072 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004073 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004074 resultType = Input->getType();
4075 break;
4076 }
4077 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004078 return ExprError();
4079 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004080 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004081}
4082
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004083/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4084Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004085 SourceLocation LabLoc,
4086 IdentifierInfo *LabelII) {
4087 // Look up the record for this label identifier.
4088 LabelStmt *&LabelDecl = LabelMap[LabelII];
4089
Daniel Dunbar879788d2008-08-04 16:51:22 +00004090 // If we haven't seen this label yet, create a forward reference. It
4091 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004092 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004093 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004094
4095 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004096 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4097 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004098}
4099
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004100Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004101 SourceLocation RPLoc) { // "({..})"
4102 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4103 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4104 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4105
Eli Friedmanbc941e12009-01-24 23:09:00 +00004106 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4107 if (isFileScope) {
4108 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4109 }
4110
Chris Lattner4b009652007-07-25 00:24:17 +00004111 // FIXME: there are a variety of strange constraints to enforce here, for
4112 // example, it is not possible to goto into a stmt expression apparently.
4113 // More semantic analysis is needed.
4114
4115 // FIXME: the last statement in the compount stmt has its value used. We
4116 // should not warn about it being unused.
4117
4118 // If there are sub stmts in the compound stmt, take the type of the last one
4119 // as the type of the stmtexpr.
4120 QualType Ty = Context.VoidTy;
4121
Chris Lattner200964f2008-07-26 19:51:01 +00004122 if (!Compound->body_empty()) {
4123 Stmt *LastStmt = Compound->body_back();
4124 // If LastStmt is a label, skip down through into the body.
4125 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4126 LastStmt = Label->getSubStmt();
4127
4128 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004129 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004130 }
Chris Lattner4b009652007-07-25 00:24:17 +00004131
Steve Naroff774e4152009-01-21 00:14:39 +00004132 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004133}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004134
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004135Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4136 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004137 SourceLocation TypeLoc,
4138 TypeTy *argty,
4139 OffsetOfComponent *CompPtr,
4140 unsigned NumComponents,
4141 SourceLocation RPLoc) {
4142 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4143 assert(!ArgTy.isNull() && "Missing type argument!");
4144
4145 // We must have at least one component that refers to the type, and the first
4146 // one is known to be a field designator. Verify that the ArgTy represents
4147 // a struct/union/class.
4148 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004149 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004150
4151 // Otherwise, create a compound literal expression as the base, and
4152 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004153 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004154 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004155 IList->setType(ArgTy);
4156 Expr *Res =
4157 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4158
Chris Lattnerb37522e2007-08-31 21:49:13 +00004159 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4160 // GCC extension, diagnose them.
4161 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004162 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4163 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004164
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004165 for (unsigned i = 0; i != NumComponents; ++i) {
4166 const OffsetOfComponent &OC = CompPtr[i];
4167 if (OC.isBrackets) {
4168 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004169 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004170 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004171 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004172 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004173 }
4174
Chris Lattner2af6a802007-08-30 17:59:59 +00004175 // FIXME: C++: Verify that operator[] isn't overloaded.
4176
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004177 // C99 6.5.2.1p1
4178 Expr *Idx = static_cast<Expr*>(OC.U.E);
4179 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004180 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4181 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004182
Steve Naroff774e4152009-01-21 00:14:39 +00004183 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4184 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004185 continue;
4186 }
4187
4188 const RecordType *RC = Res->getType()->getAsRecordType();
4189 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004190 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004191 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004192 }
4193
4194 // Get the decl corresponding to this.
4195 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004196 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004197 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4198 LookupMemberName)
4199 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004200 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004201 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4202 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004203
4204 // FIXME: C++: Verify that MemberDecl isn't a static field.
4205 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004206 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4207 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004208 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4209 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004210 }
4211
Steve Naroff774e4152009-01-21 00:14:39 +00004212 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4213 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004214}
4215
4216
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004217Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004218 TypeTy *arg1, TypeTy *arg2,
4219 SourceLocation RPLoc) {
4220 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4221 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4222
4223 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4224
Steve Naroff774e4152009-01-21 00:14:39 +00004225 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4226 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004227}
4228
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004229Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004230 ExprTy *expr1, ExprTy *expr2,
4231 SourceLocation RPLoc) {
4232 Expr *CondExpr = static_cast<Expr*>(cond);
4233 Expr *LHSExpr = static_cast<Expr*>(expr1);
4234 Expr *RHSExpr = static_cast<Expr*>(expr2);
4235
4236 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4237
4238 // The conditional expression is required to be a constant expression.
4239 llvm::APSInt condEval(32);
4240 SourceLocation ExpLoc;
4241 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004242 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4243 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004244
4245 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4246 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4247 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004248 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4249 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004250}
4251
Steve Naroff52a81c02008-09-03 18:15:37 +00004252//===----------------------------------------------------------------------===//
4253// Clang Extensions.
4254//===----------------------------------------------------------------------===//
4255
4256/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004257void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004258 // Analyze block parameters.
4259 BlockSemaInfo *BSI = new BlockSemaInfo();
4260
4261 // Add BSI to CurBlock.
4262 BSI->PrevBlockInfo = CurBlock;
4263 CurBlock = BSI;
4264
4265 BSI->ReturnType = 0;
4266 BSI->TheScope = BlockScope;
4267
Steve Naroff52059382008-10-10 01:28:17 +00004268 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004269 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004270}
4271
Mike Stumpc1fddff2009-02-04 22:31:32 +00004272void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4273 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4274
4275 if (ParamInfo.getNumTypeObjects() == 0
4276 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4277 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4278
4279 // The type is entirely optional as well, if none, use DependentTy.
4280 if (T.isNull())
4281 T = Context.DependentTy;
4282
4283 // The parameter list is optional, if there was none, assume ().
4284 if (!T->isFunctionType())
4285 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4286
4287 CurBlock->hasPrototype = true;
4288 CurBlock->isVariadic = false;
4289 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4290 .getTypePtr();
4291
4292 if (!RetTy->isDependentType())
4293 CurBlock->ReturnType = RetTy;
4294 return;
4295 }
4296
Steve Naroff52a81c02008-09-03 18:15:37 +00004297 // Analyze arguments to block.
4298 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4299 "Not a function declarator!");
4300 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004301
Steve Naroff52059382008-10-10 01:28:17 +00004302 CurBlock->hasPrototype = FTI.hasPrototype;
4303 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004304
4305 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4306 // no arguments, not a function that takes a single void argument.
4307 if (FTI.hasPrototype &&
4308 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4309 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4310 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4311 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004312 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004313 } else if (FTI.hasPrototype) {
4314 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004315 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4316 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004317 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4318
4319 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4320 .getTypePtr();
4321
4322 if (!RetTy->isDependentType())
4323 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004324 }
Steve Naroff52059382008-10-10 01:28:17 +00004325 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4326
4327 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4328 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4329 // If this has an identifier, add it to the scope stack.
4330 if ((*AI)->getIdentifier())
4331 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004332}
4333
4334/// ActOnBlockError - If there is an error parsing a block, this callback
4335/// is invoked to pop the information about the block from the action impl.
4336void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4337 // Ensure that CurBlock is deleted.
4338 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4339
4340 // Pop off CurBlock, handle nested blocks.
4341 CurBlock = CurBlock->PrevBlockInfo;
4342
4343 // FIXME: Delete the ParmVarDecl objects as well???
4344
4345}
4346
4347/// ActOnBlockStmtExpr - This is called when the body of a block statement
4348/// literal was successfully completed. ^(int x){...}
4349Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4350 Scope *CurScope) {
4351 // Ensure that CurBlock is deleted.
4352 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004353 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004354
Steve Naroff52059382008-10-10 01:28:17 +00004355 PopDeclContext();
4356
Steve Naroff52a81c02008-09-03 18:15:37 +00004357 // Pop off CurBlock, handle nested blocks.
4358 CurBlock = CurBlock->PrevBlockInfo;
4359
4360 QualType RetTy = Context.VoidTy;
4361 if (BSI->ReturnType)
4362 RetTy = QualType(BSI->ReturnType, 0);
4363
4364 llvm::SmallVector<QualType, 8> ArgTypes;
4365 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4366 ArgTypes.push_back(BSI->Params[i]->getType());
4367
4368 QualType BlockTy;
4369 if (!BSI->hasPrototype)
4370 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4371 else
4372 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004373 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004374
4375 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004376
Steve Naroff95029d92008-10-08 18:44:00 +00004377 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004378 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004379}
4380
Nate Begemanbd881ef2008-01-30 20:50:20 +00004381/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004382/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004383/// The number of arguments has already been validated to match the number of
4384/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004385static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4386 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004387 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004388 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004389 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4390 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004391
4392 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004393 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004394 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004395 return true;
4396}
4397
4398Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4399 SourceLocation *CommaLocs,
4400 SourceLocation BuiltinLoc,
4401 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004402 // __builtin_overload requires at least 2 arguments
4403 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004404 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4405 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004406
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004407 // The first argument is required to be a constant expression. It tells us
4408 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004409 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004410 Expr *NParamsExpr = Args[0];
4411 llvm::APSInt constEval(32);
4412 SourceLocation ExpLoc;
4413 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004414 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4415 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004416
4417 // Verify that the number of parameters is > 0
4418 unsigned NumParams = constEval.getZExtValue();
4419 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004420 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4421 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004422 // Verify that we have at least 1 + NumParams arguments to the builtin.
4423 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004424 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4425 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004426
4427 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004428 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004429 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004430 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4431 // UsualUnaryConversions will convert the function DeclRefExpr into a
4432 // pointer to function.
4433 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004434 const FunctionTypeProto *FnType = 0;
4435 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4436 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004437
4438 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4439 // parameters, and the number of parameters must match the value passed to
4440 // the builtin.
4441 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004442 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4443 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004444
4445 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004446 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004447 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004448 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004449 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004450 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4451 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004452 // Remember our match, and continue processing the remaining arguments
4453 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004454 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004455 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004456 BuiltinLoc, RParenLoc);
4457 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004458 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004459 // Return the newly created OverloadExpr node, if we succeded in matching
4460 // exactly one of the candidate functions.
4461 if (OE)
4462 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004463
4464 // If we didn't find a matching function Expr in the __builtin_overload list
4465 // the return an error.
4466 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004467 for (unsigned i = 0; i != NumParams; ++i) {
4468 if (i != 0) typeNames += ", ";
4469 typeNames += Args[i+1]->getType().getAsString();
4470 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004471
Chris Lattner77d52da2008-11-20 06:06:08 +00004472 return Diag(BuiltinLoc, diag::err_overload_no_match)
4473 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004474}
4475
Anders Carlsson36760332007-10-15 20:28:48 +00004476Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4477 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004478 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004479 Expr *E = static_cast<Expr*>(expr);
4480 QualType T = QualType::getFromOpaquePtr(type);
4481
4482 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004483
4484 // Get the va_list type
4485 QualType VaListType = Context.getBuiltinVaListType();
4486 // Deal with implicit array decay; for example, on x86-64,
4487 // va_list is an array, but it's supposed to decay to
4488 // a pointer for va_arg.
4489 if (VaListType->isArrayType())
4490 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004491 // Make sure the input expression also decays appropriately.
4492 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004493
4494 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004495 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004496 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004497 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004498
4499 // FIXME: Warn if a non-POD type is passed in.
4500
Steve Naroff774e4152009-01-21 00:14:39 +00004501 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004502}
4503
Douglas Gregorad4b3792008-11-29 04:51:27 +00004504Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4505 // The type of __null will be int or long, depending on the size of
4506 // pointers on the target.
4507 QualType Ty;
4508 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4509 Ty = Context.IntTy;
4510 else
4511 Ty = Context.LongTy;
4512
Steve Naroff774e4152009-01-21 00:14:39 +00004513 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004514}
4515
Chris Lattner005ed752008-01-04 18:04:52 +00004516bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4517 SourceLocation Loc,
4518 QualType DstType, QualType SrcType,
4519 Expr *SrcExpr, const char *Flavor) {
4520 // Decode the result (notice that AST's are still created for extensions).
4521 bool isInvalid = false;
4522 unsigned DiagKind;
4523 switch (ConvTy) {
4524 default: assert(0 && "Unknown conversion type");
4525 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004526 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004527 DiagKind = diag::ext_typecheck_convert_pointer_int;
4528 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004529 case IntToPointer:
4530 DiagKind = diag::ext_typecheck_convert_int_pointer;
4531 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004532 case IncompatiblePointer:
4533 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4534 break;
4535 case FunctionVoidPointer:
4536 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4537 break;
4538 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004539 // If the qualifiers lost were because we were applying the
4540 // (deprecated) C++ conversion from a string literal to a char*
4541 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4542 // Ideally, this check would be performed in
4543 // CheckPointerTypesForAssignment. However, that would require a
4544 // bit of refactoring (so that the second argument is an
4545 // expression, rather than a type), which should be done as part
4546 // of a larger effort to fix CheckPointerTypesForAssignment for
4547 // C++ semantics.
4548 if (getLangOptions().CPlusPlus &&
4549 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4550 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004551 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4552 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004553 case IntToBlockPointer:
4554 DiagKind = diag::err_int_to_block_pointer;
4555 break;
4556 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004557 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004558 break;
Steve Naroff19608432008-10-14 22:18:38 +00004559 case IncompatibleObjCQualifiedId:
4560 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4561 // it can give a more specific diagnostic.
4562 DiagKind = diag::warn_incompatible_qualified_id;
4563 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004564 case IncompatibleVectors:
4565 DiagKind = diag::warn_incompatible_vectors;
4566 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004567 case Incompatible:
4568 DiagKind = diag::err_typecheck_convert_incompatible;
4569 isInvalid = true;
4570 break;
4571 }
4572
Chris Lattner271d4c22008-11-24 05:29:24 +00004573 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4574 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004575 return isInvalid;
4576}
Anders Carlssond5201b92008-11-30 19:50:32 +00004577
4578bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4579{
4580 Expr::EvalResult EvalResult;
4581
4582 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4583 EvalResult.HasSideEffects) {
4584 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4585
4586 if (EvalResult.Diag) {
4587 // We only show the note if it's not the usual "invalid subexpression"
4588 // or if it's actually in a subexpression.
4589 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4590 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4591 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4592 }
4593
4594 return true;
4595 }
4596
4597 if (EvalResult.Diag) {
4598 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4599 E->getSourceRange();
4600
4601 // Print the reason it's not a constant.
4602 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4603 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4604 }
4605
4606 if (Result)
4607 *Result = EvalResult.Val.getInt();
4608 return false;
4609}