blob: 3143fc7aa1faf1ea8b8c19d294dd33f1855a9eb4 [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>()) {
35 // If this reference happens *in* a deprecated function or method, don't
36 // warn. Implementing deprecated stuff requires referencing depreated
37 // stuff.
38 NamedDecl *ND = getCurFunctionOrMethodDecl();
39 if (ND == 0 || !ND->getAttr<DeprecatedAttr>())
40 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
41 }
42
43 // See if hte decl is unavailable.
44 if (D->getAttr<UnavailableAttr>())
45 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
46}
47
Chris Lattner299b8842008-07-25 21:10:04 +000048//===----------------------------------------------------------------------===//
49// Standard Promotions and Conversions
50//===----------------------------------------------------------------------===//
51
Chris Lattner299b8842008-07-25 21:10:04 +000052/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
53void Sema::DefaultFunctionArrayConversion(Expr *&E) {
54 QualType Ty = E->getType();
55 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
56
Chris Lattner299b8842008-07-25 21:10:04 +000057 if (Ty->isFunctionType())
58 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000059 else if (Ty->isArrayType()) {
60 // In C90 mode, arrays only promote to pointers if the array expression is
61 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
62 // type 'array of type' is converted to an expression that has type 'pointer
63 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
64 // that has type 'array of type' ...". The relevant change is "an lvalue"
65 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000066 //
67 // C++ 4.2p1:
68 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
69 // T" can be converted to an rvalue of type "pointer to T".
70 //
71 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
72 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000073 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
74 }
Chris Lattner299b8842008-07-25 21:10:04 +000075}
76
77/// UsualUnaryConversions - Performs various conversions that are common to most
78/// operators (C99 6.3). The conversions of array and function types are
79/// sometimes surpressed. For example, the array->pointer conversion doesn't
80/// apply if the array is an argument to the sizeof or address (&) operators.
81/// In these instances, this routine should *not* be called.
82Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
83 QualType Ty = Expr->getType();
84 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
85
Chris Lattner299b8842008-07-25 21:10:04 +000086 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
87 ImpCastExprToType(Expr, Context.IntTy);
88 else
89 DefaultFunctionArrayConversion(Expr);
90
91 return Expr;
92}
93
Chris Lattner9305c3d2008-07-25 22:25:12 +000094/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
95/// do not have a prototype. Arguments that have type float are promoted to
96/// double. All other argument types are converted by UsualUnaryConversions().
97void Sema::DefaultArgumentPromotion(Expr *&Expr) {
98 QualType Ty = Expr->getType();
99 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
100
101 // If this is a 'float' (CVR qualified or typedef) promote to double.
102 if (const BuiltinType *BT = Ty->getAsBuiltinType())
103 if (BT->getKind() == BuiltinType::Float)
104 return ImpCastExprToType(Expr, Context.DoubleTy);
105
106 UsualUnaryConversions(Expr);
107}
108
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000109// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
110// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000111void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000112 DefaultArgumentPromotion(Expr);
113
114 if (!Expr->getType()->isPODType()) {
115 Diag(Expr->getLocStart(),
116 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
117 Expr->getType() << CT;
118 }
119}
120
121
Chris Lattner299b8842008-07-25 21:10:04 +0000122/// UsualArithmeticConversions - Performs various conversions that are common to
123/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
124/// routine returns the first non-arithmetic type found. The client is
125/// responsible for emitting appropriate error diagnostics.
126/// FIXME: verify the conversion rules for "complex int" are consistent with
127/// GCC.
128QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
129 bool isCompAssign) {
130 if (!isCompAssign) {
131 UsualUnaryConversions(lhsExpr);
132 UsualUnaryConversions(rhsExpr);
133 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000134
Chris Lattner299b8842008-07-25 21:10:04 +0000135 // For conversion purposes, we ignore any qualifiers.
136 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000137 QualType lhs =
138 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
139 QualType rhs =
140 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000141
142 // If both types are identical, no conversion is needed.
143 if (lhs == rhs)
144 return lhs;
145
146 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
147 // The caller can deal with this (e.g. pointer + int).
148 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
149 return lhs;
150
151 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
152 if (!isCompAssign) {
153 ImpCastExprToType(lhsExpr, destType);
154 ImpCastExprToType(rhsExpr, destType);
155 }
156 return destType;
157}
158
159QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
160 // Perform the usual unary conversions. We do this early so that
161 // integral promotions to "int" can allow us to exit early, in the
162 // lhs == rhs check. Also, for conversion purposes, we ignore any
163 // qualifiers. For example, "const float" and "float" are
164 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000165 if (lhs->isPromotableIntegerType())
166 lhs = Context.IntTy;
167 else
168 lhs = lhs.getUnqualifiedType();
169 if (rhs->isPromotableIntegerType())
170 rhs = Context.IntTy;
171 else
172 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000173
Chris Lattner299b8842008-07-25 21:10:04 +0000174 // If both types are identical, no conversion is needed.
175 if (lhs == rhs)
176 return lhs;
177
178 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
179 // The caller can deal with this (e.g. pointer + int).
180 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
181 return lhs;
182
183 // At this point, we have two different arithmetic types.
184
185 // Handle complex types first (C99 6.3.1.8p1).
186 if (lhs->isComplexType() || rhs->isComplexType()) {
187 // if we have an integer operand, the result is the complex type.
188 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
189 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000190 return lhs;
191 }
192 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
193 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return rhs;
195 }
196 // This handles complex/complex, complex/float, or float/complex.
197 // When both operands are complex, the shorter operand is converted to the
198 // type of the longer, and that is the type of the result. This corresponds
199 // to what is done when combining two real floating-point operands.
200 // The fun begins when size promotion occur across type domains.
201 // From H&S 6.3.4: When one operand is complex and the other is a real
202 // floating-point type, the less precise type is converted, within it's
203 // real or complex domain, to the precision of the other type. For example,
204 // when combining a "long double" with a "double _Complex", the
205 // "double _Complex" is promoted to "long double _Complex".
206 int result = Context.getFloatingTypeOrder(lhs, rhs);
207
208 if (result > 0) { // The left side is bigger, convert rhs.
209 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000210 } else if (result < 0) { // The right side is bigger, convert lhs.
211 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000212 }
213 // At this point, lhs and rhs have the same rank/size. Now, make sure the
214 // domains match. This is a requirement for our implementation, C99
215 // does not require this promotion.
216 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
217 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000218 return rhs;
219 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000220 return lhs;
221 }
222 }
223 return lhs; // The domain/size match exactly.
224 }
225 // Now handle "real" floating types (i.e. float, double, long double).
226 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
227 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000228 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000229 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000230 return lhs;
231 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000232 if (rhs->isComplexIntegerType()) {
233 // convert rhs to the complex floating point type.
234 return Context.getComplexType(lhs);
235 }
236 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000237 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000238 return rhs;
239 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000240 if (lhs->isComplexIntegerType()) {
241 // convert lhs to the complex floating point type.
242 return Context.getComplexType(rhs);
243 }
Chris Lattner299b8842008-07-25 21:10:04 +0000244 // We have two real floating types, float/complex combos were handled above.
245 // Convert the smaller operand to the bigger result.
246 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000247 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000248 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000249 assert(result < 0 && "illegal float comparison");
250 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000251 }
252 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
253 // Handle GCC complex int extension.
254 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
255 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
256
257 if (lhsComplexInt && rhsComplexInt) {
258 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000259 rhsComplexInt->getElementType()) >= 0)
260 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000261 return rhs;
262 } else if (lhsComplexInt && rhs->isIntegerType()) {
263 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000264 return lhs;
265 } else if (rhsComplexInt && lhs->isIntegerType()) {
266 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000267 return rhs;
268 }
269 }
270 // Finally, we have two differing integer types.
271 // The rules for this case are in C99 6.3.1.8
272 int compare = Context.getIntegerTypeOrder(lhs, rhs);
273 bool lhsSigned = lhs->isSignedIntegerType(),
274 rhsSigned = rhs->isSignedIntegerType();
275 QualType destType;
276 if (lhsSigned == rhsSigned) {
277 // Same signedness; use the higher-ranked type
278 destType = compare >= 0 ? lhs : rhs;
279 } else if (compare != (lhsSigned ? 1 : -1)) {
280 // The unsigned type has greater than or equal rank to the
281 // signed type, so use the unsigned type
282 destType = lhsSigned ? rhs : lhs;
283 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
284 // The two types are different widths; if we are here, that
285 // means the signed type is larger than the unsigned type, so
286 // use the signed type.
287 destType = lhsSigned ? lhs : rhs;
288 } else {
289 // The signed type is higher-ranked than the unsigned type,
290 // but isn't actually any bigger (like unsigned int and long
291 // on most 32-bit systems). Use the unsigned type corresponding
292 // to the signed type.
293 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
294 }
Chris Lattner299b8842008-07-25 21:10:04 +0000295 return destType;
296}
297
298//===----------------------------------------------------------------------===//
299// Semantic Analysis for various Expression Types
300//===----------------------------------------------------------------------===//
301
302
Steve Naroff87d58b42007-09-16 03:34:24 +0000303/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000304/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
305/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
306/// multiple tokens. However, the common case is that StringToks points to one
307/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000308///
309Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000310Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000311 assert(NumStringToks && "Must have at least one string!");
312
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000313 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000314 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000315 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000316
317 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
318 for (unsigned i = 0; i != NumStringToks; ++i)
319 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000320
Chris Lattnera6dcce32008-02-11 00:02:17 +0000321 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000322 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000323 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000324
325 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
326 if (getLangOptions().CPlusPlus)
327 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000328
Chris Lattnera6dcce32008-02-11 00:02:17 +0000329 // Get an array type for the string, according to C99 6.4.5. This includes
330 // the nul terminator character as well as the string length for pascal
331 // strings.
332 StrTy = Context.getConstantArrayType(StrTy,
333 llvm::APInt(32, Literal.GetStringLength()+1),
334 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000335
Chris Lattner4b009652007-07-25 00:24:17 +0000336 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek4f530a92009-02-06 19:55:15 +0000337 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff774e4152009-01-21 00:14:39 +0000338 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000339 Literal.AnyWide, StrTy,
340 StringToks[0].getLocation(),
341 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000342}
343
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000344/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
345/// CurBlock to VD should cause it to be snapshotted (as we do for auto
346/// variables defined outside the block) or false if this is not needed (e.g.
347/// for values inside the block or for globals).
348///
349/// FIXME: This will create BlockDeclRefExprs for global variables,
350/// function references, etc which is suboptimal :) and breaks
351/// things like "integer constant expression" tests.
352static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
353 ValueDecl *VD) {
354 // If the value is defined inside the block, we couldn't snapshot it even if
355 // we wanted to.
356 if (CurBlock->TheDecl == VD->getDeclContext())
357 return false;
358
359 // If this is an enum constant or function, it is constant, don't snapshot.
360 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
361 return false;
362
363 // If this is a reference to an extern, static, or global variable, no need to
364 // snapshot it.
365 // FIXME: What about 'const' variables in C++?
366 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
367 return Var->hasLocalStorage();
368
369 return true;
370}
371
372
373
Steve Naroff0acc9c92007-09-15 18:49:24 +0000374/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000375/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000376/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000377/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000378/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000379Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
380 IdentifierInfo &II,
381 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000382 const CXXScopeSpec *SS,
383 bool isAddressOfOperand) {
384 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000385 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000386}
387
Douglas Gregor566782a2009-01-06 05:10:23 +0000388/// BuildDeclRefExpr - Build either a DeclRefExpr or a
389/// QualifiedDeclRefExpr based on whether or not SS is a
390/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000391DeclRefExpr *
392Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
393 bool TypeDependent, bool ValueDependent,
394 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000395 if (SS && !SS->isEmpty())
396 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000397 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000398 else
399 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000400}
401
Douglas Gregor723d3332009-01-07 00:43:41 +0000402/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
403/// variable corresponding to the anonymous union or struct whose type
404/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000405static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000406 assert(Record->isAnonymousStructOrUnion() &&
407 "Record must be an anonymous struct or union!");
408
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000409 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000410 // be an O(1) operation rather than a slow walk through DeclContext's
411 // vector (which itself will be eliminated). DeclGroups might make
412 // this even better.
413 DeclContext *Ctx = Record->getDeclContext();
414 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
415 DEnd = Ctx->decls_end();
416 D != DEnd; ++D) {
417 if (*D == Record) {
418 // The object for the anonymous struct/union directly
419 // follows its type in the list of declarations.
420 ++D;
421 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000422 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000423 return *D;
424 }
425 }
426
427 assert(false && "Missing object for anonymous record");
428 return 0;
429}
430
Sebastian Redlcd883f72009-01-18 18:53:16 +0000431Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000432Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
433 FieldDecl *Field,
434 Expr *BaseObjectExpr,
435 SourceLocation OpLoc) {
436 assert(Field->getDeclContext()->isRecord() &&
437 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
438 && "Field must be stored inside an anonymous struct or union");
439
440 // Construct the sequence of field member references
441 // we'll have to perform to get to the field in the anonymous
442 // union/struct. The list of members is built from the field
443 // outward, so traverse it backwards to go from an object in
444 // the current context to the field we found.
445 llvm::SmallVector<FieldDecl *, 4> AnonFields;
446 AnonFields.push_back(Field);
447 VarDecl *BaseObject = 0;
448 DeclContext *Ctx = Field->getDeclContext();
449 do {
450 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000451 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000452 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
453 AnonFields.push_back(AnonField);
454 else {
455 BaseObject = cast<VarDecl>(AnonObject);
456 break;
457 }
458 Ctx = Ctx->getParent();
459 } while (Ctx->isRecord() &&
460 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
461
462 // Build the expression that refers to the base object, from
463 // which we will build a sequence of member references to each
464 // of the anonymous union objects and, eventually, the field we
465 // found via name lookup.
466 bool BaseObjectIsPointer = false;
467 unsigned ExtraQuals = 0;
468 if (BaseObject) {
469 // BaseObject is an anonymous struct/union variable (and is,
470 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000471 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000472 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000473 SourceLocation());
474 ExtraQuals
475 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
476 } else if (BaseObjectExpr) {
477 // The caller provided the base object expression. Determine
478 // whether its a pointer and whether it adds any qualifiers to the
479 // anonymous struct/union fields we're looking into.
480 QualType ObjectType = BaseObjectExpr->getType();
481 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
482 BaseObjectIsPointer = true;
483 ObjectType = ObjectPtr->getPointeeType();
484 }
485 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
486 } else {
487 // We've found a member of an anonymous struct/union that is
488 // inside a non-anonymous struct/union, so in a well-formed
489 // program our base object expression is "this".
490 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
491 if (!MD->isStatic()) {
492 QualType AnonFieldType
493 = Context.getTagDeclType(
494 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
495 QualType ThisType = Context.getTagDeclType(MD->getParent());
496 if ((Context.getCanonicalType(AnonFieldType)
497 == Context.getCanonicalType(ThisType)) ||
498 IsDerivedFrom(ThisType, AnonFieldType)) {
499 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000500 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000501 MD->getThisType(Context));
502 BaseObjectIsPointer = true;
503 }
504 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000505 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
506 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000507 }
508 ExtraQuals = MD->getTypeQualifiers();
509 }
510
511 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000512 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
513 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000514 }
515
516 // Build the implicit member references to the field of the
517 // anonymous struct/union.
518 Expr *Result = BaseObjectExpr;
519 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
520 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
521 FI != FIEnd; ++FI) {
522 QualType MemberType = (*FI)->getType();
523 if (!(*FI)->isMutable()) {
524 unsigned combinedQualifiers
525 = MemberType.getCVRQualifiers() | ExtraQuals;
526 MemberType = MemberType.getQualifiedType(combinedQualifiers);
527 }
Steve Naroff774e4152009-01-21 00:14:39 +0000528 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
529 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000530 BaseObjectIsPointer = false;
531 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
532 OpLoc = SourceLocation();
533 }
534
Sebastian Redlcd883f72009-01-18 18:53:16 +0000535 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000536}
537
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000538/// ActOnDeclarationNameExpr - The parser has read some kind of name
539/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
540/// performs lookup on that name and returns an expression that refers
541/// to that name. This routine isn't directly called from the parser,
542/// because the parser doesn't know about DeclarationName. Rather,
543/// this routine is called by ActOnIdentifierExpr,
544/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
545/// which form the DeclarationName from the corresponding syntactic
546/// forms.
547///
548/// HasTrailingLParen indicates whether this identifier is used in a
549/// function call context. LookupCtx is only used for a C++
550/// qualified-id (foo::bar) to indicate the class or namespace that
551/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000552///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000553/// isAddressOfOperand means that this expression is the direct operand
554/// of an address-of operator. This matters because this is the only
555/// situation where a qualified name referencing a non-static member may
556/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000557Sema::OwningExprResult
558Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
559 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000560 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000561 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000562 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000563 if (SS && SS->isInvalid())
564 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000565 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
566 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000567
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000568 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
569 HasTrailingLParen && Lookup.getKind() == LookupResult::NotFound) {
570 // We've seen something of the form
571 //
572 // identifier(
573 //
574 // and we did not find any entity by the name
575 // "identifier". However, this identifier is still subject to
576 // argument-dependent lookup, so keep track of the name.
577 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
578 Context.OverloadTy,
579 Loc));
580 }
581
Douglas Gregor09be81b2009-02-04 17:27:36 +0000582 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000583 if (Lookup.isAmbiguous()) {
584 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
585 SS && SS->isSet() ? SS->getRange()
586 : SourceRange());
587 return ExprError();
588 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000589 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000590
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000591 // If this reference is in an Objective-C method, then ivar lookup happens as
592 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000593 IdentifierInfo *II = Name.getAsIdentifierInfo();
594 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000595 // There are two cases to handle here. 1) scoped lookup could have failed,
596 // in which case we should look for an ivar. 2) scoped lookup could have
597 // found a decl, but that decl is outside the current method (i.e. a global
598 // variable). In these two cases, we do a lookup for an ivar with this
599 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000600 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000601 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000602 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000603 // FIXME: This should use a new expr for a direct reference, don't turn
604 // this into Self->ivar, just return a BareIVarExpr or something.
605 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000606 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000607 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
608 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000609 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000610 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000611 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000612 }
613 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000614 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000615 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000616 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000617 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000618 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000619 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000620 }
Chris Lattner4b009652007-07-25 00:24:17 +0000621 if (D == 0) {
622 // Otherwise, this could be an implicitly declared function reference (legal
623 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000624 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000625 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000626 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 else {
628 // If this name wasn't predeclared and if this is not a function call,
629 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000630 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000631 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
632 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000633 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
634 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000635 return ExprError(Diag(Loc, diag::err_undeclared_use)
636 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000637 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000638 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000639 }
640 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000641
Sebastian Redl0c9da212009-02-03 20:19:35 +0000642 // If this is an expression of the form &Class::member, don't build an
643 // implicit member ref, because we want a pointer to the member in general,
644 // not any specific instance's member.
645 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000646 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000647 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000648 QualType DType;
649 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
650 DType = FD->getType().getNonReferenceType();
651 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
652 DType = Method->getType();
653 } else if (isa<OverloadedFunctionDecl>(D)) {
654 DType = Context.OverloadTy;
655 }
656 // Could be an inner type. That's diagnosed below, so ignore it here.
657 if (!DType.isNull()) {
658 // The pointer is type- and value-dependent if it points into something
659 // dependent.
660 bool Dependent = false;
661 for (; DC; DC = DC->getParent()) {
662 // FIXME: could stop early at namespace scope.
663 if (DC->isRecord()) {
664 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
665 if (Context.getTypeDeclType(Record)->isDependentType()) {
666 Dependent = true;
667 break;
668 }
669 }
670 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000671 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000672 }
673 }
674 }
675
Douglas Gregor723d3332009-01-07 00:43:41 +0000676 // We may have found a field within an anonymous union or struct
677 // (C++ [class.union]).
678 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
679 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
680 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000681
Douglas Gregor3257fb52008-12-22 05:46:06 +0000682 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
683 if (!MD->isStatic()) {
684 // C++ [class.mfct.nonstatic]p2:
685 // [...] if name lookup (3.4.1) resolves the name in the
686 // id-expression to a nonstatic nontype member of class X or of
687 // a base class of X, the id-expression is transformed into a
688 // class member access expression (5.2.5) using (*this) (9.3.2)
689 // as the postfix-expression to the left of the '.' operator.
690 DeclContext *Ctx = 0;
691 QualType MemberType;
692 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
693 Ctx = FD->getDeclContext();
694 MemberType = FD->getType();
695
696 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
697 MemberType = RefType->getPointeeType();
698 else if (!FD->isMutable()) {
699 unsigned combinedQualifiers
700 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
701 MemberType = MemberType.getQualifiedType(combinedQualifiers);
702 }
703 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
704 if (!Method->isStatic()) {
705 Ctx = Method->getParent();
706 MemberType = Method->getType();
707 }
708 } else if (OverloadedFunctionDecl *Ovl
709 = dyn_cast<OverloadedFunctionDecl>(D)) {
710 for (OverloadedFunctionDecl::function_iterator
711 Func = Ovl->function_begin(),
712 FuncEnd = Ovl->function_end();
713 Func != FuncEnd; ++Func) {
714 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
715 if (!DMethod->isStatic()) {
716 Ctx = Ovl->getDeclContext();
717 MemberType = Context.OverloadTy;
718 break;
719 }
720 }
721 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000722
723 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000724 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
725 QualType ThisType = Context.getTagDeclType(MD->getParent());
726 if ((Context.getCanonicalType(CtxType)
727 == Context.getCanonicalType(ThisType)) ||
728 IsDerivedFrom(ThisType, CtxType)) {
729 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000730 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000731 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000732 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000733 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000734 }
735 }
736 }
737 }
738
Douglas Gregor8acb7272008-12-11 16:49:14 +0000739 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000740 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
741 if (MD->isStatic())
742 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000743 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
744 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000745 }
746
Douglas Gregor3257fb52008-12-22 05:46:06 +0000747 // Any other ways we could have found the field in a well-formed
748 // program would have been turned into implicit member expressions
749 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000750 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
751 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000752 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000753
Chris Lattner4b009652007-07-25 00:24:17 +0000754 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000755 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000756 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000757 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000758 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000759 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000760
Steve Naroffd6163f32008-09-05 22:11:13 +0000761 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000762 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000763 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
764 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000765 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
766 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
767 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000768 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000769
Chris Lattnerd9037472009-02-15 01:38:09 +0000770 // Check if referencing an identifier with __attribute__((deprecated)).
Chris Lattner2cb744b2009-02-15 22:43:40 +0000771 DiagnoseUseOfDeprecatedDecl(VD, Loc);
Chris Lattnerd9037472009-02-15 01:38:09 +0000772
Douglas Gregor48840c72008-12-10 23:01:14 +0000773 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
774 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
775 Scope *CheckS = S;
776 while (CheckS) {
777 if (CheckS->isWithinElse() &&
778 CheckS->getControlParent()->isDeclScope(Var)) {
779 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000780 ExprError(Diag(Loc, diag::warn_value_always_false)
781 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000782 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000783 ExprError(Diag(Loc, diag::warn_value_always_zero)
784 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000785 break;
786 }
787
788 // Move up one more control parent to check again.
789 CheckS = CheckS->getControlParent();
790 if (CheckS)
791 CheckS = CheckS->getParent();
792 }
793 }
794 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000795
796 // Only create DeclRefExpr's for valid Decl's.
797 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000798 return ExprError();
799
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000800 // If the identifier reference is inside a block, and it refers to a value
801 // that is outside the block, create a BlockDeclRefExpr instead of a
802 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
803 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000804 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000805 // We do not do this for things like enum constants, global variables, etc,
806 // as they do not get snapshotted.
807 //
808 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000809 // The BlocksAttr indicates the variable is bound by-reference.
810 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000811 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000812 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000813
Steve Naroff52059382008-10-10 01:28:17 +0000814 // Variable will be bound by-copy, make it const within the closure.
815 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000816 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000817 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000818 }
819 // If this reference is not in a block or if the referenced variable is
820 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000821
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000822 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000823 bool ValueDependent = false;
824 if (getLangOptions().CPlusPlus) {
825 // C++ [temp.dep.expr]p3:
826 // An id-expression is type-dependent if it contains:
827 // - an identifier that was declared with a dependent type,
828 if (VD->getType()->isDependentType())
829 TypeDependent = true;
830 // - FIXME: a template-id that is dependent,
831 // - a conversion-function-id that specifies a dependent type,
832 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
833 Name.getCXXNameType()->isDependentType())
834 TypeDependent = true;
835 // - a nested-name-specifier that contains a class-name that
836 // names a dependent type.
837 else if (SS && !SS->isEmpty()) {
838 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
839 DC; DC = DC->getParent()) {
840 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000841 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000842 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
843 if (Context.getTypeDeclType(Record)->isDependentType()) {
844 TypeDependent = true;
845 break;
846 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000847 }
848 }
849 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000850
Douglas Gregora5d84612008-12-10 20:57:37 +0000851 // C++ [temp.dep.constexpr]p2:
852 //
853 // An identifier is value-dependent if it is:
854 // - a name declared with a dependent type,
855 if (TypeDependent)
856 ValueDependent = true;
857 // - the name of a non-type template parameter,
858 else if (isa<NonTypeTemplateParmDecl>(VD))
859 ValueDependent = true;
860 // - a constant with integral or enumeration type and is
861 // initialized with an expression that is value-dependent
862 // (FIXME!).
863 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000864
Sebastian Redlcd883f72009-01-18 18:53:16 +0000865 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
866 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000867}
868
Sebastian Redlcd883f72009-01-18 18:53:16 +0000869Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
870 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000871 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000872
Chris Lattner4b009652007-07-25 00:24:17 +0000873 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000874 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000875 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
876 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
877 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000878 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000879
Chris Lattner7e637512008-01-12 08:14:25 +0000880 // Pre-defined identifiers are of type char[x], where x is the length of the
881 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000882 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000883 if (FunctionDecl *FD = getCurFunctionDecl())
884 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000885 else if (ObjCMethodDecl *MD = getCurMethodDecl())
886 Length = MD->getSynthesizedMethodSize();
887 else {
888 Diag(Loc, diag::ext_predef_outside_function);
889 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
890 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
891 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000892
893
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000894 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000895 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000896 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000897 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000898}
899
Sebastian Redlcd883f72009-01-18 18:53:16 +0000900Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000901 llvm::SmallString<16> CharBuffer;
902 CharBuffer.resize(Tok.getLength());
903 const char *ThisTokBegin = &CharBuffer[0];
904 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000905
Chris Lattner4b009652007-07-25 00:24:17 +0000906 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
907 Tok.getLocation(), PP);
908 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000909 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000910
911 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
912
Sebastian Redl75324932009-01-20 22:23:13 +0000913 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
914 Literal.isWide(),
915 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000916}
917
Sebastian Redlcd883f72009-01-18 18:53:16 +0000918Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
919 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000920 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
921 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000922 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000923 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000924 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000925 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000926 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000927
Chris Lattner4b009652007-07-25 00:24:17 +0000928 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000929 // Add padding so that NumericLiteralParser can overread by one character.
930 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000931 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000932
Chris Lattner4b009652007-07-25 00:24:17 +0000933 // Get the spelling of the token, which eliminates trigraphs, etc.
934 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000935
Chris Lattner4b009652007-07-25 00:24:17 +0000936 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
937 Tok.getLocation(), PP);
938 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000939 return ExprError();
940
Chris Lattner1de66eb2007-08-26 03:42:43 +0000941 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000942
Chris Lattner1de66eb2007-08-26 03:42:43 +0000943 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000944 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000945 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000946 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000947 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000948 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000949 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000950 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000951
952 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
953
Ted Kremenekddedbe22007-11-29 00:56:49 +0000954 // isExact will be set by GetFloatValue().
955 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000956 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
957 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000958
Chris Lattner1de66eb2007-08-26 03:42:43 +0000959 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000960 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000961 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000962 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000963
Neil Booth7421e9c2007-08-29 22:00:19 +0000964 // long long is a C99 feature.
965 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000966 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000967 Diag(Tok.getLocation(), diag::ext_longlong);
968
Chris Lattner4b009652007-07-25 00:24:17 +0000969 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000970 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000971
Chris Lattner4b009652007-07-25 00:24:17 +0000972 if (Literal.GetIntegerValue(ResultVal)) {
973 // If this value didn't fit into uintmax_t, warn and force to ull.
974 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000975 Ty = Context.UnsignedLongLongTy;
976 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000977 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000978 } else {
979 // If this value fits into a ULL, try to figure out what else it fits into
980 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000981
Chris Lattner4b009652007-07-25 00:24:17 +0000982 // Octal, Hexadecimal, and integers with a U suffix are allowed to
983 // be an unsigned int.
984 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
985
986 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000987 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000988 if (!Literal.isLong && !Literal.isLongLong) {
989 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000990 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000991
Chris Lattner4b009652007-07-25 00:24:17 +0000992 // Does it fit in a unsigned int?
993 if (ResultVal.isIntN(IntSize)) {
994 // Does it fit in a signed int?
995 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000996 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000997 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000998 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000999 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001000 }
Chris Lattner4b009652007-07-25 00:24:17 +00001001 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001002
Chris Lattner4b009652007-07-25 00:24:17 +00001003 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001004 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001005 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001006
Chris Lattner4b009652007-07-25 00:24:17 +00001007 // Does it fit in a unsigned long?
1008 if (ResultVal.isIntN(LongSize)) {
1009 // Does it fit in a signed long?
1010 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001011 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001012 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001013 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001014 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001015 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001016 }
1017
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001019 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001020 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001021
Chris Lattner4b009652007-07-25 00:24:17 +00001022 // Does it fit in a unsigned long long?
1023 if (ResultVal.isIntN(LongLongSize)) {
1024 // Does it fit in a signed long long?
1025 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001026 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001027 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001028 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001029 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001030 }
1031 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001032
Chris Lattner4b009652007-07-25 00:24:17 +00001033 // If we still couldn't decide a type, we probably have something that
1034 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001035 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001036 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001037 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001038 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001039 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001040
Chris Lattnere4068872008-05-09 05:59:00 +00001041 if (ResultVal.getBitWidth() != Width)
1042 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001043 }
Sebastian Redl75324932009-01-20 22:23:13 +00001044 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001045 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001046
Chris Lattner1de66eb2007-08-26 03:42:43 +00001047 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1048 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001049 Res = new (Context) ImaginaryLiteral(Res,
1050 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001051
1052 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001053}
1054
Sebastian Redlcd883f72009-01-18 18:53:16 +00001055Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1056 SourceLocation R, ExprArg Val) {
1057 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001058 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001059 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001060}
1061
1062/// The UsualUnaryConversions() function is *not* called by this routine.
1063/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001064bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1065 SourceLocation OpLoc,
1066 const SourceRange &ExprRange,
1067 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001068 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001069 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001070 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001071 if (isSizeof)
1072 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1073 return false;
1074 }
1075
1076 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001077 Diag(OpLoc, diag::ext_sizeof_void_type)
1078 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001079 return false;
1080 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001081
Chris Lattner159fe082009-01-24 19:46:37 +00001082 return DiagnoseIncompleteType(OpLoc, exprType,
1083 isSizeof ? diag::err_sizeof_incomplete_type :
1084 diag::err_alignof_incomplete_type,
1085 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001086}
1087
Chris Lattner8d9f7962009-01-24 20:17:12 +00001088bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1089 const SourceRange &ExprRange) {
1090 E = E->IgnoreParens();
1091
1092 // alignof decl is always ok.
1093 if (isa<DeclRefExpr>(E))
1094 return false;
1095
1096 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1097 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1098 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001099 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001100 return true;
1101 }
1102 // Other fields are ok.
1103 return false;
1104 }
1105 }
1106 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1107}
1108
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001109/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1110/// the same for @c alignof and @c __alignof
1111/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001112Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001113Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1114 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001115 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001116 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001117
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001118 QualType ArgTy;
1119 SourceRange Range;
1120 if (isType) {
1121 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1122 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001123
1124 // Verify that the operand is valid.
1125 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1126 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001127 } else {
1128 // Get the end location.
1129 Expr *ArgEx = (Expr *)TyOrEx;
1130 Range = ArgEx->getSourceRange();
1131 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001132
1133 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001134 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001135 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001136 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001137 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1138 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1139 isInvalid = true;
1140 } else {
1141 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1142 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001143
1144 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001145 DeleteExpr(ArgEx);
1146 return ExprError();
1147 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001148 }
1149
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001150 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001151 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001152 Context.getSizeType(), OpLoc,
1153 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001154}
1155
Chris Lattner5110ad52007-08-24 21:41:10 +00001156QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001157 DefaultFunctionArrayConversion(V);
1158
Chris Lattnera16e42d2007-08-26 05:39:26 +00001159 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001160 if (const ComplexType *CT = V->getType()->getAsComplexType())
1161 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001162
1163 // Otherwise they pass through real integer and floating point types here.
1164 if (V->getType()->isArithmeticType())
1165 return V->getType();
1166
1167 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001168 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001169 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001170}
1171
1172
Chris Lattner4b009652007-07-25 00:24:17 +00001173
Sebastian Redl8b769972009-01-19 00:08:26 +00001174Action::OwningExprResult
1175Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1176 tok::TokenKind Kind, ExprArg Input) {
1177 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001178
Chris Lattner4b009652007-07-25 00:24:17 +00001179 UnaryOperator::Opcode Opc;
1180 switch (Kind) {
1181 default: assert(0 && "Unknown unary op!");
1182 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1183 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1184 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001185
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001186 if (getLangOptions().CPlusPlus &&
1187 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1188 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001189 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001190 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1191
1192 // C++ [over.inc]p1:
1193 //
1194 // [...] If the function is a member function with one
1195 // parameter (which shall be of type int) or a non-member
1196 // function with two parameters (the second of which shall be
1197 // of type int), it defines the postfix increment operator ++
1198 // for objects of that type. When the postfix increment is
1199 // called as a result of using the ++ operator, the int
1200 // argument will have value zero.
1201 Expr *Args[2] = {
1202 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001203 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1204 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001205 };
1206
1207 // Build the candidate set for overloading
1208 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001209 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1210 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001211
1212 // Perform overload resolution.
1213 OverloadCandidateSet::iterator Best;
1214 switch (BestViableFunction(CandidateSet, Best)) {
1215 case OR_Success: {
1216 // We found a built-in operator or an overloaded operator.
1217 FunctionDecl *FnDecl = Best->Function;
1218
1219 if (FnDecl) {
1220 // We matched an overloaded operator. Build a call to that
1221 // operator.
1222
1223 // Convert the arguments.
1224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1225 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001226 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001227 } else {
1228 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001229 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001230 FnDecl->getParamDecl(0)->getType(),
1231 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001232 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001233 }
1234
1235 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001236 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001237 = FnDecl->getType()->getAsFunctionType()->getResultType();
1238 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001239
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001240 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001241 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001242 SourceLocation());
1243 UsualUnaryConversions(FnExpr);
1244
Sebastian Redl8b769972009-01-19 00:08:26 +00001245 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001246 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1247 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001248 } else {
1249 // We matched a built-in operator. Convert the arguments, then
1250 // break out so that we will build the appropriate built-in
1251 // operator node.
1252 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1253 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001254 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001255
1256 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001257 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001258 }
1259
1260 case OR_No_Viable_Function:
1261 // No viable function; fall through to handling this as a
1262 // built-in operator, which will produce an error message for us.
1263 break;
1264
1265 case OR_Ambiguous:
1266 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1267 << UnaryOperator::getOpcodeStr(Opc)
1268 << Arg->getSourceRange();
1269 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001270 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001271 }
1272
1273 // Either we found no viable overloaded operator or we matched a
1274 // built-in operator. In either case, fall through to trying to
1275 // build a built-in operation.
1276 }
1277
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001278 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1279 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001280 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001281 return ExprError();
1282 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001283 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001284}
1285
Sebastian Redl8b769972009-01-19 00:08:26 +00001286Action::OwningExprResult
1287Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1288 ExprArg Idx, SourceLocation RLoc) {
1289 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1290 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001291
Douglas Gregor80723c52008-11-19 17:17:41 +00001292 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001293 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001294 LHSExp->getType()->isEnumeralType() ||
1295 RHSExp->getType()->isRecordType() ||
1296 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001297 // Add the appropriate overloaded operators (C++ [over.match.oper])
1298 // to the candidate set.
1299 OverloadCandidateSet CandidateSet;
1300 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001301 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1302 SourceRange(LLoc, RLoc)))
1303 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001304
Douglas Gregor80723c52008-11-19 17:17:41 +00001305 // Perform overload resolution.
1306 OverloadCandidateSet::iterator Best;
1307 switch (BestViableFunction(CandidateSet, Best)) {
1308 case OR_Success: {
1309 // We found a built-in operator or an overloaded operator.
1310 FunctionDecl *FnDecl = Best->Function;
1311
1312 if (FnDecl) {
1313 // We matched an overloaded operator. Build a call to that
1314 // operator.
1315
1316 // Convert the arguments.
1317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1318 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1319 PerformCopyInitialization(RHSExp,
1320 FnDecl->getParamDecl(0)->getType(),
1321 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001322 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001323 } else {
1324 // Convert the arguments.
1325 if (PerformCopyInitialization(LHSExp,
1326 FnDecl->getParamDecl(0)->getType(),
1327 "passing") ||
1328 PerformCopyInitialization(RHSExp,
1329 FnDecl->getParamDecl(1)->getType(),
1330 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001331 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001332 }
1333
1334 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001335 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001336 = FnDecl->getType()->getAsFunctionType()->getResultType();
1337 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001338
Douglas Gregor80723c52008-11-19 17:17:41 +00001339 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001340 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001341 SourceLocation());
1342 UsualUnaryConversions(FnExpr);
1343
Sebastian Redl8b769972009-01-19 00:08:26 +00001344 Base.release();
1345 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001346 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001347 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001348 } else {
1349 // We matched a built-in operator. Convert the arguments, then
1350 // break out so that we will build the appropriate built-in
1351 // operator node.
1352 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1353 "passing") ||
1354 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1355 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001356 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001357
1358 break;
1359 }
1360 }
1361
1362 case OR_No_Viable_Function:
1363 // No viable function; fall through to handling this as a
1364 // built-in operator, which will produce an error message for us.
1365 break;
1366
1367 case OR_Ambiguous:
1368 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1369 << "[]"
1370 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1371 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001372 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001373 }
1374
1375 // Either we found no viable overloaded operator or we matched a
1376 // built-in operator. In either case, fall through to trying to
1377 // build a built-in operation.
1378 }
1379
Chris Lattner4b009652007-07-25 00:24:17 +00001380 // Perform default conversions.
1381 DefaultFunctionArrayConversion(LHSExp);
1382 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001383
Chris Lattner4b009652007-07-25 00:24:17 +00001384 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1385
1386 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001387 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001388 // in the subscript position. As a result, we need to derive the array base
1389 // and index from the expression types.
1390 Expr *BaseExpr, *IndexExpr;
1391 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001392 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001393 BaseExpr = LHSExp;
1394 IndexExpr = RHSExp;
1395 // FIXME: need to deal with const...
1396 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001397 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001398 // Handle the uncommon case of "123[Ptr]".
1399 BaseExpr = RHSExp;
1400 IndexExpr = LHSExp;
1401 // FIXME: need to deal with const...
1402 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001403 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1404 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001405 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001406
Chris Lattner4b009652007-07-25 00:24:17 +00001407 // FIXME: need to deal with const...
1408 ResultType = VTy->getElementType();
1409 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001410 return ExprError(Diag(LHSExp->getLocStart(),
1411 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1412 }
Chris Lattner4b009652007-07-25 00:24:17 +00001413 // C99 6.5.2.1p1
1414 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001415 return ExprError(Diag(IndexExpr->getLocStart(),
1416 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001417
1418 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1419 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001420 // void (*)(int)) and pointers to incomplete types. Functions are not
1421 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001422 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001423 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001424 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001425 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001426
Sebastian Redl8b769972009-01-19 00:08:26 +00001427 Base.release();
1428 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001429 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1430 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001431}
1432
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001433QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001434CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001435 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001436 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001437
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001438 // The vector accessor can't exceed the number of elements.
1439 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001440
1441 // This flag determines whether or not the component is one of the four
1442 // special names that indicate a subset of exactly half the elements are
1443 // to be selected.
1444 bool HalvingSwizzle = false;
1445
1446 // This flag determines whether or not CompName has an 's' char prefix,
1447 // indicating that it is a string of hex values to be used as vector indices.
1448 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001449
1450 // Check that we've found one of the special components, or that the component
1451 // names must come from the same set.
1452 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001453 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1454 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001455 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001456 do
1457 compStr++;
1458 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001459 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001460 do
1461 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001462 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001463 }
Nate Begeman1486b502009-01-18 01:47:54 +00001464
1465 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001466 // We didn't get to the end of the string. This means the component names
1467 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001468 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1469 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001470 return QualType();
1471 }
Nate Begeman1486b502009-01-18 01:47:54 +00001472
1473 // Ensure no component accessor exceeds the width of the vector type it
1474 // operates on.
1475 if (!HalvingSwizzle) {
1476 compStr = CompName.getName();
1477
1478 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001479 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001480
1481 while (*compStr) {
1482 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1483 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1484 << baseType << SourceRange(CompLoc);
1485 return QualType();
1486 }
1487 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001488 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001489
Nate Begeman1486b502009-01-18 01:47:54 +00001490 // If this is a halving swizzle, verify that the base type has an even
1491 // number of elements.
1492 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001493 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001494 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001495 return QualType();
1496 }
1497
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001498 // The component accessor looks fine - now we need to compute the actual type.
1499 // The vector type is implied by the component accessor. For example,
1500 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001501 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001502 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001503 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1504 : CompName.getLength();
1505 if (HexSwizzle)
1506 CompSize--;
1507
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001508 if (CompSize == 1)
1509 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001510
Nate Begemanaf6ed502008-04-18 23:10:10 +00001511 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001512 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001513 // diagostics look bad. We want extended vector types to appear built-in.
1514 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1515 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1516 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001517 }
1518 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001519}
1520
Chris Lattner2cb744b2009-02-15 22:43:40 +00001521
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001522/// constructSetterName - Return the setter name for the given
1523/// identifier, i.e. "set" + Name where the initial character of Name
1524/// has been capitalized.
1525// FIXME: Merge with same routine in Parser. But where should this
1526// live?
1527static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1528 const IdentifierInfo *Name) {
1529 llvm::SmallString<100> SelectorName;
1530 SelectorName = "set";
1531 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1532 SelectorName[3] = toupper(SelectorName[3]);
1533 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1534}
1535
Sebastian Redl8b769972009-01-19 00:08:26 +00001536Action::OwningExprResult
1537Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1538 tok::TokenKind OpKind, SourceLocation MemberLoc,
1539 IdentifierInfo &Member) {
1540 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001541 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001542
1543 // Perform default conversions.
1544 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001545
Steve Naroff2cb66382007-07-26 03:11:44 +00001546 QualType BaseType = BaseExpr->getType();
1547 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001548
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001549 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1550 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001551 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001552 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001553 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001554 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001555 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1556 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001557 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001558 return ExprError(Diag(MemberLoc,
1559 diag::err_typecheck_member_reference_arrow)
1560 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001561 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001562
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001563 // Handle field access to simple records. This also handles access to fields
1564 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001565 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001566 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001567 if (DiagnoseIncompleteType(OpLoc, BaseType,
1568 diag::err_typecheck_incomplete_tag,
1569 BaseExpr->getSourceRange()))
1570 return ExprError();
1571
Steve Naroff2cb66382007-07-26 03:11:44 +00001572 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001573 // FIXME: Qualified name lookup for C++ is a bit more complicated
1574 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001575 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001576 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001577 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001578
Douglas Gregor09be81b2009-02-04 17:27:36 +00001579 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001580 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001581 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1582 << &Member << BaseExpr->getSourceRange());
1583 else if (Result.isAmbiguous()) {
1584 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1585 MemberLoc, BaseExpr->getSourceRange());
1586 return ExprError();
1587 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001588 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001589
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001590 // If the decl being referenced had an error, return an error for this
1591 // sub-expr without emitting another error, in order to avoid cascading
1592 // error cases.
1593 if (MemberDecl->isInvalidDecl())
1594 return ExprError();
1595
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001596 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001597 // We may have found a field within an anonymous union or struct
1598 // (C++ [class.union]).
1599 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001600 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001601 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001602
Douglas Gregor82d44772008-12-20 23:49:58 +00001603 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1604 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001605 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001606 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1607 MemberType = Ref->getPointeeType();
1608 else {
1609 unsigned combinedQualifiers =
1610 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001611 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001612 combinedQualifiers &= ~QualType::Const;
1613 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1614 }
Eli Friedman76b49832008-02-06 22:48:16 +00001615
Steve Naroff774e4152009-01-21 00:14:39 +00001616 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1617 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001618 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001619 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001620 Var, MemberLoc,
1621 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001622 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001623 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1624 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001625 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001626 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001627 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001628 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001629 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001630 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001631 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001632 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001633 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1634 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001635
Douglas Gregor82d44772008-12-20 23:49:58 +00001636 // We found a declaration kind that we didn't expect. This is a
1637 // generic error message that tells the user that she can't refer
1638 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001639 return ExprError(Diag(MemberLoc,
1640 diag::err_typecheck_member_reference_unknown)
1641 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001642 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001643
Chris Lattnere9d71612008-07-21 04:59:05 +00001644 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1645 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001646 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001647 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001648 // If the decl being referenced had an error, return an error for this
1649 // sub-expr without emitting another error, in order to avoid cascading
1650 // error cases.
1651 if (IV->isInvalidDecl())
1652 return ExprError();
1653
Steve Naroff774e4152009-01-21 00:14:39 +00001654 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1655 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001656 OpKind == tok::arrow);
1657 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001658 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001659 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001660 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1661 << IFTy->getDecl()->getDeclName() << &Member
1662 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001663 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001664
Chris Lattnere9d71612008-07-21 04:59:05 +00001665 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1666 // pointer to a (potentially qualified) interface type.
1667 const PointerType *PTy;
1668 const ObjCInterfaceType *IFTy;
1669 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1670 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1671 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001672
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001673 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001674 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001675 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001676 MemberLoc, BaseExpr));
1677
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001678 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001679 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1680 E = IFTy->qual_end(); I != E; ++I)
1681 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001682 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001683 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001684
1685 // If that failed, look for an "implicit" property by seeing if the nullary
1686 // selector is implemented.
1687
1688 // FIXME: The logic for looking up nullary and unary selectors should be
1689 // shared with the code in ActOnInstanceMessage.
1690
1691 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1692 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001693
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001694 // If this reference is in an @implementation, check for 'private' methods.
1695 if (!Getter)
1696 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1697 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1698 if (ObjCImplementationDecl *ImpDecl =
1699 ObjCImplementations[ClassDecl->getIdentifier()])
1700 Getter = ImpDecl->getInstanceMethod(Sel);
1701
Steve Naroff04151f32008-10-22 19:16:27 +00001702 // Look through local category implementations associated with the class.
1703 if (!Getter) {
1704 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1705 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1706 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1707 }
1708 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001709 if (Getter) {
1710 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001711 // will look for the matching setter, in case it is needed.
1712 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1713 &Member);
1714 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1715 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1716 if (!Setter) {
1717 // If this reference is in an @implementation, also check for 'private'
1718 // methods.
1719 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1720 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1721 if (ObjCImplementationDecl *ImpDecl =
1722 ObjCImplementations[ClassDecl->getIdentifier()])
1723 Setter = ImpDecl->getInstanceMethod(SetterSel);
1724 }
1725 // Look through local category implementations associated with the class.
1726 if (!Setter) {
1727 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1728 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1729 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1730 }
1731 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001732
1733 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001734 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1735 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001736 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001737
1738 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1739 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001740 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001741 // Handle properties on qualified "id" protocols.
1742 const ObjCQualifiedIdType *QIdTy;
1743 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1744 // Check protocols on qualified interfaces.
1745 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001746 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001747 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001748 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001749 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001750 // Also must look for a getter name which uses property syntax.
1751 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1752 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001753 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1754 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001755 }
1756 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001757
1758 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1759 << &Member << BaseType);
1760 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001761 // Handle 'field access' to vectors, such as 'V.xx'.
1762 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001763 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1764 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001765 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001766 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1767 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001768 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001769
1770 return ExprError(Diag(MemberLoc,
1771 diag::err_typecheck_member_reference_struct_union)
1772 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001773}
1774
Douglas Gregor3257fb52008-12-22 05:46:06 +00001775/// ConvertArgumentsForCall - Converts the arguments specified in
1776/// Args/NumArgs to the parameter types of the function FDecl with
1777/// function prototype Proto. Call is the call expression itself, and
1778/// Fn is the function expression. For a C++ member function, this
1779/// routine does not attempt to convert the object argument. Returns
1780/// true if the call is ill-formed.
1781bool
1782Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1783 FunctionDecl *FDecl,
1784 const FunctionTypeProto *Proto,
1785 Expr **Args, unsigned NumArgs,
1786 SourceLocation RParenLoc) {
1787 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1788 // assignment, to the types of the corresponding parameter, ...
1789 unsigned NumArgsInProto = Proto->getNumArgs();
1790 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001791 bool Invalid = false;
1792
Douglas Gregor3257fb52008-12-22 05:46:06 +00001793 // If too few arguments are available (and we don't have default
1794 // arguments for the remaining parameters), don't make the call.
1795 if (NumArgs < NumArgsInProto) {
1796 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1797 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1798 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1799 // Use default arguments for missing arguments
1800 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001801 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001802 }
1803
1804 // If too many are passed and not variadic, error on the extras and drop
1805 // them.
1806 if (NumArgs > NumArgsInProto) {
1807 if (!Proto->isVariadic()) {
1808 Diag(Args[NumArgsInProto]->getLocStart(),
1809 diag::err_typecheck_call_too_many_args)
1810 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1811 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1812 Args[NumArgs-1]->getLocEnd());
1813 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001814 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001815 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001816 }
1817 NumArgsToCheck = NumArgsInProto;
1818 }
1819
1820 // Continue to check argument types (even if we have too few/many args).
1821 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1822 QualType ProtoArgType = Proto->getArgType(i);
1823
1824 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001825 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001826 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001827
1828 // Pass the argument.
1829 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1830 return true;
1831 } else
1832 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001833 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001834 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001835
Douglas Gregor3257fb52008-12-22 05:46:06 +00001836 Call->setArg(i, Arg);
1837 }
1838
1839 // If this is a variadic call, handle args passed through "...".
1840 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001841 VariadicCallType CallType = VariadicFunction;
1842 if (Fn->getType()->isBlockPointerType())
1843 CallType = VariadicBlock; // Block
1844 else if (isa<MemberExpr>(Fn))
1845 CallType = VariadicMethod;
1846
Douglas Gregor3257fb52008-12-22 05:46:06 +00001847 // Promote the arguments (C99 6.5.2.2p7).
1848 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1849 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001850 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001851 Call->setArg(i, Arg);
1852 }
1853 }
1854
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001855 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001856}
1857
Steve Naroff87d58b42007-09-16 03:34:24 +00001858/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001859/// This provides the location of the left/right parens and a list of comma
1860/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001861Action::OwningExprResult
1862Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1863 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001864 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001865 unsigned NumArgs = args.size();
1866 Expr *Fn = static_cast<Expr *>(fn.release());
1867 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001868 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001869 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001870 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001871
Douglas Gregor3257fb52008-12-22 05:46:06 +00001872 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001873 // Determine whether this is a dependent call inside a C++ template,
1874 // in which case we won't do any semantic analysis now.
1875 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1876 bool Dependent = false;
1877 if (Fn->isTypeDependent())
1878 Dependent = true;
1879 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1880 Dependent = true;
1881
1882 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001883 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001884 Context.DependentTy, RParenLoc));
1885
1886 // Determine whether this is a call to an object (C++ [over.call.object]).
1887 if (Fn->getType()->isRecordType())
1888 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1889 CommaLocs, RParenLoc));
1890
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001891 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001892 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1893 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1894 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001895 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1896 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001897 }
1898
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001899 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001900 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001901 Expr *FnExpr = Fn;
1902 bool ADL = true;
1903 while (true) {
1904 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1905 FnExpr = IcExpr->getSubExpr();
1906 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001907 // Parentheses around a function disable ADL
1908 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001909 ADL = false;
1910 FnExpr = PExpr->getSubExpr();
1911 } else if (isa<UnaryOperator>(FnExpr) &&
1912 cast<UnaryOperator>(FnExpr)->getOpcode()
1913 == UnaryOperator::AddrOf) {
1914 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001915 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1916 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1917 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1918 break;
1919 } else if (UnresolvedFunctionNameExpr *DepName
1920 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1921 UnqualifiedName = DepName->getName();
1922 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001923 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001924 // Any kind of name that does not refer to a declaration (or
1925 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1926 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001927 break;
1928 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001929 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001930
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001931 OverloadedFunctionDecl *Ovl = 0;
1932 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001933 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001934 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1935 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001936
Douglas Gregorfcb19192009-02-11 23:02:49 +00001937 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001938 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00001939 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001940 ADL = false;
1941
Douglas Gregorfcb19192009-02-11 23:02:49 +00001942 // We don't perform ADL in C.
1943 if (!getLangOptions().CPlusPlus)
1944 ADL = false;
1945
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001946 if (Ovl || ADL) {
1947 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1948 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001949 NumArgs, CommaLocs, RParenLoc, ADL);
1950 if (!FDecl)
1951 return ExprError();
1952
1953 // Update Fn to refer to the actual function selected.
1954 Expr *NewFn = 0;
1955 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001956 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001957 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1958 QDRExpr->getLocation(),
1959 false, false,
1960 QDRExpr->getSourceRange().getBegin());
1961 else
1962 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1963 Fn->getSourceRange().getBegin());
1964 Fn->Destroy(Context);
1965 Fn = NewFn;
1966 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001967 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001968
1969 // Promote the function operand.
1970 UsualUnaryConversions(Fn);
1971
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001972 // Make the call expr early, before semantic checks. This guarantees cleanup
1973 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001974 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1975 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00001976 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
1977 Args, NumArgs,
1978 Context.BoolTy,
1979 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001980
Steve Naroffd6163f32008-09-05 22:11:13 +00001981 const FunctionType *FuncT;
1982 if (!Fn->getType()->isBlockPointerType()) {
1983 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1984 // have type pointer to function".
1985 const PointerType *PT = Fn->getType()->getAsPointerType();
1986 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001987 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1988 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001989 FuncT = PT->getPointeeType()->getAsFunctionType();
1990 } else { // This is a block call.
1991 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1992 getAsFunctionType();
1993 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001994 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001995 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1996 << Fn->getType() << Fn->getSourceRange());
1997
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001998 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001999 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002000
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002001 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002002 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2003 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002004 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002005 } else {
2006 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002007
Steve Naroffdb65e052007-08-28 23:30:39 +00002008 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002009 for (unsigned i = 0; i != NumArgs; i++) {
2010 Expr *Arg = Args[i];
2011 DefaultArgumentPromotion(Arg);
2012 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002013 }
Chris Lattner4b009652007-07-25 00:24:17 +00002014 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002015
Douglas Gregor3257fb52008-12-22 05:46:06 +00002016 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2017 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002018 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2019 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002020
Chris Lattner2e64c072007-08-10 20:18:51 +00002021 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002022 if (FDecl)
2023 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002024
Sebastian Redl8b769972009-01-19 00:08:26 +00002025 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002026}
2027
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002028Action::OwningExprResult
2029Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2030 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002031 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002032 QualType literalType = QualType::getFromOpaquePtr(Ty);
2033 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002034 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002035 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002036
Eli Friedman8c2173d2008-05-20 05:22:08 +00002037 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002038 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002039 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2040 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002041 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2042 diag::err_typecheck_decl_incomplete_type,
2043 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002044 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002045
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002046 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002047 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002048 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002049
Chris Lattnere5cb5862008-12-04 23:50:19 +00002050 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002051 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002052 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002053 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002054 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002055 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002056 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2057 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002058}
2059
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002060Action::OwningExprResult
2061Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2062 InitListDesignations &Designators,
2063 SourceLocation RBraceLoc) {
2064 unsigned NumInit = initlist.size();
2065 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002066
Steve Naroff0acc9c92007-09-15 18:49:24 +00002067 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002068 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002069
Steve Naroff774e4152009-01-21 00:14:39 +00002070 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002071 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002072 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002073 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002074}
2075
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002076/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002077bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002078 UsualUnaryConversions(castExpr);
2079
2080 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2081 // type needs to be scalar.
2082 if (castType->isVoidType()) {
2083 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002084 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2085 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002086 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002087 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2088 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2089 (castType->isStructureType() || castType->isUnionType())) {
2090 // GCC struct/union extension: allow cast to self.
2091 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2092 << castType << castExpr->getSourceRange();
2093 } else if (castType->isUnionType()) {
2094 // GCC cast to union extension
2095 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2096 RecordDecl::field_iterator Field, FieldEnd;
2097 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2098 Field != FieldEnd; ++Field) {
2099 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2100 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2101 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2102 << castExpr->getSourceRange();
2103 break;
2104 }
2105 }
2106 if (Field == FieldEnd)
2107 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2108 << castExpr->getType() << castExpr->getSourceRange();
2109 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002110 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002111 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002112 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002113 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002114 } else if (!castExpr->getType()->isScalarType() &&
2115 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002116 return Diag(castExpr->getLocStart(),
2117 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002118 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002119 } else if (castExpr->getType()->isVectorType()) {
2120 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2121 return true;
2122 } else if (castType->isVectorType()) {
2123 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2124 return true;
2125 }
2126 return false;
2127}
2128
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002129bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002130 assert(VectorTy->isVectorType() && "Not a vector type!");
2131
2132 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002133 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002134 return Diag(R.getBegin(),
2135 Ty->isVectorType() ?
2136 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002137 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002138 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002139 } else
2140 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002141 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002142 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002143
2144 return false;
2145}
2146
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002147Action::OwningExprResult
2148Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2149 SourceLocation RParenLoc, ExprArg Op) {
2150 assert((Ty != 0) && (Op.get() != 0) &&
2151 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002152
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002153 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002154 QualType castType = QualType::getFromOpaquePtr(Ty);
2155
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002156 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002157 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002158 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002159 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002160}
2161
Chris Lattner98a425c2007-11-26 01:40:58 +00002162/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2163/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002164inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2165 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2166 UsualUnaryConversions(cond);
2167 UsualUnaryConversions(lex);
2168 UsualUnaryConversions(rex);
2169 QualType condT = cond->getType();
2170 QualType lexT = lex->getType();
2171 QualType rexT = rex->getType();
2172
2173 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002174 if (!cond->isTypeDependent()) {
2175 if (!condT->isScalarType()) { // C99 6.5.15p2
2176 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2177 return QualType();
2178 }
Chris Lattner4b009652007-07-25 00:24:17 +00002179 }
Chris Lattner992ae932008-01-06 22:42:25 +00002180
2181 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002182 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2183 return Context.DependentTy;
2184
Chris Lattner992ae932008-01-06 22:42:25 +00002185 // If both operands have arithmetic type, do the usual arithmetic conversions
2186 // to find a common type: C99 6.5.15p3,5.
2187 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002188 UsualArithmeticConversions(lex, rex);
2189 return lex->getType();
2190 }
Chris Lattner992ae932008-01-06 22:42:25 +00002191
2192 // If both operands are the same structure or union type, the result is that
2193 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002194 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002195 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002196 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002197 // "If both the operands have structure or union type, the result has
2198 // that type." This implies that CV qualifiers are dropped.
2199 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002200 }
Chris Lattner992ae932008-01-06 22:42:25 +00002201
2202 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002203 // The following || allows only one side to be void (a GCC-ism).
2204 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002205 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002206 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2207 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002208 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002209 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2210 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002211 ImpCastExprToType(lex, Context.VoidTy);
2212 ImpCastExprToType(rex, Context.VoidTy);
2213 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002214 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002215 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2216 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002217 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2218 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002219 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002220 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002221 return lexT;
2222 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002223 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2224 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002225 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002226 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002227 return rexT;
2228 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002229 // Handle the case where both operands are pointers before we handle null
2230 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002231 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2232 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2233 // get the "pointed to" types
2234 QualType lhptee = LHSPT->getPointeeType();
2235 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002236
Chris Lattner71225142007-07-31 21:27:01 +00002237 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2238 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002239 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002240 // Figure out necessary qualifiers (C99 6.5.15p6)
2241 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002242 QualType destType = Context.getPointerType(destPointee);
2243 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2244 ImpCastExprToType(rex, destType); // promote to void*
2245 return destType;
2246 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002247 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002248 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002249 QualType destType = Context.getPointerType(destPointee);
2250 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2251 ImpCastExprToType(rex, destType); // promote to void*
2252 return destType;
2253 }
Chris Lattner4b009652007-07-25 00:24:17 +00002254
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002255 QualType compositeType = lexT;
2256
2257 // If either type is an Objective-C object type then check
2258 // compatibility according to Objective-C.
2259 if (Context.isObjCObjectPointerType(lexT) ||
2260 Context.isObjCObjectPointerType(rexT)) {
2261 // If both operands are interfaces and either operand can be
2262 // assigned to the other, use that type as the composite
2263 // type. This allows
2264 // xxx ? (A*) a : (B*) b
2265 // where B is a subclass of A.
2266 //
2267 // Additionally, as for assignment, if either type is 'id'
2268 // allow silent coercion. Finally, if the types are
2269 // incompatible then make sure to use 'id' as the composite
2270 // type so the result is acceptable for sending messages to.
2271
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002272 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2273 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002274 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2275 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2276 if (LHSIface && RHSIface &&
2277 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2278 compositeType = lexT;
2279 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002280 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002281 compositeType = rexT;
Steve Naroff17c03822009-02-12 17:52:19 +00002282 } else if (Context.isObjCIdStructType(lhptee) ||
2283 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002284 compositeType = Context.getObjCIdType();
2285 } else {
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002286 Diag(questionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2287 << lexT << rexT
2288 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002289 QualType incompatTy = Context.getObjCIdType();
2290 ImpCastExprToType(lex, incompatTy);
2291 ImpCastExprToType(rex, incompatTy);
2292 return incompatTy;
2293 }
2294 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2295 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002296 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002297 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002298 // In this situation, we assume void* type. No especially good
2299 // reason, but this is what gcc does, and we do have to pick
2300 // to get a consistent AST.
2301 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002302 ImpCastExprToType(lex, incompatTy);
2303 ImpCastExprToType(rex, incompatTy);
2304 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002305 }
2306 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002307 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2308 // differently qualified versions of compatible types, the result type is
2309 // a pointer to an appropriately qualified version of the *composite*
2310 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002311 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002312 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002313 ImpCastExprToType(lex, compositeType);
2314 ImpCastExprToType(rex, compositeType);
2315 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002316 }
Chris Lattner4b009652007-07-25 00:24:17 +00002317 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002318 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2319 // evaluates to "struct objc_object *" (and is handled above when comparing
2320 // id with statically typed objects).
2321 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2322 // GCC allows qualified id and any Objective-C type to devolve to
2323 // id. Currently localizing to here until clear this should be
2324 // part of ObjCQualifiedIdTypesAreCompatible.
2325 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2326 (lexT->isObjCQualifiedIdType() &&
2327 Context.isObjCObjectPointerType(rexT)) ||
2328 (rexT->isObjCQualifiedIdType() &&
2329 Context.isObjCObjectPointerType(lexT))) {
2330 // FIXME: This is not the correct composite type. This only
2331 // happens to work because id can more or less be used anywhere,
2332 // however this may change the type of method sends.
2333 // FIXME: gcc adds some type-checking of the arguments and emits
2334 // (confusing) incompatible comparison warnings in some
2335 // cases. Investigate.
2336 QualType compositeType = Context.getObjCIdType();
2337 ImpCastExprToType(lex, compositeType);
2338 ImpCastExprToType(rex, compositeType);
2339 return compositeType;
2340 }
2341 }
2342
Steve Naroff3eac7692008-09-10 19:17:48 +00002343 // Selection between block pointer types is ok as long as they are the same.
2344 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2345 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2346 return lexT;
2347
Chris Lattner992ae932008-01-06 22:42:25 +00002348 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002349 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002350 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002351 return QualType();
2352}
2353
Steve Naroff87d58b42007-09-16 03:34:24 +00002354/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002355/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002356Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2357 SourceLocation ColonLoc,
2358 ExprArg Cond, ExprArg LHS,
2359 ExprArg RHS) {
2360 Expr *CondExpr = (Expr *) Cond.get();
2361 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002362
2363 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2364 // was the condition.
2365 bool isLHSNull = LHSExpr == 0;
2366 if (isLHSNull)
2367 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002368
2369 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002370 RHSExpr, QuestionLoc);
2371 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002372 return ExprError();
2373
2374 Cond.release();
2375 LHS.release();
2376 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002377 return Owned(new (Context) ConditionalOperator(CondExpr,
2378 isLHSNull ? 0 : LHSExpr,
2379 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002380}
2381
Chris Lattner4b009652007-07-25 00:24:17 +00002382
2383// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2384// being closely modeled after the C99 spec:-). The odd characteristic of this
2385// routine is it effectively iqnores the qualifiers on the top level pointee.
2386// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2387// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002388Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002389Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2390 QualType lhptee, rhptee;
2391
2392 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002393 lhptee = lhsType->getAsPointerType()->getPointeeType();
2394 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002395
2396 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002397 lhptee = Context.getCanonicalType(lhptee);
2398 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002399
Chris Lattner005ed752008-01-04 18:04:52 +00002400 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002401
2402 // C99 6.5.16.1p1: This following citation is common to constraints
2403 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2404 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002405 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002406 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002407 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002408
2409 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2410 // incomplete type and the other is a pointer to a qualified or unqualified
2411 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002412 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002413 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002414 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002415
2416 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002417 assert(rhptee->isFunctionType());
2418 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002419 }
2420
2421 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002422 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002423 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002424
2425 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002426 assert(lhptee->isFunctionType());
2427 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002428 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002429
2430 // Check for ObjC interfaces
2431 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2432 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2433 if (LHSIface && RHSIface &&
2434 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2435 return ConvTy;
2436
2437 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002438 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002439 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002440 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002441 return ConvTy;
2442
Chris Lattner4b009652007-07-25 00:24:17 +00002443 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2444 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002445 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2446 rhptee.getUnqualifiedType()))
2447 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002448 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002449}
2450
Steve Naroff3454b6c2008-09-04 15:10:53 +00002451/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2452/// block pointer types are compatible or whether a block and normal pointer
2453/// are compatible. It is more restrict than comparing two function pointer
2454// types.
2455Sema::AssignConvertType
2456Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2457 QualType rhsType) {
2458 QualType lhptee, rhptee;
2459
2460 // get the "pointed to" type (ignoring qualifiers at the top level)
2461 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2462 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2463
2464 // make sure we operate on the canonical type
2465 lhptee = Context.getCanonicalType(lhptee);
2466 rhptee = Context.getCanonicalType(rhptee);
2467
2468 AssignConvertType ConvTy = Compatible;
2469
2470 // For blocks we enforce that qualifiers are identical.
2471 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2472 ConvTy = CompatiblePointerDiscardsQualifiers;
2473
2474 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2475 return IncompatibleBlockPointer;
2476 return ConvTy;
2477}
2478
Chris Lattner4b009652007-07-25 00:24:17 +00002479/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2480/// has code to accommodate several GCC extensions when type checking
2481/// pointers. Here are some objectionable examples that GCC considers warnings:
2482///
2483/// int a, *pint;
2484/// short *pshort;
2485/// struct foo *pfoo;
2486///
2487/// pint = pshort; // warning: assignment from incompatible pointer type
2488/// a = pint; // warning: assignment makes integer from pointer without a cast
2489/// pint = a; // warning: assignment makes pointer from integer without a cast
2490/// pint = pfoo; // warning: assignment from incompatible pointer type
2491///
2492/// As a result, the code for dealing with pointers is more complex than the
2493/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002494///
Chris Lattner005ed752008-01-04 18:04:52 +00002495Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002496Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002497 // Get canonical types. We're not formatting these types, just comparing
2498 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002499 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2500 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002501
2502 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002503 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002504
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002505 // If the left-hand side is a reference type, then we are in a
2506 // (rare!) case where we've allowed the use of references in C,
2507 // e.g., as a parameter type in a built-in function. In this case,
2508 // just make sure that the type referenced is compatible with the
2509 // right-hand side type. The caller is responsible for adjusting
2510 // lhsType so that the resulting expression does not have reference
2511 // type.
2512 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2513 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002514 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002515 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002516 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002517
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002518 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2519 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002520 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002521 // Relax integer conversions like we do for pointers below.
2522 if (rhsType->isIntegerType())
2523 return IntToPointer;
2524 if (lhsType->isIntegerType())
2525 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002526 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002527 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002528
Nate Begemanc5f0f652008-07-14 18:02:46 +00002529 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002530 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002531 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2532 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002533 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002534
Nate Begemanc5f0f652008-07-14 18:02:46 +00002535 // If we are allowing lax vector conversions, and LHS and RHS are both
2536 // vectors, the total size only needs to be the same. This is a bitcast;
2537 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002538 if (getLangOptions().LaxVectorConversions &&
2539 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002540 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002541 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002542 }
2543 return Incompatible;
2544 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002545
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002546 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002547 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002548
Chris Lattner390564e2008-04-07 06:49:41 +00002549 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002550 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002551 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002552
Chris Lattner390564e2008-04-07 06:49:41 +00002553 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002554 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002555
Steve Naroffa982c712008-09-29 18:10:17 +00002556 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002557 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002558 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002559
2560 // Treat block pointers as objects.
2561 if (getLangOptions().ObjC1 &&
2562 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2563 return Compatible;
2564 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002565 return Incompatible;
2566 }
2567
2568 if (isa<BlockPointerType>(lhsType)) {
2569 if (rhsType->isIntegerType())
2570 return IntToPointer;
2571
Steve Naroffa982c712008-09-29 18:10:17 +00002572 // Treat block pointers as objects.
2573 if (getLangOptions().ObjC1 &&
2574 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2575 return Compatible;
2576
Steve Naroff3454b6c2008-09-04 15:10:53 +00002577 if (rhsType->isBlockPointerType())
2578 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2579
2580 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2581 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002582 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002583 }
Chris Lattner1853da22008-01-04 23:18:45 +00002584 return Incompatible;
2585 }
2586
Chris Lattner390564e2008-04-07 06:49:41 +00002587 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002588 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002589 if (lhsType == Context.BoolTy)
2590 return Compatible;
2591
2592 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002593 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002594
Chris Lattner390564e2008-04-07 06:49:41 +00002595 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002596 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002597
2598 if (isa<BlockPointerType>(lhsType) &&
2599 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002600 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002601 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002602 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002603
Chris Lattner1853da22008-01-04 23:18:45 +00002604 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002605 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002606 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002607 }
2608 return Incompatible;
2609}
2610
Chris Lattner005ed752008-01-04 18:04:52 +00002611Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002612Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002613 if (getLangOptions().CPlusPlus) {
2614 if (!lhsType->isRecordType()) {
2615 // C++ 5.17p3: If the left operand is not of class type, the
2616 // expression is implicitly converted (C++ 4) to the
2617 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002618 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2619 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002620 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002621 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002622 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002623 }
2624
2625 // FIXME: Currently, we fall through and treat C++ classes like C
2626 // structures.
2627 }
2628
Steve Naroffcdee22d2007-11-27 17:58:44 +00002629 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2630 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002631 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2632 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002633 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002634 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002635 return Compatible;
2636 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002637
2638 // We don't allow conversion of non-null-pointer constants to integers.
2639 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2640 return IntToBlockPointer;
2641
Chris Lattner5f505bf2007-10-16 02:55:40 +00002642 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002643 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002644 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002645 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002646 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002647 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002648 if (!lhsType->isReferenceType())
2649 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002650
Chris Lattner005ed752008-01-04 18:04:52 +00002651 Sema::AssignConvertType result =
2652 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002653
2654 // C99 6.5.16.1p2: The value of the right operand is converted to the
2655 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002656 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2657 // so that we can use references in built-in functions even in C.
2658 // The getNonReferenceType() call makes sure that the resulting expression
2659 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002660 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002661 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002662 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002663}
2664
Chris Lattner005ed752008-01-04 18:04:52 +00002665Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002666Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2667 return CheckAssignmentConstraints(lhsType, rhsType);
2668}
2669
Chris Lattner1eafdea2008-11-18 01:30:42 +00002670QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002671 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002672 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002673 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002674 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002675}
2676
Chris Lattner1eafdea2008-11-18 01:30:42 +00002677inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002678 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002679 // For conversion purposes, we ignore any qualifiers.
2680 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002681 QualType lhsType =
2682 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2683 QualType rhsType =
2684 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002685
Nate Begemanc5f0f652008-07-14 18:02:46 +00002686 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002687 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002688 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002689
Nate Begemanc5f0f652008-07-14 18:02:46 +00002690 // Handle the case of a vector & extvector type of the same size and element
2691 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002692 if (getLangOptions().LaxVectorConversions) {
2693 // FIXME: Should we warn here?
2694 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002695 if (const VectorType *RV = rhsType->getAsVectorType())
2696 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002697 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002698 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002699 }
2700 }
2701 }
2702
Nate Begemanc5f0f652008-07-14 18:02:46 +00002703 // If the lhs is an extended vector and the rhs is a scalar of the same type
2704 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002705 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002706 QualType eltType = V->getElementType();
2707
2708 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2709 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2710 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002711 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002712 return lhsType;
2713 }
2714 }
2715
Nate Begemanc5f0f652008-07-14 18:02:46 +00002716 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002717 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002718 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002719 QualType eltType = V->getElementType();
2720
2721 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2722 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2723 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002724 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002725 return rhsType;
2726 }
2727 }
2728
Chris Lattner4b009652007-07-25 00:24:17 +00002729 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002730 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002731 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002732 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002733 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002734}
2735
Chris Lattner4b009652007-07-25 00:24:17 +00002736inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002737 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002738{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002739 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002740 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002741
Steve Naroff8f708362007-08-24 19:07:16 +00002742 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002743
Chris Lattner4b009652007-07-25 00:24:17 +00002744 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002745 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002746 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002747}
2748
2749inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002750 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002751{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002752 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2753 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2754 return CheckVectorOperands(Loc, lex, rex);
2755 return InvalidOperands(Loc, lex, rex);
2756 }
Chris Lattner4b009652007-07-25 00:24:17 +00002757
Steve Naroff8f708362007-08-24 19:07:16 +00002758 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002759
Chris Lattner4b009652007-07-25 00:24:17 +00002760 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002761 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002762 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002763}
2764
2765inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002766 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002767{
2768 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002769 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002770
Steve Naroff8f708362007-08-24 19:07:16 +00002771 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002772
Chris Lattner4b009652007-07-25 00:24:17 +00002773 // handle the common case first (both operands are arithmetic).
2774 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002775 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002776
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002777 // Put any potential pointer into PExp
2778 Expr* PExp = lex, *IExp = rex;
2779 if (IExp->getType()->isPointerType())
2780 std::swap(PExp, IExp);
2781
2782 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2783 if (IExp->getType()->isIntegerType()) {
2784 // Check for arithmetic on pointers to incomplete types
2785 if (!PTy->getPointeeType()->isObjectType()) {
2786 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002787 if (getLangOptions().CPlusPlus) {
2788 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2789 << lex->getSourceRange() << rex->getSourceRange();
2790 return QualType();
2791 }
2792
2793 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002794 Diag(Loc, diag::ext_gnu_void_ptr)
2795 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002796 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002797 if (getLangOptions().CPlusPlus) {
2798 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2799 << lex->getType() << lex->getSourceRange();
2800 return QualType();
2801 }
2802
2803 // GNU extension: arithmetic on pointer to function
2804 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002805 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002806 } else {
2807 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2808 diag::err_typecheck_arithmetic_incomplete_type,
2809 lex->getSourceRange(), SourceRange(),
2810 lex->getType());
2811 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002812 }
2813 }
2814 return PExp->getType();
2815 }
2816 }
2817
Chris Lattner1eafdea2008-11-18 01:30:42 +00002818 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002819}
2820
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002821// C99 6.5.6
2822QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002823 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002824 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002825 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002826
Steve Naroff8f708362007-08-24 19:07:16 +00002827 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002828
Chris Lattnerf6da2912007-12-09 21:53:25 +00002829 // Enforce type constraints: C99 6.5.6p3.
2830
2831 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002832 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002833 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002834
2835 // Either ptr - int or ptr - ptr.
2836 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002837 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002838
Chris Lattnerf6da2912007-12-09 21:53:25 +00002839 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002840 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002841 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002842 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002843 Diag(Loc, diag::ext_gnu_void_ptr)
2844 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002845 } else if (lpointee->isFunctionType()) {
2846 if (getLangOptions().CPlusPlus) {
2847 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2848 << lex->getType() << lex->getSourceRange();
2849 return QualType();
2850 }
2851
2852 // GNU extension: arithmetic on pointer to function
2853 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2854 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002855 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002856 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002857 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002858 return QualType();
2859 }
2860 }
2861
2862 // The result type of a pointer-int computation is the pointer type.
2863 if (rex->getType()->isIntegerType())
2864 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002865
Chris Lattnerf6da2912007-12-09 21:53:25 +00002866 // Handle pointer-pointer subtractions.
2867 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002868 QualType rpointee = RHSPTy->getPointeeType();
2869
Chris Lattnerf6da2912007-12-09 21:53:25 +00002870 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002871 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002872 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002873 if (rpointee->isVoidType()) {
2874 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002875 Diag(Loc, diag::ext_gnu_void_ptr)
2876 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002877 } else if (rpointee->isFunctionType()) {
2878 if (getLangOptions().CPlusPlus) {
2879 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2880 << rex->getType() << rex->getSourceRange();
2881 return QualType();
2882 }
2883
2884 // GNU extension: arithmetic on pointer to function
2885 if (!lpointee->isFunctionType())
2886 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2887 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002888 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002889 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002890 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002891 return QualType();
2892 }
2893 }
2894
2895 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002896 if (!Context.typesAreCompatible(
2897 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2898 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002899 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002900 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002901 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002902 return QualType();
2903 }
2904
2905 return Context.getPointerDiffType();
2906 }
2907 }
2908
Chris Lattner1eafdea2008-11-18 01:30:42 +00002909 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002910}
2911
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002912// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002913QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002914 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002915 // C99 6.5.7p2: Each of the operands shall have integer type.
2916 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002917 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002918
Chris Lattner2c8bff72007-12-12 05:47:28 +00002919 // Shifts don't perform usual arithmetic conversions, they just do integer
2920 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002921 if (!isCompAssign)
2922 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002923 UsualUnaryConversions(rex);
2924
2925 // "The type of the result is that of the promoted left operand."
2926 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002927}
2928
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002929// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002930QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002931 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002932 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002933 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002934
Chris Lattner254f3bc2007-08-26 01:18:55 +00002935 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002936 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2937 UsualArithmeticConversions(lex, rex);
2938 else {
2939 UsualUnaryConversions(lex);
2940 UsualUnaryConversions(rex);
2941 }
Chris Lattner4b009652007-07-25 00:24:17 +00002942 QualType lType = lex->getType();
2943 QualType rType = rex->getType();
2944
Ted Kremenek486509e2007-10-29 17:13:39 +00002945 // For non-floating point types, check for self-comparisons of the form
2946 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2947 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002948 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002949 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2950 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002951 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002952 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002953 }
2954
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002955 // The result of comparisons is 'bool' in C++, 'int' in C.
2956 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2957
Chris Lattner254f3bc2007-08-26 01:18:55 +00002958 if (isRelational) {
2959 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002960 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002961 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002962 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002963 if (lType->isFloatingType()) {
2964 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002965 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002966 }
2967
Chris Lattner254f3bc2007-08-26 01:18:55 +00002968 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002969 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002970 }
Chris Lattner4b009652007-07-25 00:24:17 +00002971
Chris Lattner22be8422007-08-26 01:10:14 +00002972 bool LHSIsNull = lex->isNullPointerConstant(Context);
2973 bool RHSIsNull = rex->isNullPointerConstant(Context);
2974
Chris Lattner254f3bc2007-08-26 01:18:55 +00002975 // All of the following pointer related warnings are GCC extensions, except
2976 // when handling null pointer constants. One day, we can consider making them
2977 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002978 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002979 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002980 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002981 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002982 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002983
Steve Naroff3b435622007-11-13 14:57:38 +00002984 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002985 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2986 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002987 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00002988 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002989 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002990 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002991 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002992 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002993 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002994 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002995 // Handle block pointer types.
2996 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2997 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2998 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2999
3000 if (!LHSIsNull && !RHSIsNull &&
3001 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003002 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003003 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003004 }
3005 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003006 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003007 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003008 // Allow block pointers to be compared with null pointer constants.
3009 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3010 (lType->isPointerType() && rType->isBlockPointerType())) {
3011 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003012 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003013 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003014 }
3015 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003016 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003017 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003018
Steve Naroff936c4362008-06-03 14:04:54 +00003019 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003020 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003021 const PointerType *LPT = lType->getAsPointerType();
3022 const PointerType *RPT = rType->getAsPointerType();
3023 bool LPtrToVoid = LPT ?
3024 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3025 bool RPtrToVoid = RPT ?
3026 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3027
3028 if (!LPtrToVoid && !RPtrToVoid &&
3029 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003030 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003031 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003032 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003033 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003034 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003035 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003036 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003037 }
Steve Naroff936c4362008-06-03 14:04:54 +00003038 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3039 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003040 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003041 } else {
3042 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003043 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003044 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003045 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003046 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003047 }
Steve Naroff936c4362008-06-03 14:04:54 +00003048 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003049 }
Steve Naroff936c4362008-06-03 14:04:54 +00003050 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3051 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003052 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003053 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003054 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003055 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003056 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003057 }
Steve Naroff936c4362008-06-03 14:04:54 +00003058 if (lType->isIntegerType() &&
3059 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003060 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003061 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003062 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003063 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003064 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003065 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003066 // Handle block pointers.
3067 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3068 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003069 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003070 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003071 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003072 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003073 }
3074 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3075 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003076 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003077 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003078 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003079 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003080 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003081 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003082}
3083
Nate Begemanc5f0f652008-07-14 18:02:46 +00003084/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3085/// operates on extended vector types. Instead of producing an IntTy result,
3086/// like a scalar comparison, a vector comparison produces a vector of integer
3087/// types.
3088QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003089 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003090 bool isRelational) {
3091 // Check to make sure we're operating on vectors of the same type and width,
3092 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003093 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003094 if (vType.isNull())
3095 return vType;
3096
3097 QualType lType = lex->getType();
3098 QualType rType = rex->getType();
3099
3100 // For non-floating point types, check for self-comparisons of the form
3101 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3102 // often indicate logic errors in the program.
3103 if (!lType->isFloatingType()) {
3104 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3105 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3106 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003107 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003108 }
3109
3110 // Check for comparisons of floating point operands using != and ==.
3111 if (!isRelational && lType->isFloatingType()) {
3112 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003113 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003114 }
3115
3116 // Return the type for the comparison, which is the same as vector type for
3117 // integer vectors, or an integer type of identical size and number of
3118 // elements for floating point vectors.
3119 if (lType->isIntegerType())
3120 return lType;
3121
3122 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003123 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003124 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003125 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003126 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3127 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3128
3129 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3130 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003131 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3132}
3133
Chris Lattner4b009652007-07-25 00:24:17 +00003134inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003135 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003136{
3137 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003138 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003139
Steve Naroff8f708362007-08-24 19:07:16 +00003140 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003141
3142 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003143 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003144 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003145}
3146
3147inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003148 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003149{
3150 UsualUnaryConversions(lex);
3151 UsualUnaryConversions(rex);
3152
Eli Friedmanbea3f842008-05-13 20:16:47 +00003153 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003154 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003155 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003156}
3157
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003158/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3159/// is a read-only property; return true if so. A readonly property expression
3160/// depends on various declarations and thus must be treated specially.
3161///
3162static bool IsReadonlyProperty(Expr *E, Sema &S)
3163{
3164 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3165 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3166 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3167 QualType BaseType = PropExpr->getBase()->getType();
3168 if (const PointerType *PTy = BaseType->getAsPointerType())
3169 if (const ObjCInterfaceType *IFTy =
3170 PTy->getPointeeType()->getAsObjCInterfaceType())
3171 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3172 if (S.isPropertyReadonly(PDecl, IFace))
3173 return true;
3174 }
3175 }
3176 return false;
3177}
3178
Chris Lattner4c2642c2008-11-18 01:22:49 +00003179/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3180/// emit an error and return true. If so, return false.
3181static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003182 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3183 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3184 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003185 if (IsLV == Expr::MLV_Valid)
3186 return false;
3187
3188 unsigned Diag = 0;
3189 bool NeedType = false;
3190 switch (IsLV) { // C99 6.5.16p2
3191 default: assert(0 && "Unknown result from isModifiableLvalue!");
3192 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003193 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003194 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3195 NeedType = true;
3196 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003197 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003198 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3199 NeedType = true;
3200 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003201 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003202 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3203 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003204 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003205 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3206 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003207 case Expr::MLV_IncompleteType:
3208 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003209 return S.DiagnoseIncompleteType(Loc, E->getType(),
3210 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3211 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003212 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003213 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3214 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003215 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003216 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3217 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003218 case Expr::MLV_ReadonlyProperty:
3219 Diag = diag::error_readonly_property_assignment;
3220 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003221 case Expr::MLV_NoSetterProperty:
3222 Diag = diag::error_nosetter_property_assignment;
3223 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003224 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003225
Chris Lattner4c2642c2008-11-18 01:22:49 +00003226 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003227 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003228 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003229 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003230 return true;
3231}
3232
3233
3234
3235// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003236QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3237 SourceLocation Loc,
3238 QualType CompoundType) {
3239 // Verify that LHS is a modifiable lvalue, and emit error if not.
3240 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003241 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003242
3243 QualType LHSType = LHS->getType();
3244 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003245
Chris Lattner005ed752008-01-04 18:04:52 +00003246 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003247 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003248 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003249 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003250 // Special case of NSObject attributes on c-style pointer types.
3251 if (ConvTy == IncompatiblePointer &&
3252 ((Context.isObjCNSObjectType(LHSType) &&
3253 Context.isObjCObjectPointerType(RHSType)) ||
3254 (Context.isObjCNSObjectType(RHSType) &&
3255 Context.isObjCObjectPointerType(LHSType))))
3256 ConvTy = Compatible;
3257
Chris Lattner34c85082008-08-21 18:04:13 +00003258 // If the RHS is a unary plus or minus, check to see if they = and + are
3259 // right next to each other. If so, the user may have typo'd "x =+ 4"
3260 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003261 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003262 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3263 RHSCheck = ICE->getSubExpr();
3264 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3265 if ((UO->getOpcode() == UnaryOperator::Plus ||
3266 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003267 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003268 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003269 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003270 Diag(Loc, diag::warn_not_compound_assign)
3271 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3272 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003273 }
3274 } else {
3275 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003276 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003277 }
Chris Lattner005ed752008-01-04 18:04:52 +00003278
Chris Lattner1eafdea2008-11-18 01:30:42 +00003279 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3280 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003281 return QualType();
3282
Chris Lattner4b009652007-07-25 00:24:17 +00003283 // C99 6.5.16p3: The type of an assignment expression is the type of the
3284 // left operand unless the left operand has qualified type, in which case
3285 // it is the unqualified version of the type of the left operand.
3286 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3287 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003288 // C++ 5.17p1: the type of the assignment expression is that of its left
3289 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003290 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003291}
3292
Chris Lattner1eafdea2008-11-18 01:30:42 +00003293// C99 6.5.17
3294QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3295 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003296
3297 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003298 DefaultFunctionArrayConversion(RHS);
3299 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003300}
3301
3302/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3303/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003304QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3305 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003306 QualType ResType = Op->getType();
3307 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003308
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003309 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3310 // Decrement of bool is not allowed.
3311 if (!isInc) {
3312 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3313 return QualType();
3314 }
3315 // Increment of bool sets it to true, but is deprecated.
3316 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3317 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003318 // OK!
3319 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3320 // C99 6.5.2.4p2, 6.5.6p2
3321 if (PT->getPointeeType()->isObjectType()) {
3322 // Pointer to object is ok!
3323 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003324 if (getLangOptions().CPlusPlus) {
3325 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3326 << Op->getSourceRange();
3327 return QualType();
3328 }
3329
3330 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003331 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003332 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003333 if (getLangOptions().CPlusPlus) {
3334 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3335 << Op->getType() << Op->getSourceRange();
3336 return QualType();
3337 }
3338
3339 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003340 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003341 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003342 } else {
3343 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3344 diag::err_typecheck_arithmetic_incomplete_type,
3345 Op->getSourceRange(), SourceRange(),
3346 ResType);
3347 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003348 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003349 } else if (ResType->isComplexType()) {
3350 // C99 does not support ++/-- on complex types, we allow as an extension.
3351 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003352 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003353 } else {
3354 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003355 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003356 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003357 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003358 // At this point, we know we have a real, complex or pointer type.
3359 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003360 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003361 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003362 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003363}
3364
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003365/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003366/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003367/// where the declaration is needed for type checking. We only need to
3368/// handle cases when the expression references a function designator
3369/// or is an lvalue. Here are some examples:
3370/// - &(x) => x
3371/// - &*****f => f for f a function designator.
3372/// - &s.xx => s
3373/// - &s.zz[1].yy -> s, if zz is an array
3374/// - *(x + 1) -> x, if x is an array
3375/// - &"123"[2] -> 0
3376/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003377static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003378 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003379 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003380 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003381 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003382 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003383 // Fields cannot be declared with a 'register' storage class.
3384 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003385 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003386 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003387 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003388 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003389 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003390
Douglas Gregord2baafd2008-10-21 16:13:35 +00003391 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003392 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003393 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003394 return 0;
3395 else
3396 return VD;
3397 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003398 case Stmt::UnaryOperatorClass: {
3399 UnaryOperator *UO = cast<UnaryOperator>(E);
3400
3401 switch(UO->getOpcode()) {
3402 case UnaryOperator::Deref: {
3403 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003404 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3405 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3406 if (!VD || VD->getType()->isPointerType())
3407 return 0;
3408 return VD;
3409 }
3410 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003411 }
3412 case UnaryOperator::Real:
3413 case UnaryOperator::Imag:
3414 case UnaryOperator::Extension:
3415 return getPrimaryDecl(UO->getSubExpr());
3416 default:
3417 return 0;
3418 }
3419 }
3420 case Stmt::BinaryOperatorClass: {
3421 BinaryOperator *BO = cast<BinaryOperator>(E);
3422
3423 // Handle cases involving pointer arithmetic. The result of an
3424 // Assign or AddAssign is not an lvalue so they can be ignored.
3425
3426 // (x + n) or (n + x) => x
3427 if (BO->getOpcode() == BinaryOperator::Add) {
3428 if (BO->getLHS()->getType()->isPointerType()) {
3429 return getPrimaryDecl(BO->getLHS());
3430 } else if (BO->getRHS()->getType()->isPointerType()) {
3431 return getPrimaryDecl(BO->getRHS());
3432 }
3433 }
3434
3435 return 0;
3436 }
Chris Lattner4b009652007-07-25 00:24:17 +00003437 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003438 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003439 case Stmt::ImplicitCastExprClass:
3440 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003441 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003442 default:
3443 return 0;
3444 }
3445}
3446
3447/// CheckAddressOfOperand - The operand of & must be either a function
3448/// designator or an lvalue designating an object. If it is an lvalue, the
3449/// object cannot be declared with storage class register or be a bit field.
3450/// Note: The usual conversions are *not* applied to the operand of the &
3451/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003452/// In C++, the operand might be an overloaded function name, in which case
3453/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003454QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003455 if (op->isTypeDependent())
3456 return Context.DependentTy;
3457
Steve Naroff9c6c3592008-01-13 17:10:08 +00003458 if (getLangOptions().C99) {
3459 // Implement C99-only parts of addressof rules.
3460 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3461 if (uOp->getOpcode() == UnaryOperator::Deref)
3462 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3463 // (assuming the deref expression is valid).
3464 return uOp->getSubExpr()->getType();
3465 }
3466 // Technically, there should be a check for array subscript
3467 // expressions here, but the result of one is always an lvalue anyway.
3468 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003469 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003470 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003471
Chris Lattner4b009652007-07-25 00:24:17 +00003472 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003473 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3474 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003475 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3476 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003477 return QualType();
3478 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003479 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003480 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3481 if (Field->isBitField()) {
3482 Diag(OpLoc, diag::err_typecheck_address_of)
3483 << "bit-field" << op->getSourceRange();
3484 return QualType();
3485 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003486 }
3487 // Check for Apple extension for accessing vector components.
3488 } else if (isa<ArraySubscriptExpr>(op) &&
3489 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003490 Diag(OpLoc, diag::err_typecheck_address_of)
3491 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003492 return QualType();
3493 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003494 // We have an lvalue with a decl. Make sure the decl is not declared
3495 // with the register storage-class specifier.
3496 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3497 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003498 Diag(OpLoc, diag::err_typecheck_address_of)
3499 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003500 return QualType();
3501 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003502 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003503 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003504 } else if (isa<FieldDecl>(dcl)) {
3505 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003506 // Could be a pointer to member, though, if there is an explicit
3507 // scope qualifier for the class.
3508 if (isa<QualifiedDeclRefExpr>(op)) {
3509 DeclContext *Ctx = dcl->getDeclContext();
3510 if (Ctx && Ctx->isRecord())
3511 return Context.getMemberPointerType(op->getType(),
3512 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3513 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003514 } else if (isa<FunctionDecl>(dcl)) {
3515 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003516 // As above.
3517 if (isa<QualifiedDeclRefExpr>(op)) {
3518 DeclContext *Ctx = dcl->getDeclContext();
3519 if (Ctx && Ctx->isRecord())
3520 return Context.getMemberPointerType(op->getType(),
3521 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3522 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003523 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003524 else
Chris Lattner4b009652007-07-25 00:24:17 +00003525 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003526 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003527
Chris Lattner4b009652007-07-25 00:24:17 +00003528 // If the operand has type "type", the result has type "pointer to type".
3529 return Context.getPointerType(op->getType());
3530}
3531
Chris Lattnerda5c0872008-11-23 09:13:29 +00003532QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3533 UsualUnaryConversions(Op);
3534 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003535
Chris Lattnerda5c0872008-11-23 09:13:29 +00003536 // Note that per both C89 and C99, this is always legal, even if ptype is an
3537 // incomplete type or void. It would be possible to warn about dereferencing
3538 // a void pointer, but it's completely well-defined, and such a warning is
3539 // unlikely to catch any mistakes.
3540 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003541 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003542
Chris Lattner77d52da2008-11-20 06:06:08 +00003543 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003544 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003545 return QualType();
3546}
3547
3548static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3549 tok::TokenKind Kind) {
3550 BinaryOperator::Opcode Opc;
3551 switch (Kind) {
3552 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003553 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3554 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003555 case tok::star: Opc = BinaryOperator::Mul; break;
3556 case tok::slash: Opc = BinaryOperator::Div; break;
3557 case tok::percent: Opc = BinaryOperator::Rem; break;
3558 case tok::plus: Opc = BinaryOperator::Add; break;
3559 case tok::minus: Opc = BinaryOperator::Sub; break;
3560 case tok::lessless: Opc = BinaryOperator::Shl; break;
3561 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3562 case tok::lessequal: Opc = BinaryOperator::LE; break;
3563 case tok::less: Opc = BinaryOperator::LT; break;
3564 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3565 case tok::greater: Opc = BinaryOperator::GT; break;
3566 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3567 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3568 case tok::amp: Opc = BinaryOperator::And; break;
3569 case tok::caret: Opc = BinaryOperator::Xor; break;
3570 case tok::pipe: Opc = BinaryOperator::Or; break;
3571 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3572 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3573 case tok::equal: Opc = BinaryOperator::Assign; break;
3574 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3575 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3576 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3577 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3578 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3579 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3580 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3581 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3582 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3583 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3584 case tok::comma: Opc = BinaryOperator::Comma; break;
3585 }
3586 return Opc;
3587}
3588
3589static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3590 tok::TokenKind Kind) {
3591 UnaryOperator::Opcode Opc;
3592 switch (Kind) {
3593 default: assert(0 && "Unknown unary op!");
3594 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3595 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3596 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3597 case tok::star: Opc = UnaryOperator::Deref; break;
3598 case tok::plus: Opc = UnaryOperator::Plus; break;
3599 case tok::minus: Opc = UnaryOperator::Minus; break;
3600 case tok::tilde: Opc = UnaryOperator::Not; break;
3601 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003602 case tok::kw___real: Opc = UnaryOperator::Real; break;
3603 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3604 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3605 }
3606 return Opc;
3607}
3608
Douglas Gregord7f915e2008-11-06 23:29:22 +00003609/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3610/// operator @p Opc at location @c TokLoc. This routine only supports
3611/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003612Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3613 unsigned Op,
3614 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003615 QualType ResultTy; // Result type of the binary operator.
3616 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3617 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3618
3619 switch (Opc) {
3620 default:
3621 assert(0 && "Unknown binary expr!");
3622 case BinaryOperator::Assign:
3623 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3624 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003625 case BinaryOperator::PtrMemD:
3626 case BinaryOperator::PtrMemI:
3627 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3628 Opc == BinaryOperator::PtrMemI);
3629 break;
3630 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003631 case BinaryOperator::Div:
3632 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3633 break;
3634 case BinaryOperator::Rem:
3635 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3636 break;
3637 case BinaryOperator::Add:
3638 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3639 break;
3640 case BinaryOperator::Sub:
3641 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3642 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003643 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003644 case BinaryOperator::Shr:
3645 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3646 break;
3647 case BinaryOperator::LE:
3648 case BinaryOperator::LT:
3649 case BinaryOperator::GE:
3650 case BinaryOperator::GT:
3651 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3652 break;
3653 case BinaryOperator::EQ:
3654 case BinaryOperator::NE:
3655 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3656 break;
3657 case BinaryOperator::And:
3658 case BinaryOperator::Xor:
3659 case BinaryOperator::Or:
3660 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3661 break;
3662 case BinaryOperator::LAnd:
3663 case BinaryOperator::LOr:
3664 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3665 break;
3666 case BinaryOperator::MulAssign:
3667 case BinaryOperator::DivAssign:
3668 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3669 if (!CompTy.isNull())
3670 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3671 break;
3672 case BinaryOperator::RemAssign:
3673 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3674 if (!CompTy.isNull())
3675 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3676 break;
3677 case BinaryOperator::AddAssign:
3678 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3679 if (!CompTy.isNull())
3680 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3681 break;
3682 case BinaryOperator::SubAssign:
3683 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3684 if (!CompTy.isNull())
3685 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3686 break;
3687 case BinaryOperator::ShlAssign:
3688 case BinaryOperator::ShrAssign:
3689 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3690 if (!CompTy.isNull())
3691 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3692 break;
3693 case BinaryOperator::AndAssign:
3694 case BinaryOperator::XorAssign:
3695 case BinaryOperator::OrAssign:
3696 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3697 if (!CompTy.isNull())
3698 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3699 break;
3700 case BinaryOperator::Comma:
3701 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3702 break;
3703 }
3704 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003705 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003706 if (CompTy.isNull())
3707 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3708 else
3709 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003710 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003711}
3712
Chris Lattner4b009652007-07-25 00:24:17 +00003713// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003714Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3715 tok::TokenKind Kind,
3716 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003717 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003718 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003719
Steve Naroff87d58b42007-09-16 03:34:24 +00003720 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3721 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003722
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003723 // If either expression is type-dependent, just build the AST.
3724 // FIXME: We'll need to perform some caching of the result of name
3725 // lookup for operator+.
3726 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003727 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3728 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003729 Context.DependentTy,
3730 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003731 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003732 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3733 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003734 }
3735
Sebastian Redl95216a62009-02-07 00:15:38 +00003736 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003737 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3738 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003739 // If this is one of the assignment operators, we only perform
3740 // overload resolution if the left-hand side is a class or
3741 // enumeration type (C++ [expr.ass]p3).
3742 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3743 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3744 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3745 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003746
Douglas Gregord7f915e2008-11-06 23:29:22 +00003747 // Determine which overloaded operator we're dealing with.
3748 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003749 // Overloading .* is not possible.
3750 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003751 OO_Star, OO_Slash, OO_Percent,
3752 OO_Plus, OO_Minus,
3753 OO_LessLess, OO_GreaterGreater,
3754 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3755 OO_EqualEqual, OO_ExclaimEqual,
3756 OO_Amp,
3757 OO_Caret,
3758 OO_Pipe,
3759 OO_AmpAmp,
3760 OO_PipePipe,
3761 OO_Equal, OO_StarEqual,
3762 OO_SlashEqual, OO_PercentEqual,
3763 OO_PlusEqual, OO_MinusEqual,
3764 OO_LessLessEqual, OO_GreaterGreaterEqual,
3765 OO_AmpEqual, OO_CaretEqual,
3766 OO_PipeEqual,
3767 OO_Comma
3768 };
3769 OverloadedOperatorKind OverOp = OverOps[Opc];
3770
Douglas Gregor5ed15042008-11-18 23:14:02 +00003771 // Add the appropriate overloaded operators (C++ [over.match.oper])
3772 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003773 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003774 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003775 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3776 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003777
3778 // Perform overload resolution.
3779 OverloadCandidateSet::iterator Best;
3780 switch (BestViableFunction(CandidateSet, Best)) {
3781 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003782 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003783 FunctionDecl *FnDecl = Best->Function;
3784
Douglas Gregor70d26122008-11-12 17:17:38 +00003785 if (FnDecl) {
3786 // We matched an overloaded operator. Build a call to that
3787 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003788
Douglas Gregor70d26122008-11-12 17:17:38 +00003789 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003790 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3791 if (PerformObjectArgumentInitialization(lhs, Method) ||
3792 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3793 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003794 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003795 } else {
3796 // Convert the arguments.
3797 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3798 "passing") ||
3799 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3800 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003801 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003802 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003803
Douglas Gregor70d26122008-11-12 17:17:38 +00003804 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003805 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003806 = FnDecl->getType()->getAsFunctionType()->getResultType();
3807 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003808
Douglas Gregor70d26122008-11-12 17:17:38 +00003809 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003810 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3811 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003812 UsualUnaryConversions(FnExpr);
3813
Ted Kremenek362abcd2009-02-09 20:51:47 +00003814 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003815 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003816 } else {
3817 // We matched a built-in operator. Convert the arguments, then
3818 // break out so that we will build the appropriate built-in
3819 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003820 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3821 Best->Conversions[0], "passing") ||
3822 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3823 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003824 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003825
3826 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003827 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003828 }
3829
3830 case OR_No_Viable_Function:
3831 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003832 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003833 break;
3834
3835 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003836 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3837 << BinaryOperator::getOpcodeStr(Opc)
3838 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003839 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003840 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003841 }
3842
Douglas Gregor70d26122008-11-12 17:17:38 +00003843 // Either we found no viable overloaded operator or we matched a
3844 // built-in operator. In either case, fall through to trying to
3845 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003846 }
3847
Douglas Gregord7f915e2008-11-06 23:29:22 +00003848 // Build a built-in binary operation.
3849 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003850}
3851
3852// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003853Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3854 tok::TokenKind Op, ExprArg input) {
3855 // FIXME: Input is modified later, but smart pointer not reassigned.
3856 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003857 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003858
3859 if (getLangOptions().CPlusPlus &&
3860 (Input->getType()->isRecordType()
3861 || Input->getType()->isEnumeralType())) {
3862 // Determine which overloaded operator we're dealing with.
3863 static const OverloadedOperatorKind OverOps[] = {
3864 OO_None, OO_None,
3865 OO_PlusPlus, OO_MinusMinus,
3866 OO_Amp, OO_Star,
3867 OO_Plus, OO_Minus,
3868 OO_Tilde, OO_Exclaim,
3869 OO_None, OO_None,
3870 OO_None,
3871 OO_None
3872 };
3873 OverloadedOperatorKind OverOp = OverOps[Opc];
3874
3875 // Add the appropriate overloaded operators (C++ [over.match.oper])
3876 // to the candidate set.
3877 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003878 if (OverOp != OO_None &&
3879 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3880 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003881
3882 // Perform overload resolution.
3883 OverloadCandidateSet::iterator Best;
3884 switch (BestViableFunction(CandidateSet, Best)) {
3885 case OR_Success: {
3886 // We found a built-in operator or an overloaded operator.
3887 FunctionDecl *FnDecl = Best->Function;
3888
3889 if (FnDecl) {
3890 // We matched an overloaded operator. Build a call to that
3891 // operator.
3892
3893 // Convert the arguments.
3894 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3895 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003896 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003897 } else {
3898 // Convert the arguments.
3899 if (PerformCopyInitialization(Input,
3900 FnDecl->getParamDecl(0)->getType(),
3901 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003902 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003903 }
3904
3905 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003906 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003907 = FnDecl->getType()->getAsFunctionType()->getResultType();
3908 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003909
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003910 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003911 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3912 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003913 UsualUnaryConversions(FnExpr);
3914
Sebastian Redl8b769972009-01-19 00:08:26 +00003915 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003916 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003917 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003918 } else {
3919 // We matched a built-in operator. Convert the arguments, then
3920 // break out so that we will build the appropriate built-in
3921 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003922 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3923 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003924 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003925
3926 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003927 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003928 }
3929
3930 case OR_No_Viable_Function:
3931 // No viable function; fall through to handling this as a
3932 // built-in operator, which will produce an error message for us.
3933 break;
3934
3935 case OR_Ambiguous:
3936 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3937 << UnaryOperator::getOpcodeStr(Opc)
3938 << Input->getSourceRange();
3939 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003940 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003941 }
3942
3943 // Either we found no viable overloaded operator or we matched a
3944 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003945 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003946 }
3947
Chris Lattner4b009652007-07-25 00:24:17 +00003948 QualType resultType;
3949 switch (Opc) {
3950 default:
3951 assert(0 && "Unimplemented unary expr!");
3952 case UnaryOperator::PreInc:
3953 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003954 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3955 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003956 break;
3957 case UnaryOperator::AddrOf:
3958 resultType = CheckAddressOfOperand(Input, OpLoc);
3959 break;
3960 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003961 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003962 resultType = CheckIndirectionOperand(Input, OpLoc);
3963 break;
3964 case UnaryOperator::Plus:
3965 case UnaryOperator::Minus:
3966 UsualUnaryConversions(Input);
3967 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003968 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3969 break;
3970 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3971 resultType->isEnumeralType())
3972 break;
3973 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3974 Opc == UnaryOperator::Plus &&
3975 resultType->isPointerType())
3976 break;
3977
Sebastian Redl8b769972009-01-19 00:08:26 +00003978 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3979 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003980 case UnaryOperator::Not: // bitwise complement
3981 UsualUnaryConversions(Input);
3982 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003983 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3984 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3985 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003986 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003987 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003988 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003989 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3990 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003991 break;
3992 case UnaryOperator::LNot: // logical negation
3993 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3994 DefaultFunctionArrayConversion(Input);
3995 resultType = Input->getType();
3996 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003997 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3998 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003999 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004000 // In C++, it's bool. C++ 5.3.1p8
4001 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004002 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004003 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004004 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00004005 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00004006 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004007 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004008 resultType = Input->getType();
4009 break;
4010 }
4011 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004012 return ExprError();
4013 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004014 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004015}
4016
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004017/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4018Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004019 SourceLocation LabLoc,
4020 IdentifierInfo *LabelII) {
4021 // Look up the record for this label identifier.
4022 LabelStmt *&LabelDecl = LabelMap[LabelII];
4023
Daniel Dunbar879788d2008-08-04 16:51:22 +00004024 // If we haven't seen this label yet, create a forward reference. It
4025 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004026 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004027 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004028
4029 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004030 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4031 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004032}
4033
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004034Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004035 SourceLocation RPLoc) { // "({..})"
4036 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4037 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4038 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4039
Eli Friedmanbc941e12009-01-24 23:09:00 +00004040 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4041 if (isFileScope) {
4042 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4043 }
4044
Chris Lattner4b009652007-07-25 00:24:17 +00004045 // FIXME: there are a variety of strange constraints to enforce here, for
4046 // example, it is not possible to goto into a stmt expression apparently.
4047 // More semantic analysis is needed.
4048
4049 // FIXME: the last statement in the compount stmt has its value used. We
4050 // should not warn about it being unused.
4051
4052 // If there are sub stmts in the compound stmt, take the type of the last one
4053 // as the type of the stmtexpr.
4054 QualType Ty = Context.VoidTy;
4055
Chris Lattner200964f2008-07-26 19:51:01 +00004056 if (!Compound->body_empty()) {
4057 Stmt *LastStmt = Compound->body_back();
4058 // If LastStmt is a label, skip down through into the body.
4059 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4060 LastStmt = Label->getSubStmt();
4061
4062 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004063 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004064 }
Chris Lattner4b009652007-07-25 00:24:17 +00004065
Steve Naroff774e4152009-01-21 00:14:39 +00004066 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004067}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004068
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004069Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4070 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004071 SourceLocation TypeLoc,
4072 TypeTy *argty,
4073 OffsetOfComponent *CompPtr,
4074 unsigned NumComponents,
4075 SourceLocation RPLoc) {
4076 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4077 assert(!ArgTy.isNull() && "Missing type argument!");
4078
4079 // We must have at least one component that refers to the type, and the first
4080 // one is known to be a field designator. Verify that the ArgTy represents
4081 // a struct/union/class.
4082 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004083 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004084
4085 // Otherwise, create a compound literal expression as the base, and
4086 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004087 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004088 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004089 IList->setType(ArgTy);
4090 Expr *Res =
4091 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4092
Chris Lattnerb37522e2007-08-31 21:49:13 +00004093 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4094 // GCC extension, diagnose them.
4095 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004096 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4097 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004098
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004099 for (unsigned i = 0; i != NumComponents; ++i) {
4100 const OffsetOfComponent &OC = CompPtr[i];
4101 if (OC.isBrackets) {
4102 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004103 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004104 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004105 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004106 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004107 }
4108
Chris Lattner2af6a802007-08-30 17:59:59 +00004109 // FIXME: C++: Verify that operator[] isn't overloaded.
4110
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004111 // C99 6.5.2.1p1
4112 Expr *Idx = static_cast<Expr*>(OC.U.E);
4113 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004114 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4115 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004116
Steve Naroff774e4152009-01-21 00:14:39 +00004117 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4118 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004119 continue;
4120 }
4121
4122 const RecordType *RC = Res->getType()->getAsRecordType();
4123 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004124 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004125 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004126 }
4127
4128 // Get the decl corresponding to this.
4129 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004130 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004131 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4132 LookupMemberName)
4133 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004134 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004135 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4136 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004137
4138 // FIXME: C++: Verify that MemberDecl isn't a static field.
4139 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004140 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4141 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004142 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4143 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004144 }
4145
Steve Naroff774e4152009-01-21 00:14:39 +00004146 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4147 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004148}
4149
4150
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004151Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004152 TypeTy *arg1, TypeTy *arg2,
4153 SourceLocation RPLoc) {
4154 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4155 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4156
4157 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4158
Steve Naroff774e4152009-01-21 00:14:39 +00004159 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4160 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004161}
4162
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004163Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004164 ExprTy *expr1, ExprTy *expr2,
4165 SourceLocation RPLoc) {
4166 Expr *CondExpr = static_cast<Expr*>(cond);
4167 Expr *LHSExpr = static_cast<Expr*>(expr1);
4168 Expr *RHSExpr = static_cast<Expr*>(expr2);
4169
4170 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4171
4172 // The conditional expression is required to be a constant expression.
4173 llvm::APSInt condEval(32);
4174 SourceLocation ExpLoc;
4175 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004176 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4177 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004178
4179 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4180 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4181 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004182 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4183 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004184}
4185
Steve Naroff52a81c02008-09-03 18:15:37 +00004186//===----------------------------------------------------------------------===//
4187// Clang Extensions.
4188//===----------------------------------------------------------------------===//
4189
4190/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004191void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004192 // Analyze block parameters.
4193 BlockSemaInfo *BSI = new BlockSemaInfo();
4194
4195 // Add BSI to CurBlock.
4196 BSI->PrevBlockInfo = CurBlock;
4197 CurBlock = BSI;
4198
4199 BSI->ReturnType = 0;
4200 BSI->TheScope = BlockScope;
4201
Steve Naroff52059382008-10-10 01:28:17 +00004202 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004203 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004204}
4205
Mike Stumpc1fddff2009-02-04 22:31:32 +00004206void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4207 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4208
4209 if (ParamInfo.getNumTypeObjects() == 0
4210 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4211 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4212
4213 // The type is entirely optional as well, if none, use DependentTy.
4214 if (T.isNull())
4215 T = Context.DependentTy;
4216
4217 // The parameter list is optional, if there was none, assume ().
4218 if (!T->isFunctionType())
4219 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4220
4221 CurBlock->hasPrototype = true;
4222 CurBlock->isVariadic = false;
4223 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4224 .getTypePtr();
4225
4226 if (!RetTy->isDependentType())
4227 CurBlock->ReturnType = RetTy;
4228 return;
4229 }
4230
Steve Naroff52a81c02008-09-03 18:15:37 +00004231 // Analyze arguments to block.
4232 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4233 "Not a function declarator!");
4234 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004235
Steve Naroff52059382008-10-10 01:28:17 +00004236 CurBlock->hasPrototype = FTI.hasPrototype;
4237 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004238
4239 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4240 // no arguments, not a function that takes a single void argument.
4241 if (FTI.hasPrototype &&
4242 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4243 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4244 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4245 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004246 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004247 } else if (FTI.hasPrototype) {
4248 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004249 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4250 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004251 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4252
4253 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4254 .getTypePtr();
4255
4256 if (!RetTy->isDependentType())
4257 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004258 }
Steve Naroff52059382008-10-10 01:28:17 +00004259 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4260
4261 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4262 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4263 // If this has an identifier, add it to the scope stack.
4264 if ((*AI)->getIdentifier())
4265 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004266}
4267
4268/// ActOnBlockError - If there is an error parsing a block, this callback
4269/// is invoked to pop the information about the block from the action impl.
4270void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4271 // Ensure that CurBlock is deleted.
4272 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4273
4274 // Pop off CurBlock, handle nested blocks.
4275 CurBlock = CurBlock->PrevBlockInfo;
4276
4277 // FIXME: Delete the ParmVarDecl objects as well???
4278
4279}
4280
4281/// ActOnBlockStmtExpr - This is called when the body of a block statement
4282/// literal was successfully completed. ^(int x){...}
4283Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4284 Scope *CurScope) {
4285 // Ensure that CurBlock is deleted.
4286 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004287 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004288
Steve Naroff52059382008-10-10 01:28:17 +00004289 PopDeclContext();
4290
Steve Naroff52a81c02008-09-03 18:15:37 +00004291 // Pop off CurBlock, handle nested blocks.
4292 CurBlock = CurBlock->PrevBlockInfo;
4293
4294 QualType RetTy = Context.VoidTy;
4295 if (BSI->ReturnType)
4296 RetTy = QualType(BSI->ReturnType, 0);
4297
4298 llvm::SmallVector<QualType, 8> ArgTypes;
4299 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4300 ArgTypes.push_back(BSI->Params[i]->getType());
4301
4302 QualType BlockTy;
4303 if (!BSI->hasPrototype)
4304 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4305 else
4306 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004307 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004308
4309 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004310
Steve Naroff95029d92008-10-08 18:44:00 +00004311 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004312 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004313}
4314
Nate Begemanbd881ef2008-01-30 20:50:20 +00004315/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004316/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004317/// The number of arguments has already been validated to match the number of
4318/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004319static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4320 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004321 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004322 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004323 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4324 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004325
4326 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004327 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004328 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004329 return true;
4330}
4331
4332Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4333 SourceLocation *CommaLocs,
4334 SourceLocation BuiltinLoc,
4335 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004336 // __builtin_overload requires at least 2 arguments
4337 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004338 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4339 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004340
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004341 // The first argument is required to be a constant expression. It tells us
4342 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004343 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004344 Expr *NParamsExpr = Args[0];
4345 llvm::APSInt constEval(32);
4346 SourceLocation ExpLoc;
4347 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004348 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4349 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004350
4351 // Verify that the number of parameters is > 0
4352 unsigned NumParams = constEval.getZExtValue();
4353 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004354 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4355 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004356 // Verify that we have at least 1 + NumParams arguments to the builtin.
4357 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004358 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4359 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004360
4361 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004362 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004363 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004364 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4365 // UsualUnaryConversions will convert the function DeclRefExpr into a
4366 // pointer to function.
4367 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004368 const FunctionTypeProto *FnType = 0;
4369 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4370 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004371
4372 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4373 // parameters, and the number of parameters must match the value passed to
4374 // the builtin.
4375 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004376 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4377 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004378
4379 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004380 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004381 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004382 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004383 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004384 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4385 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004386 // Remember our match, and continue processing the remaining arguments
4387 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004388 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004389 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004390 BuiltinLoc, RParenLoc);
4391 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004392 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004393 // Return the newly created OverloadExpr node, if we succeded in matching
4394 // exactly one of the candidate functions.
4395 if (OE)
4396 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004397
4398 // If we didn't find a matching function Expr in the __builtin_overload list
4399 // the return an error.
4400 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004401 for (unsigned i = 0; i != NumParams; ++i) {
4402 if (i != 0) typeNames += ", ";
4403 typeNames += Args[i+1]->getType().getAsString();
4404 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004405
Chris Lattner77d52da2008-11-20 06:06:08 +00004406 return Diag(BuiltinLoc, diag::err_overload_no_match)
4407 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004408}
4409
Anders Carlsson36760332007-10-15 20:28:48 +00004410Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4411 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004412 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004413 Expr *E = static_cast<Expr*>(expr);
4414 QualType T = QualType::getFromOpaquePtr(type);
4415
4416 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004417
4418 // Get the va_list type
4419 QualType VaListType = Context.getBuiltinVaListType();
4420 // Deal with implicit array decay; for example, on x86-64,
4421 // va_list is an array, but it's supposed to decay to
4422 // a pointer for va_arg.
4423 if (VaListType->isArrayType())
4424 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004425 // Make sure the input expression also decays appropriately.
4426 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004427
4428 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004429 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004430 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004431 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004432
4433 // FIXME: Warn if a non-POD type is passed in.
4434
Steve Naroff774e4152009-01-21 00:14:39 +00004435 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004436}
4437
Douglas Gregorad4b3792008-11-29 04:51:27 +00004438Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4439 // The type of __null will be int or long, depending on the size of
4440 // pointers on the target.
4441 QualType Ty;
4442 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4443 Ty = Context.IntTy;
4444 else
4445 Ty = Context.LongTy;
4446
Steve Naroff774e4152009-01-21 00:14:39 +00004447 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004448}
4449
Chris Lattner005ed752008-01-04 18:04:52 +00004450bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4451 SourceLocation Loc,
4452 QualType DstType, QualType SrcType,
4453 Expr *SrcExpr, const char *Flavor) {
4454 // Decode the result (notice that AST's are still created for extensions).
4455 bool isInvalid = false;
4456 unsigned DiagKind;
4457 switch (ConvTy) {
4458 default: assert(0 && "Unknown conversion type");
4459 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004460 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004461 DiagKind = diag::ext_typecheck_convert_pointer_int;
4462 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004463 case IntToPointer:
4464 DiagKind = diag::ext_typecheck_convert_int_pointer;
4465 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004466 case IncompatiblePointer:
4467 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4468 break;
4469 case FunctionVoidPointer:
4470 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4471 break;
4472 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004473 // If the qualifiers lost were because we were applying the
4474 // (deprecated) C++ conversion from a string literal to a char*
4475 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4476 // Ideally, this check would be performed in
4477 // CheckPointerTypesForAssignment. However, that would require a
4478 // bit of refactoring (so that the second argument is an
4479 // expression, rather than a type), which should be done as part
4480 // of a larger effort to fix CheckPointerTypesForAssignment for
4481 // C++ semantics.
4482 if (getLangOptions().CPlusPlus &&
4483 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4484 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004485 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4486 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004487 case IntToBlockPointer:
4488 DiagKind = diag::err_int_to_block_pointer;
4489 break;
4490 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004491 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004492 break;
Steve Naroff19608432008-10-14 22:18:38 +00004493 case IncompatibleObjCQualifiedId:
4494 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4495 // it can give a more specific diagnostic.
4496 DiagKind = diag::warn_incompatible_qualified_id;
4497 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004498 case IncompatibleVectors:
4499 DiagKind = diag::warn_incompatible_vectors;
4500 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004501 case Incompatible:
4502 DiagKind = diag::err_typecheck_convert_incompatible;
4503 isInvalid = true;
4504 break;
4505 }
4506
Chris Lattner271d4c22008-11-24 05:29:24 +00004507 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4508 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004509 return isInvalid;
4510}
Anders Carlssond5201b92008-11-30 19:50:32 +00004511
4512bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4513{
4514 Expr::EvalResult EvalResult;
4515
4516 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4517 EvalResult.HasSideEffects) {
4518 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4519
4520 if (EvalResult.Diag) {
4521 // We only show the note if it's not the usual "invalid subexpression"
4522 // or if it's actually in a subexpression.
4523 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4524 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4525 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4526 }
4527
4528 return true;
4529 }
4530
4531 if (EvalResult.Diag) {
4532 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4533 E->getSourceRange();
4534
4535 // Print the reason it's not a constant.
4536 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4537 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4538 }
4539
4540 if (Result)
4541 *Result = EvalResult.Val.getInt();
4542 return false;
4543}