blob: 66dc8e13ae1ba82894c1a5e9929865c23a6564c5 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Douglas Gregoraa57e862009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62 MD->isInstanceMethod());
63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64 }
65 }
66 }
67
68 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000069 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70 }
71
Douglas Gregoraa57e862009-02-18 21:56:37 +000072 // See if this is a deleted function.
73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
74 if (FD->isDeleted()) {
75 Diag(Loc, diag::err_deleted_function_use);
76 Diag(D->getLocation(), diag::note_unavailable_here) << true;
77 return true;
78 }
79
80 // See if the decl is unavailable
81 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000082 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000083 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
84 }
85
86
87 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000088}
89
Chris Lattner299b8842008-07-25 21:10:04 +000090//===----------------------------------------------------------------------===//
91// Standard Promotions and Conversions
92//===----------------------------------------------------------------------===//
93
Chris Lattner299b8842008-07-25 21:10:04 +000094/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
95void Sema::DefaultFunctionArrayConversion(Expr *&E) {
96 QualType Ty = E->getType();
97 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
98
Chris Lattner299b8842008-07-25 21:10:04 +000099 if (Ty->isFunctionType())
100 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000101 else if (Ty->isArrayType()) {
102 // In C90 mode, arrays only promote to pointers if the array expression is
103 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
104 // type 'array of type' is converted to an expression that has type 'pointer
105 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
106 // that has type 'array of type' ...". The relevant change is "an lvalue"
107 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000108 //
109 // C++ 4.2p1:
110 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
111 // T" can be converted to an rvalue of type "pointer to T".
112 //
113 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
114 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000115 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
116 }
Chris Lattner299b8842008-07-25 21:10:04 +0000117}
118
119/// UsualUnaryConversions - Performs various conversions that are common to most
120/// operators (C99 6.3). The conversions of array and function types are
121/// sometimes surpressed. For example, the array->pointer conversion doesn't
122/// apply if the array is an argument to the sizeof or address (&) operators.
123/// In these instances, this routine should *not* be called.
124Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
125 QualType Ty = Expr->getType();
126 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
127
Chris Lattner299b8842008-07-25 21:10:04 +0000128 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
129 ImpCastExprToType(Expr, Context.IntTy);
130 else
131 DefaultFunctionArrayConversion(Expr);
132
133 return Expr;
134}
135
Chris Lattner9305c3d2008-07-25 22:25:12 +0000136/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
137/// do not have a prototype. Arguments that have type float are promoted to
138/// double. All other argument types are converted by UsualUnaryConversions().
139void Sema::DefaultArgumentPromotion(Expr *&Expr) {
140 QualType Ty = Expr->getType();
141 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
142
143 // If this is a 'float' (CVR qualified or typedef) promote to double.
144 if (const BuiltinType *BT = Ty->getAsBuiltinType())
145 if (BT->getKind() == BuiltinType::Float)
146 return ImpCastExprToType(Expr, Context.DoubleTy);
147
148 UsualUnaryConversions(Expr);
149}
150
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000151// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
152// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000153void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000154 DefaultArgumentPromotion(Expr);
155
156 if (!Expr->getType()->isPODType()) {
157 Diag(Expr->getLocStart(),
158 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
159 Expr->getType() << CT;
160 }
161}
162
163
Chris Lattner299b8842008-07-25 21:10:04 +0000164/// UsualArithmeticConversions - Performs various conversions that are common to
165/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
166/// routine returns the first non-arithmetic type found. The client is
167/// responsible for emitting appropriate error diagnostics.
168/// FIXME: verify the conversion rules for "complex int" are consistent with
169/// GCC.
170QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
171 bool isCompAssign) {
172 if (!isCompAssign) {
173 UsualUnaryConversions(lhsExpr);
174 UsualUnaryConversions(rhsExpr);
175 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000176
Chris Lattner299b8842008-07-25 21:10:04 +0000177 // For conversion purposes, we ignore any qualifiers.
178 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000179 QualType lhs =
180 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
181 QualType rhs =
182 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000183
184 // If both types are identical, no conversion is needed.
185 if (lhs == rhs)
186 return lhs;
187
188 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
189 // The caller can deal with this (e.g. pointer + int).
190 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
191 return lhs;
192
193 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
194 if (!isCompAssign) {
195 ImpCastExprToType(lhsExpr, destType);
196 ImpCastExprToType(rhsExpr, destType);
197 }
198 return destType;
199}
200
201QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
202 // Perform the usual unary conversions. We do this early so that
203 // integral promotions to "int" can allow us to exit early, in the
204 // lhs == rhs check. Also, for conversion purposes, we ignore any
205 // qualifiers. For example, "const float" and "float" are
206 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000207 if (lhs->isPromotableIntegerType())
208 lhs = Context.IntTy;
209 else
210 lhs = lhs.getUnqualifiedType();
211 if (rhs->isPromotableIntegerType())
212 rhs = Context.IntTy;
213 else
214 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000215
Chris Lattner299b8842008-07-25 21:10:04 +0000216 // If both types are identical, no conversion is needed.
217 if (lhs == rhs)
218 return lhs;
219
220 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
221 // The caller can deal with this (e.g. pointer + int).
222 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
223 return lhs;
224
225 // At this point, we have two different arithmetic types.
226
227 // Handle complex types first (C99 6.3.1.8p1).
228 if (lhs->isComplexType() || rhs->isComplexType()) {
229 // if we have an integer operand, the result is the complex type.
230 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
231 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000232 return lhs;
233 }
234 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
235 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000236 return rhs;
237 }
238 // This handles complex/complex, complex/float, or float/complex.
239 // When both operands are complex, the shorter operand is converted to the
240 // type of the longer, and that is the type of the result. This corresponds
241 // to what is done when combining two real floating-point operands.
242 // The fun begins when size promotion occur across type domains.
243 // From H&S 6.3.4: When one operand is complex and the other is a real
244 // floating-point type, the less precise type is converted, within it's
245 // real or complex domain, to the precision of the other type. For example,
246 // when combining a "long double" with a "double _Complex", the
247 // "double _Complex" is promoted to "long double _Complex".
248 int result = Context.getFloatingTypeOrder(lhs, rhs);
249
250 if (result > 0) { // The left side is bigger, convert rhs.
251 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000252 } else if (result < 0) { // The right side is bigger, convert lhs.
253 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000254 }
255 // At this point, lhs and rhs have the same rank/size. Now, make sure the
256 // domains match. This is a requirement for our implementation, C99
257 // does not require this promotion.
258 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
259 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000260 return rhs;
261 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000262 return lhs;
263 }
264 }
265 return lhs; // The domain/size match exactly.
266 }
267 // Now handle "real" floating types (i.e. float, double, long double).
268 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
269 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000270 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000271 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000272 return lhs;
273 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000274 if (rhs->isComplexIntegerType()) {
275 // convert rhs to the complex floating point type.
276 return Context.getComplexType(lhs);
277 }
278 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000279 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000280 return rhs;
281 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000282 if (lhs->isComplexIntegerType()) {
283 // convert lhs to the complex floating point type.
284 return Context.getComplexType(rhs);
285 }
Chris Lattner299b8842008-07-25 21:10:04 +0000286 // We have two real floating types, float/complex combos were handled above.
287 // Convert the smaller operand to the bigger result.
288 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000289 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000290 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000291 assert(result < 0 && "illegal float comparison");
292 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000293 }
294 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
295 // Handle GCC complex int extension.
296 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
297 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
298
299 if (lhsComplexInt && rhsComplexInt) {
300 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000301 rhsComplexInt->getElementType()) >= 0)
302 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000303 return rhs;
304 } else if (lhsComplexInt && rhs->isIntegerType()) {
305 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000306 return lhs;
307 } else if (rhsComplexInt && lhs->isIntegerType()) {
308 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000309 return rhs;
310 }
311 }
312 // Finally, we have two differing integer types.
313 // The rules for this case are in C99 6.3.1.8
314 int compare = Context.getIntegerTypeOrder(lhs, rhs);
315 bool lhsSigned = lhs->isSignedIntegerType(),
316 rhsSigned = rhs->isSignedIntegerType();
317 QualType destType;
318 if (lhsSigned == rhsSigned) {
319 // Same signedness; use the higher-ranked type
320 destType = compare >= 0 ? lhs : rhs;
321 } else if (compare != (lhsSigned ? 1 : -1)) {
322 // The unsigned type has greater than or equal rank to the
323 // signed type, so use the unsigned type
324 destType = lhsSigned ? rhs : lhs;
325 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
326 // The two types are different widths; if we are here, that
327 // means the signed type is larger than the unsigned type, so
328 // use the signed type.
329 destType = lhsSigned ? lhs : rhs;
330 } else {
331 // The signed type is higher-ranked than the unsigned type,
332 // but isn't actually any bigger (like unsigned int and long
333 // on most 32-bit systems). Use the unsigned type corresponding
334 // to the signed type.
335 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
336 }
Chris Lattner299b8842008-07-25 21:10:04 +0000337 return destType;
338}
339
340//===----------------------------------------------------------------------===//
341// Semantic Analysis for various Expression Types
342//===----------------------------------------------------------------------===//
343
344
Steve Naroff87d58b42007-09-16 03:34:24 +0000345/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000346/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
347/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
348/// multiple tokens. However, the common case is that StringToks points to one
349/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000350///
351Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000352Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000353 assert(NumStringToks && "Must have at least one string!");
354
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000355 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000356 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000357 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000358
359 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
360 for (unsigned i = 0; i != NumStringToks; ++i)
361 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000362
Chris Lattnera6dcce32008-02-11 00:02:17 +0000363 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000364 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000365 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000366
367 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
368 if (getLangOptions().CPlusPlus)
369 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000370
Chris Lattnera6dcce32008-02-11 00:02:17 +0000371 // Get an array type for the string, according to C99 6.4.5. This includes
372 // the nul terminator character as well as the string length for pascal
373 // strings.
374 StrTy = Context.getConstantArrayType(StrTy,
375 llvm::APInt(32, Literal.GetStringLength()+1),
376 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000377
Chris Lattner4b009652007-07-25 00:24:17 +0000378 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000379 return Owned(StringLiteral::Create(Context, Literal.GetString(),
380 Literal.GetStringLength(),
381 Literal.AnyWide, StrTy,
382 &StringTokLocs[0],
383 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000384}
385
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000386/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
387/// CurBlock to VD should cause it to be snapshotted (as we do for auto
388/// variables defined outside the block) or false if this is not needed (e.g.
389/// for values inside the block or for globals).
390///
391/// FIXME: This will create BlockDeclRefExprs for global variables,
392/// function references, etc which is suboptimal :) and breaks
393/// things like "integer constant expression" tests.
394static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
395 ValueDecl *VD) {
396 // If the value is defined inside the block, we couldn't snapshot it even if
397 // we wanted to.
398 if (CurBlock->TheDecl == VD->getDeclContext())
399 return false;
400
401 // If this is an enum constant or function, it is constant, don't snapshot.
402 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
403 return false;
404
405 // If this is a reference to an extern, static, or global variable, no need to
406 // snapshot it.
407 // FIXME: What about 'const' variables in C++?
408 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
409 return Var->hasLocalStorage();
410
411 return true;
412}
413
414
415
Steve Naroff0acc9c92007-09-15 18:49:24 +0000416/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000417/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000418/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000419/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000420/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000421Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
422 IdentifierInfo &II,
423 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000424 const CXXScopeSpec *SS,
425 bool isAddressOfOperand) {
426 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000427 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000428}
429
Douglas Gregor566782a2009-01-06 05:10:23 +0000430/// BuildDeclRefExpr - Build either a DeclRefExpr or a
431/// QualifiedDeclRefExpr based on whether or not SS is a
432/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000433DeclRefExpr *
434Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
435 bool TypeDependent, bool ValueDependent,
436 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000437 if (SS && !SS->isEmpty())
438 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000439 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000440 else
441 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000442}
443
Douglas Gregor723d3332009-01-07 00:43:41 +0000444/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
445/// variable corresponding to the anonymous union or struct whose type
446/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000447static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000448 assert(Record->isAnonymousStructOrUnion() &&
449 "Record must be an anonymous struct or union!");
450
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000451 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000452 // be an O(1) operation rather than a slow walk through DeclContext's
453 // vector (which itself will be eliminated). DeclGroups might make
454 // this even better.
455 DeclContext *Ctx = Record->getDeclContext();
456 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
457 DEnd = Ctx->decls_end();
458 D != DEnd; ++D) {
459 if (*D == Record) {
460 // The object for the anonymous struct/union directly
461 // follows its type in the list of declarations.
462 ++D;
463 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000464 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000465 return *D;
466 }
467 }
468
469 assert(false && "Missing object for anonymous record");
470 return 0;
471}
472
Sebastian Redlcd883f72009-01-18 18:53:16 +0000473Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000474Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
475 FieldDecl *Field,
476 Expr *BaseObjectExpr,
477 SourceLocation OpLoc) {
478 assert(Field->getDeclContext()->isRecord() &&
479 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
480 && "Field must be stored inside an anonymous struct or union");
481
482 // Construct the sequence of field member references
483 // we'll have to perform to get to the field in the anonymous
484 // union/struct. The list of members is built from the field
485 // outward, so traverse it backwards to go from an object in
486 // the current context to the field we found.
487 llvm::SmallVector<FieldDecl *, 4> AnonFields;
488 AnonFields.push_back(Field);
489 VarDecl *BaseObject = 0;
490 DeclContext *Ctx = Field->getDeclContext();
491 do {
492 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000493 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000494 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
495 AnonFields.push_back(AnonField);
496 else {
497 BaseObject = cast<VarDecl>(AnonObject);
498 break;
499 }
500 Ctx = Ctx->getParent();
501 } while (Ctx->isRecord() &&
502 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
503
504 // Build the expression that refers to the base object, from
505 // which we will build a sequence of member references to each
506 // of the anonymous union objects and, eventually, the field we
507 // found via name lookup.
508 bool BaseObjectIsPointer = false;
509 unsigned ExtraQuals = 0;
510 if (BaseObject) {
511 // BaseObject is an anonymous struct/union variable (and is,
512 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000513 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000514 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000515 SourceLocation());
516 ExtraQuals
517 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
518 } else if (BaseObjectExpr) {
519 // The caller provided the base object expression. Determine
520 // whether its a pointer and whether it adds any qualifiers to the
521 // anonymous struct/union fields we're looking into.
522 QualType ObjectType = BaseObjectExpr->getType();
523 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
524 BaseObjectIsPointer = true;
525 ObjectType = ObjectPtr->getPointeeType();
526 }
527 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
528 } else {
529 // We've found a member of an anonymous struct/union that is
530 // inside a non-anonymous struct/union, so in a well-formed
531 // program our base object expression is "this".
532 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
533 if (!MD->isStatic()) {
534 QualType AnonFieldType
535 = Context.getTagDeclType(
536 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
537 QualType ThisType = Context.getTagDeclType(MD->getParent());
538 if ((Context.getCanonicalType(AnonFieldType)
539 == Context.getCanonicalType(ThisType)) ||
540 IsDerivedFrom(ThisType, AnonFieldType)) {
541 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000542 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000543 MD->getThisType(Context));
544 BaseObjectIsPointer = true;
545 }
546 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000547 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
548 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000549 }
550 ExtraQuals = MD->getTypeQualifiers();
551 }
552
553 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000554 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
555 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000556 }
557
558 // Build the implicit member references to the field of the
559 // anonymous struct/union.
560 Expr *Result = BaseObjectExpr;
561 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
562 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
563 FI != FIEnd; ++FI) {
564 QualType MemberType = (*FI)->getType();
565 if (!(*FI)->isMutable()) {
566 unsigned combinedQualifiers
567 = MemberType.getCVRQualifiers() | ExtraQuals;
568 MemberType = MemberType.getQualifiedType(combinedQualifiers);
569 }
Steve Naroff774e4152009-01-21 00:14:39 +0000570 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
571 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000572 BaseObjectIsPointer = false;
573 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
574 OpLoc = SourceLocation();
575 }
576
Sebastian Redlcd883f72009-01-18 18:53:16 +0000577 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000578}
579
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000580/// ActOnDeclarationNameExpr - The parser has read some kind of name
581/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
582/// performs lookup on that name and returns an expression that refers
583/// to that name. This routine isn't directly called from the parser,
584/// because the parser doesn't know about DeclarationName. Rather,
585/// this routine is called by ActOnIdentifierExpr,
586/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
587/// which form the DeclarationName from the corresponding syntactic
588/// forms.
589///
590/// HasTrailingLParen indicates whether this identifier is used in a
591/// function call context. LookupCtx is only used for a C++
592/// qualified-id (foo::bar) to indicate the class or namespace that
593/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000594///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000595/// isAddressOfOperand means that this expression is the direct operand
596/// of an address-of operator. This matters because this is the only
597/// situation where a qualified name referencing a non-static member may
598/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000599Sema::OwningExprResult
600Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
601 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000602 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000603 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000604 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000605 if (SS && SS->isInvalid())
606 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000607 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
608 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000609
Douglas Gregor09be81b2009-02-04 17:27:36 +0000610 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000611 if (Lookup.isAmbiguous()) {
612 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
613 SS && SS->isSet() ? SS->getRange()
614 : SourceRange());
615 return ExprError();
616 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000617 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000618
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000619 // If this reference is in an Objective-C method, then ivar lookup happens as
620 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000621 IdentifierInfo *II = Name.getAsIdentifierInfo();
622 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000623 // There are two cases to handle here. 1) scoped lookup could have failed,
624 // in which case we should look for an ivar. 2) scoped lookup could have
625 // found a decl, but that decl is outside the current method (i.e. a global
626 // variable). In these two cases, we do a lookup for an ivar with this
627 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000628 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000629 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000630 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000631 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000632 if (DiagnoseUseOfDecl(IV, Loc))
633 return ExprError();
Chris Lattner2a3bef92009-02-16 17:19:12 +0000634
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000635 // FIXME: This should use a new expr for a direct reference, don't turn
636 // this into Self->ivar, just return a BareIVarExpr or something.
637 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000638 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000639 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
640 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000641 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000642 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000643 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000644 }
645 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000646 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000647 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000648 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000649 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000650 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000651 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000652 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000653
Douglas Gregoraa57e862009-02-18 21:56:37 +0000654 // Determine whether this name might be a candidate for
655 // argument-dependent lookup.
656 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
657 HasTrailingLParen;
658
659 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000660 // We've seen something of the form
661 //
662 // identifier(
663 //
664 // and we did not find any entity by the name
665 // "identifier". However, this identifier is still subject to
666 // argument-dependent lookup, so keep track of the name.
667 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
668 Context.OverloadTy,
669 Loc));
670 }
671
Chris Lattner4b009652007-07-25 00:24:17 +0000672 if (D == 0) {
673 // Otherwise, this could be an implicitly declared function reference (legal
674 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000675 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000676 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000677 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000678 else {
679 // If this name wasn't predeclared and if this is not a function call,
680 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000681 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000682 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
683 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000684 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
685 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000686 return ExprError(Diag(Loc, diag::err_undeclared_use)
687 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000688 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000689 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000690 }
691 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000692
Sebastian Redl0c9da212009-02-03 20:19:35 +0000693 // If this is an expression of the form &Class::member, don't build an
694 // implicit member ref, because we want a pointer to the member in general,
695 // not any specific instance's member.
696 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000697 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000698 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000699 QualType DType;
700 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
701 DType = FD->getType().getNonReferenceType();
702 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
703 DType = Method->getType();
704 } else if (isa<OverloadedFunctionDecl>(D)) {
705 DType = Context.OverloadTy;
706 }
707 // Could be an inner type. That's diagnosed below, so ignore it here.
708 if (!DType.isNull()) {
709 // The pointer is type- and value-dependent if it points into something
710 // dependent.
711 bool Dependent = false;
712 for (; DC; DC = DC->getParent()) {
713 // FIXME: could stop early at namespace scope.
714 if (DC->isRecord()) {
715 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
716 if (Context.getTypeDeclType(Record)->isDependentType()) {
717 Dependent = true;
718 break;
719 }
720 }
721 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000722 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000723 }
724 }
725 }
726
Douglas Gregor723d3332009-01-07 00:43:41 +0000727 // We may have found a field within an anonymous union or struct
728 // (C++ [class.union]).
729 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
730 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
731 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000732
Douglas Gregor3257fb52008-12-22 05:46:06 +0000733 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
734 if (!MD->isStatic()) {
735 // C++ [class.mfct.nonstatic]p2:
736 // [...] if name lookup (3.4.1) resolves the name in the
737 // id-expression to a nonstatic nontype member of class X or of
738 // a base class of X, the id-expression is transformed into a
739 // class member access expression (5.2.5) using (*this) (9.3.2)
740 // as the postfix-expression to the left of the '.' operator.
741 DeclContext *Ctx = 0;
742 QualType MemberType;
743 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
744 Ctx = FD->getDeclContext();
745 MemberType = FD->getType();
746
747 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
748 MemberType = RefType->getPointeeType();
749 else if (!FD->isMutable()) {
750 unsigned combinedQualifiers
751 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
752 MemberType = MemberType.getQualifiedType(combinedQualifiers);
753 }
754 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
755 if (!Method->isStatic()) {
756 Ctx = Method->getParent();
757 MemberType = Method->getType();
758 }
759 } else if (OverloadedFunctionDecl *Ovl
760 = dyn_cast<OverloadedFunctionDecl>(D)) {
761 for (OverloadedFunctionDecl::function_iterator
762 Func = Ovl->function_begin(),
763 FuncEnd = Ovl->function_end();
764 Func != FuncEnd; ++Func) {
765 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
766 if (!DMethod->isStatic()) {
767 Ctx = Ovl->getDeclContext();
768 MemberType = Context.OverloadTy;
769 break;
770 }
771 }
772 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000773
774 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000775 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
776 QualType ThisType = Context.getTagDeclType(MD->getParent());
777 if ((Context.getCanonicalType(CtxType)
778 == Context.getCanonicalType(ThisType)) ||
779 IsDerivedFrom(ThisType, CtxType)) {
780 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000781 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000782 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000783 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000784 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000785 }
786 }
787 }
788 }
789
Douglas Gregor8acb7272008-12-11 16:49:14 +0000790 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000791 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
792 if (MD->isStatic())
793 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000794 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
795 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000796 }
797
Douglas Gregor3257fb52008-12-22 05:46:06 +0000798 // Any other ways we could have found the field in a well-formed
799 // program would have been turned into implicit member expressions
800 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000801 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
802 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000803 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000804
Chris Lattner4b009652007-07-25 00:24:17 +0000805 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000806 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000807 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000808 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000809 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000810 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000811
Steve Naroffd6163f32008-09-05 22:11:13 +0000812 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000813 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000814 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
815 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000816 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
817 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
818 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000819 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000820
Douglas Gregoraa57e862009-02-18 21:56:37 +0000821 // Check whether this declaration can be used. Note that we suppress
822 // this check when we're going to perform argument-dependent lookup
823 // on this function name, because this might not be the function
824 // that overload resolution actually selects.
825 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
826 return ExprError();
827
Douglas Gregor48840c72008-12-10 23:01:14 +0000828 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000829 // Warn about constructs like:
830 // if (void *X = foo()) { ... } else { X }.
831 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000832 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
833 Scope *CheckS = S;
834 while (CheckS) {
835 if (CheckS->isWithinElse() &&
836 CheckS->getControlParent()->isDeclScope(Var)) {
837 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000838 ExprError(Diag(Loc, diag::warn_value_always_false)
839 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000840 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000841 ExprError(Diag(Loc, diag::warn_value_always_zero)
842 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000843 break;
844 }
845
846 // Move up one more control parent to check again.
847 CheckS = CheckS->getControlParent();
848 if (CheckS)
849 CheckS = CheckS->getParent();
850 }
851 }
852 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000853
854 // Only create DeclRefExpr's for valid Decl's.
855 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000856 return ExprError();
857
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000858 // If the identifier reference is inside a block, and it refers to a value
859 // that is outside the block, create a BlockDeclRefExpr instead of a
860 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
861 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000862 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000863 // We do not do this for things like enum constants, global variables, etc,
864 // as they do not get snapshotted.
865 //
866 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000867 // The BlocksAttr indicates the variable is bound by-reference.
868 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000869 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000870 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000871
Steve Naroff52059382008-10-10 01:28:17 +0000872 // Variable will be bound by-copy, make it const within the closure.
873 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000874 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000875 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000876 }
877 // If this reference is not in a block or if the referenced variable is
878 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000879
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000880 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000881 bool ValueDependent = false;
882 if (getLangOptions().CPlusPlus) {
883 // C++ [temp.dep.expr]p3:
884 // An id-expression is type-dependent if it contains:
885 // - an identifier that was declared with a dependent type,
886 if (VD->getType()->isDependentType())
887 TypeDependent = true;
888 // - FIXME: a template-id that is dependent,
889 // - a conversion-function-id that specifies a dependent type,
890 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
891 Name.getCXXNameType()->isDependentType())
892 TypeDependent = true;
893 // - a nested-name-specifier that contains a class-name that
894 // names a dependent type.
895 else if (SS && !SS->isEmpty()) {
896 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
897 DC; DC = DC->getParent()) {
898 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000899 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000900 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
901 if (Context.getTypeDeclType(Record)->isDependentType()) {
902 TypeDependent = true;
903 break;
904 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000905 }
906 }
907 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000908
Douglas Gregora5d84612008-12-10 20:57:37 +0000909 // C++ [temp.dep.constexpr]p2:
910 //
911 // An identifier is value-dependent if it is:
912 // - a name declared with a dependent type,
913 if (TypeDependent)
914 ValueDependent = true;
915 // - the name of a non-type template parameter,
916 else if (isa<NonTypeTemplateParmDecl>(VD))
917 ValueDependent = true;
918 // - a constant with integral or enumeration type and is
919 // initialized with an expression that is value-dependent
920 // (FIXME!).
921 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000922
Sebastian Redlcd883f72009-01-18 18:53:16 +0000923 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
924 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000925}
926
Sebastian Redlcd883f72009-01-18 18:53:16 +0000927Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
928 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000929 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000930
Chris Lattner4b009652007-07-25 00:24:17 +0000931 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000932 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000933 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
934 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
935 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000936 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000937
Chris Lattner7e637512008-01-12 08:14:25 +0000938 // Pre-defined identifiers are of type char[x], where x is the length of the
939 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000940 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000941 if (FunctionDecl *FD = getCurFunctionDecl())
942 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000943 else if (ObjCMethodDecl *MD = getCurMethodDecl())
944 Length = MD->getSynthesizedMethodSize();
945 else {
946 Diag(Loc, diag::ext_predef_outside_function);
947 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
948 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
949 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000950
951
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000952 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000953 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000954 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000955 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000956}
957
Sebastian Redlcd883f72009-01-18 18:53:16 +0000958Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000959 llvm::SmallString<16> CharBuffer;
960 CharBuffer.resize(Tok.getLength());
961 const char *ThisTokBegin = &CharBuffer[0];
962 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000963
Chris Lattner4b009652007-07-25 00:24:17 +0000964 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
965 Tok.getLocation(), PP);
966 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000967 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000968
969 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
970
Sebastian Redl75324932009-01-20 22:23:13 +0000971 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
972 Literal.isWide(),
973 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000974}
975
Sebastian Redlcd883f72009-01-18 18:53:16 +0000976Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
977 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000978 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
979 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000980 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000981 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000982 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000983 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000984 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000985
Chris Lattner4b009652007-07-25 00:24:17 +0000986 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000987 // Add padding so that NumericLiteralParser can overread by one character.
988 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000989 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990
Chris Lattner4b009652007-07-25 00:24:17 +0000991 // Get the spelling of the token, which eliminates trigraphs, etc.
992 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000993
Chris Lattner4b009652007-07-25 00:24:17 +0000994 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
995 Tok.getLocation(), PP);
996 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000997 return ExprError();
998
Chris Lattner1de66eb2007-08-26 03:42:43 +0000999 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001000
Chris Lattner1de66eb2007-08-26 03:42:43 +00001001 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001002 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001003 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001004 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001005 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001006 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001007 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001008 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001009
1010 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1011
Ted Kremenekddedbe22007-11-29 00:56:49 +00001012 // isExact will be set by GetFloatValue().
1013 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001014 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1015 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001016
Chris Lattner1de66eb2007-08-26 03:42:43 +00001017 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001018 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001019 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001020 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001021
Neil Booth7421e9c2007-08-29 22:00:19 +00001022 // long long is a C99 feature.
1023 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001024 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001025 Diag(Tok.getLocation(), diag::ext_longlong);
1026
Chris Lattner4b009652007-07-25 00:24:17 +00001027 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001028 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001029
Chris Lattner4b009652007-07-25 00:24:17 +00001030 if (Literal.GetIntegerValue(ResultVal)) {
1031 // If this value didn't fit into uintmax_t, warn and force to ull.
1032 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001033 Ty = Context.UnsignedLongLongTy;
1034 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001035 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001036 } else {
1037 // If this value fits into a ULL, try to figure out what else it fits into
1038 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001039
Chris Lattner4b009652007-07-25 00:24:17 +00001040 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1041 // be an unsigned int.
1042 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1043
1044 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001045 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001046 if (!Literal.isLong && !Literal.isLongLong) {
1047 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001048 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001049
Chris Lattner4b009652007-07-25 00:24:17 +00001050 // Does it fit in a unsigned int?
1051 if (ResultVal.isIntN(IntSize)) {
1052 // Does it fit in a signed int?
1053 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001054 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001055 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001056 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001057 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001058 }
Chris Lattner4b009652007-07-25 00:24:17 +00001059 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001060
Chris Lattner4b009652007-07-25 00:24:17 +00001061 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001062 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001063 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001064
Chris Lattner4b009652007-07-25 00:24:17 +00001065 // Does it fit in a unsigned long?
1066 if (ResultVal.isIntN(LongSize)) {
1067 // Does it fit in a signed long?
1068 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001069 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001070 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001071 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001072 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001073 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001074 }
1075
Chris Lattner4b009652007-07-25 00:24:17 +00001076 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001077 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001078 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001079
Chris Lattner4b009652007-07-25 00:24:17 +00001080 // Does it fit in a unsigned long long?
1081 if (ResultVal.isIntN(LongLongSize)) {
1082 // Does it fit in a signed long long?
1083 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001084 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001085 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001086 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001087 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001088 }
1089 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001090
Chris Lattner4b009652007-07-25 00:24:17 +00001091 // If we still couldn't decide a type, we probably have something that
1092 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001093 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001094 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001095 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001096 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001097 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001098
Chris Lattnere4068872008-05-09 05:59:00 +00001099 if (ResultVal.getBitWidth() != Width)
1100 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001101 }
Sebastian Redl75324932009-01-20 22:23:13 +00001102 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001103 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001104
Chris Lattner1de66eb2007-08-26 03:42:43 +00001105 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1106 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001107 Res = new (Context) ImaginaryLiteral(Res,
1108 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001109
1110 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001111}
1112
Sebastian Redlcd883f72009-01-18 18:53:16 +00001113Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1114 SourceLocation R, ExprArg Val) {
1115 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001116 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001117 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001118}
1119
1120/// The UsualUnaryConversions() function is *not* called by this routine.
1121/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001122bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1123 SourceLocation OpLoc,
1124 const SourceRange &ExprRange,
1125 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001126 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001127 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001128 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001129 if (isSizeof)
1130 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1131 return false;
1132 }
1133
1134 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001135 Diag(OpLoc, diag::ext_sizeof_void_type)
1136 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001137 return false;
1138 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001139
Chris Lattner159fe082009-01-24 19:46:37 +00001140 return DiagnoseIncompleteType(OpLoc, exprType,
1141 isSizeof ? diag::err_sizeof_incomplete_type :
1142 diag::err_alignof_incomplete_type,
1143 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001144}
1145
Chris Lattner8d9f7962009-01-24 20:17:12 +00001146bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1147 const SourceRange &ExprRange) {
1148 E = E->IgnoreParens();
1149
1150 // alignof decl is always ok.
1151 if (isa<DeclRefExpr>(E))
1152 return false;
1153
1154 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1155 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1156 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001157 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001158 return true;
1159 }
1160 // Other fields are ok.
1161 return false;
1162 }
1163 }
1164 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1165}
1166
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001167/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1168/// the same for @c alignof and @c __alignof
1169/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001170Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001171Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1172 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001173 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001174 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001175
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001176 QualType ArgTy;
1177 SourceRange Range;
1178 if (isType) {
1179 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1180 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001181
1182 // Verify that the operand is valid.
1183 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1184 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001185 } else {
1186 // Get the end location.
1187 Expr *ArgEx = (Expr *)TyOrEx;
1188 Range = ArgEx->getSourceRange();
1189 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001190
1191 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001192 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001193 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001194 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001195 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1196 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1197 isInvalid = true;
1198 } else {
1199 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1200 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001201
1202 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001203 DeleteExpr(ArgEx);
1204 return ExprError();
1205 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001206 }
1207
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001208 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001209 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001210 Context.getSizeType(), OpLoc,
1211 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001212}
1213
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001214QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Chris Lattner03931a72007-08-24 21:16:53 +00001215 DefaultFunctionArrayConversion(V);
1216
Chris Lattnera16e42d2007-08-26 05:39:26 +00001217 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001218 if (const ComplexType *CT = V->getType()->getAsComplexType())
1219 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001220
1221 // Otherwise they pass through real integer and floating point types here.
1222 if (V->getType()->isArithmeticType())
1223 return V->getType();
1224
1225 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001226 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1227 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001228 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001229}
1230
1231
Chris Lattner4b009652007-07-25 00:24:17 +00001232
Sebastian Redl8b769972009-01-19 00:08:26 +00001233Action::OwningExprResult
1234Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1235 tok::TokenKind Kind, ExprArg Input) {
1236 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001237
Chris Lattner4b009652007-07-25 00:24:17 +00001238 UnaryOperator::Opcode Opc;
1239 switch (Kind) {
1240 default: assert(0 && "Unknown unary op!");
1241 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1242 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1243 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001244
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001245 if (getLangOptions().CPlusPlus &&
1246 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1247 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001248 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001249 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1250
1251 // C++ [over.inc]p1:
1252 //
1253 // [...] If the function is a member function with one
1254 // parameter (which shall be of type int) or a non-member
1255 // function with two parameters (the second of which shall be
1256 // of type int), it defines the postfix increment operator ++
1257 // for objects of that type. When the postfix increment is
1258 // called as a result of using the ++ operator, the int
1259 // argument will have value zero.
1260 Expr *Args[2] = {
1261 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001262 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1263 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001264 };
1265
1266 // Build the candidate set for overloading
1267 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001268 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1269 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001270
1271 // Perform overload resolution.
1272 OverloadCandidateSet::iterator Best;
1273 switch (BestViableFunction(CandidateSet, Best)) {
1274 case OR_Success: {
1275 // We found a built-in operator or an overloaded operator.
1276 FunctionDecl *FnDecl = Best->Function;
1277
1278 if (FnDecl) {
1279 // We matched an overloaded operator. Build a call to that
1280 // operator.
1281
1282 // Convert the arguments.
1283 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1284 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001285 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001286 } else {
1287 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001288 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001289 FnDecl->getParamDecl(0)->getType(),
1290 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001291 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001292 }
1293
1294 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001295 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001296 = FnDecl->getType()->getAsFunctionType()->getResultType();
1297 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001298
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001299 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001300 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001301 SourceLocation());
1302 UsualUnaryConversions(FnExpr);
1303
Sebastian Redl8b769972009-01-19 00:08:26 +00001304 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001305 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1306 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001307 } else {
1308 // We matched a built-in operator. Convert the arguments, then
1309 // break out so that we will build the appropriate built-in
1310 // operator node.
1311 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1312 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001313 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001314
1315 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001316 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001317 }
1318
1319 case OR_No_Viable_Function:
1320 // No viable function; fall through to handling this as a
1321 // built-in operator, which will produce an error message for us.
1322 break;
1323
1324 case OR_Ambiguous:
1325 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1326 << UnaryOperator::getOpcodeStr(Opc)
1327 << Arg->getSourceRange();
1328 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001329 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001330
1331 case OR_Deleted:
1332 Diag(OpLoc, diag::err_ovl_deleted_oper)
1333 << Best->Function->isDeleted()
1334 << UnaryOperator::getOpcodeStr(Opc)
1335 << Arg->getSourceRange();
1336 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1337 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001338 }
1339
1340 // Either we found no viable overloaded operator or we matched a
1341 // built-in operator. In either case, fall through to trying to
1342 // build a built-in operation.
1343 }
1344
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001345 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1346 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001347 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001348 return ExprError();
1349 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001350 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001351}
1352
Sebastian Redl8b769972009-01-19 00:08:26 +00001353Action::OwningExprResult
1354Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1355 ExprArg Idx, SourceLocation RLoc) {
1356 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1357 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001358
Douglas Gregor80723c52008-11-19 17:17:41 +00001359 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001360 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001361 LHSExp->getType()->isEnumeralType() ||
1362 RHSExp->getType()->isRecordType() ||
1363 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001364 // Add the appropriate overloaded operators (C++ [over.match.oper])
1365 // to the candidate set.
1366 OverloadCandidateSet CandidateSet;
1367 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001368 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1369 SourceRange(LLoc, RLoc)))
1370 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001371
Douglas Gregor80723c52008-11-19 17:17:41 +00001372 // Perform overload resolution.
1373 OverloadCandidateSet::iterator Best;
1374 switch (BestViableFunction(CandidateSet, Best)) {
1375 case OR_Success: {
1376 // We found a built-in operator or an overloaded operator.
1377 FunctionDecl *FnDecl = Best->Function;
1378
1379 if (FnDecl) {
1380 // We matched an overloaded operator. Build a call to that
1381 // operator.
1382
1383 // Convert the arguments.
1384 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1385 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1386 PerformCopyInitialization(RHSExp,
1387 FnDecl->getParamDecl(0)->getType(),
1388 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001389 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001390 } else {
1391 // Convert the arguments.
1392 if (PerformCopyInitialization(LHSExp,
1393 FnDecl->getParamDecl(0)->getType(),
1394 "passing") ||
1395 PerformCopyInitialization(RHSExp,
1396 FnDecl->getParamDecl(1)->getType(),
1397 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001398 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001399 }
1400
1401 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001402 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001403 = FnDecl->getType()->getAsFunctionType()->getResultType();
1404 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001405
Douglas Gregor80723c52008-11-19 17:17:41 +00001406 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001407 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001408 SourceLocation());
1409 UsualUnaryConversions(FnExpr);
1410
Sebastian Redl8b769972009-01-19 00:08:26 +00001411 Base.release();
1412 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001413 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001414 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001415 } else {
1416 // We matched a built-in operator. Convert the arguments, then
1417 // break out so that we will build the appropriate built-in
1418 // operator node.
1419 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1420 "passing") ||
1421 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1422 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001423 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001424
1425 break;
1426 }
1427 }
1428
1429 case OR_No_Viable_Function:
1430 // No viable function; fall through to handling this as a
1431 // built-in operator, which will produce an error message for us.
1432 break;
1433
1434 case OR_Ambiguous:
1435 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1436 << "[]"
1437 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1438 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001439 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001440
1441 case OR_Deleted:
1442 Diag(LLoc, diag::err_ovl_deleted_oper)
1443 << Best->Function->isDeleted()
1444 << "[]"
1445 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1446 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1447 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001448 }
1449
1450 // Either we found no viable overloaded operator or we matched a
1451 // built-in operator. In either case, fall through to trying to
1452 // build a built-in operation.
1453 }
1454
Chris Lattner4b009652007-07-25 00:24:17 +00001455 // Perform default conversions.
1456 DefaultFunctionArrayConversion(LHSExp);
1457 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001458
Chris Lattner4b009652007-07-25 00:24:17 +00001459 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1460
1461 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001462 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001463 // in the subscript position. As a result, we need to derive the array base
1464 // and index from the expression types.
1465 Expr *BaseExpr, *IndexExpr;
1466 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001467 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001468 BaseExpr = LHSExp;
1469 IndexExpr = RHSExp;
1470 // FIXME: need to deal with const...
1471 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001472 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001473 // Handle the uncommon case of "123[Ptr]".
1474 BaseExpr = RHSExp;
1475 IndexExpr = LHSExp;
1476 // FIXME: need to deal with const...
1477 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001478 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1479 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001480 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001481
Chris Lattner4b009652007-07-25 00:24:17 +00001482 // FIXME: need to deal with const...
1483 ResultType = VTy->getElementType();
1484 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001485 return ExprError(Diag(LHSExp->getLocStart(),
1486 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1487 }
Chris Lattner4b009652007-07-25 00:24:17 +00001488 // C99 6.5.2.1p1
1489 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001490 return ExprError(Diag(IndexExpr->getLocStart(),
1491 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001492
1493 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1494 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001495 // void (*)(int)) and pointers to incomplete types. Functions are not
1496 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001497 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001498 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001499 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001500 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001501
Sebastian Redl8b769972009-01-19 00:08:26 +00001502 Base.release();
1503 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001504 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1505 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001506}
1507
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001508QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001509CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001510 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001511 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001512
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001513 // The vector accessor can't exceed the number of elements.
1514 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001515
1516 // This flag determines whether or not the component is one of the four
1517 // special names that indicate a subset of exactly half the elements are
1518 // to be selected.
1519 bool HalvingSwizzle = false;
1520
1521 // This flag determines whether or not CompName has an 's' char prefix,
1522 // indicating that it is a string of hex values to be used as vector indices.
1523 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001524
1525 // Check that we've found one of the special components, or that the component
1526 // names must come from the same set.
1527 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001528 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1529 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001530 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001531 do
1532 compStr++;
1533 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001534 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001535 do
1536 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001537 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001538 }
Nate Begeman1486b502009-01-18 01:47:54 +00001539
1540 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001541 // We didn't get to the end of the string. This means the component names
1542 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001543 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1544 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001545 return QualType();
1546 }
Nate Begeman1486b502009-01-18 01:47:54 +00001547
1548 // Ensure no component accessor exceeds the width of the vector type it
1549 // operates on.
1550 if (!HalvingSwizzle) {
1551 compStr = CompName.getName();
1552
1553 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001554 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001555
1556 while (*compStr) {
1557 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1558 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1559 << baseType << SourceRange(CompLoc);
1560 return QualType();
1561 }
1562 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001563 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001564
Nate Begeman1486b502009-01-18 01:47:54 +00001565 // If this is a halving swizzle, verify that the base type has an even
1566 // number of elements.
1567 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001568 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001569 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001570 return QualType();
1571 }
1572
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001573 // The component accessor looks fine - now we need to compute the actual type.
1574 // The vector type is implied by the component accessor. For example,
1575 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001576 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001577 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001578 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1579 : CompName.getLength();
1580 if (HexSwizzle)
1581 CompSize--;
1582
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001583 if (CompSize == 1)
1584 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001585
Nate Begemanaf6ed502008-04-18 23:10:10 +00001586 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001587 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001588 // diagostics look bad. We want extended vector types to appear built-in.
1589 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1590 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1591 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001592 }
1593 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001594}
1595
Chris Lattner2cb744b2009-02-15 22:43:40 +00001596
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001597/// constructSetterName - Return the setter name for the given
1598/// identifier, i.e. "set" + Name where the initial character of Name
1599/// has been capitalized.
1600// FIXME: Merge with same routine in Parser. But where should this
1601// live?
1602static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1603 const IdentifierInfo *Name) {
1604 llvm::SmallString<100> SelectorName;
1605 SelectorName = "set";
1606 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1607 SelectorName[3] = toupper(SelectorName[3]);
1608 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1609}
1610
Sebastian Redl8b769972009-01-19 00:08:26 +00001611Action::OwningExprResult
1612Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1613 tok::TokenKind OpKind, SourceLocation MemberLoc,
1614 IdentifierInfo &Member) {
1615 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001616 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001617
1618 // Perform default conversions.
1619 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001620
Steve Naroff2cb66382007-07-26 03:11:44 +00001621 QualType BaseType = BaseExpr->getType();
1622 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001623
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001624 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1625 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001626 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001627 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001628 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001629 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001630 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1631 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001632 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001633 return ExprError(Diag(MemberLoc,
1634 diag::err_typecheck_member_reference_arrow)
1635 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001636 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001637
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001638 // Handle field access to simple records. This also handles access to fields
1639 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001640 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001641 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001642 if (DiagnoseIncompleteType(OpLoc, BaseType,
1643 diag::err_typecheck_incomplete_tag,
1644 BaseExpr->getSourceRange()))
1645 return ExprError();
1646
Steve Naroff2cb66382007-07-26 03:11:44 +00001647 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001648 // FIXME: Qualified name lookup for C++ is a bit more complicated
1649 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001650 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001651 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001652 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001653
Douglas Gregor09be81b2009-02-04 17:27:36 +00001654 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001655 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001656 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1657 << &Member << BaseExpr->getSourceRange());
1658 else if (Result.isAmbiguous()) {
1659 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1660 MemberLoc, BaseExpr->getSourceRange());
1661 return ExprError();
1662 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001663 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001664
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001665 // If the decl being referenced had an error, return an error for this
1666 // sub-expr without emitting another error, in order to avoid cascading
1667 // error cases.
1668 if (MemberDecl->isInvalidDecl())
1669 return ExprError();
Chris Lattnerb63f8132009-02-16 17:07:21 +00001670
Douglas Gregoraa57e862009-02-18 21:56:37 +00001671 // Check the use of this field
1672 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1673 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001674
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001675 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001676 // We may have found a field within an anonymous union or struct
1677 // (C++ [class.union]).
1678 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001679 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001680 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001681
Douglas Gregor82d44772008-12-20 23:49:58 +00001682 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1683 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001684 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001685 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1686 MemberType = Ref->getPointeeType();
1687 else {
1688 unsigned combinedQualifiers =
1689 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001690 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001691 combinedQualifiers &= ~QualType::Const;
1692 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1693 }
Eli Friedman76b49832008-02-06 22:48:16 +00001694
Steve Naroff774e4152009-01-21 00:14:39 +00001695 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1696 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001697 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001698 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001699 Var, MemberLoc,
1700 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001701 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001702 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1703 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001704 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001705 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001706 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001707 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001708 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001709 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001710 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001711 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001712 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1713 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001714
Douglas Gregor82d44772008-12-20 23:49:58 +00001715 // We found a declaration kind that we didn't expect. This is a
1716 // generic error message that tells the user that she can't refer
1717 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001718 return ExprError(Diag(MemberLoc,
1719 diag::err_typecheck_member_reference_unknown)
1720 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001721 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001722
Chris Lattnere9d71612008-07-21 04:59:05 +00001723 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1724 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001725 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001726 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001727 // If the decl being referenced had an error, return an error for this
1728 // sub-expr without emitting another error, in order to avoid cascading
1729 // error cases.
1730 if (IV->isInvalidDecl())
1731 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001732
1733 // Check whether we can reference this field.
1734 if (DiagnoseUseOfDecl(IV, MemberLoc))
1735 return ExprError();
Chris Lattner2a3bef92009-02-16 17:19:12 +00001736
Steve Naroff774e4152009-01-21 00:14:39 +00001737 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1738 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001739 OpKind == tok::arrow);
1740 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001741 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001742 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001743 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1744 << IFTy->getDecl()->getDeclName() << &Member
1745 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001746 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001747
Chris Lattnere9d71612008-07-21 04:59:05 +00001748 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1749 // pointer to a (potentially qualified) interface type.
1750 const PointerType *PTy;
1751 const ObjCInterfaceType *IFTy;
1752 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1753 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1754 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001755
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001756 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001757 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001758 // Check whether we can reference this property.
1759 if (DiagnoseUseOfDecl(PD, MemberLoc))
1760 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001761
Steve Naroff774e4152009-01-21 00:14:39 +00001762 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001763 MemberLoc, BaseExpr));
1764 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001765
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001766 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001767 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1768 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001769 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001770 // Check whether we can reference this property.
1771 if (DiagnoseUseOfDecl(PD, MemberLoc))
1772 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001773
Steve Naroff774e4152009-01-21 00:14:39 +00001774 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001775 MemberLoc, BaseExpr));
1776 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001777
1778 // If that failed, look for an "implicit" property by seeing if the nullary
1779 // selector is implemented.
1780
1781 // FIXME: The logic for looking up nullary and unary selectors should be
1782 // shared with the code in ActOnInstanceMessage.
1783
1784 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1785 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001786
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001787 // If this reference is in an @implementation, check for 'private' methods.
1788 if (!Getter)
1789 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1790 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1791 if (ObjCImplementationDecl *ImpDecl =
1792 ObjCImplementations[ClassDecl->getIdentifier()])
1793 Getter = ImpDecl->getInstanceMethod(Sel);
1794
Steve Naroff04151f32008-10-22 19:16:27 +00001795 // Look through local category implementations associated with the class.
1796 if (!Getter) {
1797 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1798 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1799 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1800 }
1801 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001802 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001803 // Check if we can reference this property.
1804 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1805 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001806
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001807 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001808 // will look for the matching setter, in case it is needed.
1809 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1810 &Member);
1811 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1812 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1813 if (!Setter) {
1814 // If this reference is in an @implementation, also check for 'private'
1815 // methods.
1816 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1817 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1818 if (ObjCImplementationDecl *ImpDecl =
1819 ObjCImplementations[ClassDecl->getIdentifier()])
1820 Setter = ImpDecl->getInstanceMethod(SetterSel);
1821 }
1822 // Look through local category implementations associated with the class.
1823 if (!Setter) {
1824 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1825 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1826 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1827 }
1828 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001829
Douglas Gregoraa57e862009-02-18 21:56:37 +00001830 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1831 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001832
Sebastian Redl8b769972009-01-19 00:08:26 +00001833 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001834 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1835 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001836 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001837
1838 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1839 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001840 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001841 // Handle properties on qualified "id" protocols.
1842 const ObjCQualifiedIdType *QIdTy;
1843 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1844 // Check protocols on qualified interfaces.
1845 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001846 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001847 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001848 // Check the use of this declaration
1849 if (DiagnoseUseOfDecl(PD, MemberLoc))
1850 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001851
Steve Naroff774e4152009-01-21 00:14:39 +00001852 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001853 MemberLoc, BaseExpr));
1854 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001855 // Also must look for a getter name which uses property syntax.
1856 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1857 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001858 // Check the use of this method.
1859 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1860 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001861
Steve Naroff774e4152009-01-21 00:14:39 +00001862 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1863 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001864 }
1865 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001866
1867 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1868 << &Member << BaseType);
1869 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001870 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001871 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001872 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1873 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001874 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001875 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1876 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001877 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001878
1879 return ExprError(Diag(MemberLoc,
1880 diag::err_typecheck_member_reference_struct_union)
1881 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001882}
1883
Douglas Gregor3257fb52008-12-22 05:46:06 +00001884/// ConvertArgumentsForCall - Converts the arguments specified in
1885/// Args/NumArgs to the parameter types of the function FDecl with
1886/// function prototype Proto. Call is the call expression itself, and
1887/// Fn is the function expression. For a C++ member function, this
1888/// routine does not attempt to convert the object argument. Returns
1889/// true if the call is ill-formed.
1890bool
1891Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1892 FunctionDecl *FDecl,
1893 const FunctionTypeProto *Proto,
1894 Expr **Args, unsigned NumArgs,
1895 SourceLocation RParenLoc) {
1896 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1897 // assignment, to the types of the corresponding parameter, ...
1898 unsigned NumArgsInProto = Proto->getNumArgs();
1899 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001900 bool Invalid = false;
1901
Douglas Gregor3257fb52008-12-22 05:46:06 +00001902 // If too few arguments are available (and we don't have default
1903 // arguments for the remaining parameters), don't make the call.
1904 if (NumArgs < NumArgsInProto) {
1905 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1906 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1907 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1908 // Use default arguments for missing arguments
1909 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001910 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001911 }
1912
1913 // If too many are passed and not variadic, error on the extras and drop
1914 // them.
1915 if (NumArgs > NumArgsInProto) {
1916 if (!Proto->isVariadic()) {
1917 Diag(Args[NumArgsInProto]->getLocStart(),
1918 diag::err_typecheck_call_too_many_args)
1919 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1920 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1921 Args[NumArgs-1]->getLocEnd());
1922 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001923 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001924 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001925 }
1926 NumArgsToCheck = NumArgsInProto;
1927 }
1928
1929 // Continue to check argument types (even if we have too few/many args).
1930 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1931 QualType ProtoArgType = Proto->getArgType(i);
1932
1933 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001934 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001935 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001936
1937 // Pass the argument.
1938 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1939 return true;
1940 } else
1941 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001942 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001943 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001944
Douglas Gregor3257fb52008-12-22 05:46:06 +00001945 Call->setArg(i, Arg);
1946 }
1947
1948 // If this is a variadic call, handle args passed through "...".
1949 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001950 VariadicCallType CallType = VariadicFunction;
1951 if (Fn->getType()->isBlockPointerType())
1952 CallType = VariadicBlock; // Block
1953 else if (isa<MemberExpr>(Fn))
1954 CallType = VariadicMethod;
1955
Douglas Gregor3257fb52008-12-22 05:46:06 +00001956 // Promote the arguments (C99 6.5.2.2p7).
1957 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1958 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001959 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001960 Call->setArg(i, Arg);
1961 }
1962 }
1963
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001964 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001965}
1966
Steve Naroff87d58b42007-09-16 03:34:24 +00001967/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001968/// This provides the location of the left/right parens and a list of comma
1969/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001970Action::OwningExprResult
1971Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1972 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001973 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001974 unsigned NumArgs = args.size();
1975 Expr *Fn = static_cast<Expr *>(fn.release());
1976 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001977 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001978 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001979 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001980
Douglas Gregor3257fb52008-12-22 05:46:06 +00001981 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001982 // Determine whether this is a dependent call inside a C++ template,
1983 // in which case we won't do any semantic analysis now.
1984 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1985 bool Dependent = false;
1986 if (Fn->isTypeDependent())
1987 Dependent = true;
1988 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1989 Dependent = true;
1990
1991 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001992 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001993 Context.DependentTy, RParenLoc));
1994
1995 // Determine whether this is a call to an object (C++ [over.call.object]).
1996 if (Fn->getType()->isRecordType())
1997 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1998 CommaLocs, RParenLoc));
1999
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002000 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002001 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2002 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2003 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002004 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2005 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002006 }
2007
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002008 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002009 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002010 Expr *FnExpr = Fn;
2011 bool ADL = true;
2012 while (true) {
2013 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2014 FnExpr = IcExpr->getSubExpr();
2015 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002016 // Parentheses around a function disable ADL
2017 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002018 ADL = false;
2019 FnExpr = PExpr->getSubExpr();
2020 } else if (isa<UnaryOperator>(FnExpr) &&
2021 cast<UnaryOperator>(FnExpr)->getOpcode()
2022 == UnaryOperator::AddrOf) {
2023 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002024 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2025 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2026 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2027 break;
2028 } else if (UnresolvedFunctionNameExpr *DepName
2029 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2030 UnqualifiedName = DepName->getName();
2031 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002032 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002033 // Any kind of name that does not refer to a declaration (or
2034 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2035 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002036 break;
2037 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002038 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002039
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002040 OverloadedFunctionDecl *Ovl = 0;
2041 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002042 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002043 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2044 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002045
Douglas Gregorfcb19192009-02-11 23:02:49 +00002046 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002047 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002048 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002049 ADL = false;
2050
Douglas Gregorfcb19192009-02-11 23:02:49 +00002051 // We don't perform ADL in C.
2052 if (!getLangOptions().CPlusPlus)
2053 ADL = false;
2054
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002055 if (Ovl || ADL) {
2056 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2057 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002058 NumArgs, CommaLocs, RParenLoc, ADL);
2059 if (!FDecl)
2060 return ExprError();
2061
2062 // Update Fn to refer to the actual function selected.
2063 Expr *NewFn = 0;
2064 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002065 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002066 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2067 QDRExpr->getLocation(),
2068 false, false,
2069 QDRExpr->getSourceRange().getBegin());
2070 else
2071 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2072 Fn->getSourceRange().getBegin());
2073 Fn->Destroy(Context);
2074 Fn = NewFn;
2075 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002076 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002077
2078 // Promote the function operand.
2079 UsualUnaryConversions(Fn);
2080
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002081 // Make the call expr early, before semantic checks. This guarantees cleanup
2082 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002083 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2084 Args, NumArgs,
2085 Context.BoolTy,
2086 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002087
Steve Naroffd6163f32008-09-05 22:11:13 +00002088 const FunctionType *FuncT;
2089 if (!Fn->getType()->isBlockPointerType()) {
2090 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2091 // have type pointer to function".
2092 const PointerType *PT = Fn->getType()->getAsPointerType();
2093 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002094 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2095 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002096 FuncT = PT->getPointeeType()->getAsFunctionType();
2097 } else { // This is a block call.
2098 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2099 getAsFunctionType();
2100 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002101 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002102 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2103 << Fn->getType() << Fn->getSourceRange());
2104
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002105 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002106 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002107
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002108 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002109 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2110 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002111 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002112 } else {
2113 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002114
Steve Naroffdb65e052007-08-28 23:30:39 +00002115 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002116 for (unsigned i = 0; i != NumArgs; i++) {
2117 Expr *Arg = Args[i];
2118 DefaultArgumentPromotion(Arg);
2119 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002120 }
Chris Lattner4b009652007-07-25 00:24:17 +00002121 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002122
Douglas Gregor3257fb52008-12-22 05:46:06 +00002123 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2124 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002125 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2126 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002127
Chris Lattner2e64c072007-08-10 20:18:51 +00002128 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002129 if (FDecl)
2130 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002131
Sebastian Redl8b769972009-01-19 00:08:26 +00002132 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002133}
2134
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002135Action::OwningExprResult
2136Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2137 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002138 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002139 QualType literalType = QualType::getFromOpaquePtr(Ty);
2140 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002141 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002142 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002143
Eli Friedman8c2173d2008-05-20 05:22:08 +00002144 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002145 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002146 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2147 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002148 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2149 diag::err_typecheck_decl_incomplete_type,
2150 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002151 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002152
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002153 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002154 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002155 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002156
Chris Lattnere5cb5862008-12-04 23:50:19 +00002157 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002158 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002159 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002160 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002161 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002162 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002163 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2164 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002165}
2166
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002167Action::OwningExprResult
2168Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2169 InitListDesignations &Designators,
2170 SourceLocation RBraceLoc) {
2171 unsigned NumInit = initlist.size();
2172 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002173
Steve Naroff0acc9c92007-09-15 18:49:24 +00002174 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002175 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002176
Steve Naroff774e4152009-01-21 00:14:39 +00002177 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002178 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002179 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002180 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002181}
2182
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002183/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002184bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002185 UsualUnaryConversions(castExpr);
2186
2187 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2188 // type needs to be scalar.
2189 if (castType->isVoidType()) {
2190 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002191 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2192 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002193 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002194 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2195 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2196 (castType->isStructureType() || castType->isUnionType())) {
2197 // GCC struct/union extension: allow cast to self.
2198 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2199 << castType << castExpr->getSourceRange();
2200 } else if (castType->isUnionType()) {
2201 // GCC cast to union extension
2202 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2203 RecordDecl::field_iterator Field, FieldEnd;
2204 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2205 Field != FieldEnd; ++Field) {
2206 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2207 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2208 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2209 << castExpr->getSourceRange();
2210 break;
2211 }
2212 }
2213 if (Field == FieldEnd)
2214 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2215 << castExpr->getType() << castExpr->getSourceRange();
2216 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002217 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002218 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002219 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002220 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002221 } else if (!castExpr->getType()->isScalarType() &&
2222 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002223 return Diag(castExpr->getLocStart(),
2224 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002225 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002226 } else if (castExpr->getType()->isVectorType()) {
2227 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2228 return true;
2229 } else if (castType->isVectorType()) {
2230 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2231 return true;
2232 }
2233 return false;
2234}
2235
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002236bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002237 assert(VectorTy->isVectorType() && "Not a vector type!");
2238
2239 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002240 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002241 return Diag(R.getBegin(),
2242 Ty->isVectorType() ?
2243 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002244 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002245 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002246 } else
2247 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002248 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002249 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002250
2251 return false;
2252}
2253
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002254Action::OwningExprResult
2255Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2256 SourceLocation RParenLoc, ExprArg Op) {
2257 assert((Ty != 0) && (Op.get() != 0) &&
2258 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002259
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002260 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002261 QualType castType = QualType::getFromOpaquePtr(Ty);
2262
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002263 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002264 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002265 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002266 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002267}
2268
Chris Lattner98a425c2007-11-26 01:40:58 +00002269/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2270/// In that case, lex = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002271/// C99 6.5.15
2272QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2273 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002274 UsualUnaryConversions(Cond);
2275 UsualUnaryConversions(LHS);
2276 UsualUnaryConversions(RHS);
2277 QualType CondTy = Cond->getType();
2278 QualType LHSTy = LHS->getType();
2279 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002280
2281 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002282 if (!Cond->isTypeDependent()) {
2283 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2284 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2285 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002286 return QualType();
2287 }
Chris Lattner4b009652007-07-25 00:24:17 +00002288 }
Chris Lattner992ae932008-01-06 22:42:25 +00002289
2290 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002291 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002292 return Context.DependentTy;
2293
Chris Lattner992ae932008-01-06 22:42:25 +00002294 // If both operands have arithmetic type, do the usual arithmetic conversions
2295 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002296 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2297 UsualArithmeticConversions(LHS, RHS);
2298 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002299 }
Chris Lattner992ae932008-01-06 22:42:25 +00002300
2301 // If both operands are the same structure or union type, the result is that
2302 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002303 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2304 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002305 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002306 // "If both the operands have structure or union type, the result has
2307 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002308 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002309 }
Chris Lattner992ae932008-01-06 22:42:25 +00002310
2311 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002312 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002313 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2314 if (!LHSTy->isVoidType())
2315 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2316 << RHS->getSourceRange();
2317 if (!RHSTy->isVoidType())
2318 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2319 << LHS->getSourceRange();
2320 ImpCastExprToType(LHS, Context.VoidTy);
2321 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002322 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002323 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002324 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2325 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002326 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2327 Context.isObjCObjectPointerType(LHSTy)) &&
2328 RHS->isNullPointerConstant(Context)) {
2329 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2330 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002331 }
Chris Lattnere2897262009-02-18 04:28:32 +00002332 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2333 Context.isObjCObjectPointerType(RHSTy)) &&
2334 LHS->isNullPointerConstant(Context)) {
2335 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2336 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002337 }
Chris Lattner9c039b52009-02-18 04:38:20 +00002338
Chris Lattner0ac51632008-01-06 22:50:31 +00002339 // Handle the case where both operands are pointers before we handle null
2340 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002341 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2342 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002343 // get the "pointed to" types
2344 QualType lhptee = LHSPT->getPointeeType();
2345 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002346
Chris Lattner71225142007-07-31 21:27:01 +00002347 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2348 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002349 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002350 // Figure out necessary qualifiers (C99 6.5.15p6)
2351 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002352 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002353 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2354 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002355 return destType;
2356 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002357 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002358 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002359 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002360 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2361 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002362 return destType;
2363 }
Chris Lattner4b009652007-07-25 00:24:17 +00002364
Chris Lattner9c039b52009-02-18 04:38:20 +00002365 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2366 // Two identical pointers types are always compatible.
2367 return LHSTy;
2368 }
2369
Chris Lattnere2897262009-02-18 04:28:32 +00002370 QualType compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002371
2372 // If either type is an Objective-C object type then check
2373 // compatibility according to Objective-C.
Chris Lattnere2897262009-02-18 04:28:32 +00002374 if (Context.isObjCObjectPointerType(LHSTy) ||
2375 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002376 // If both operands are interfaces and either operand can be
2377 // assigned to the other, use that type as the composite
2378 // type. This allows
2379 // xxx ? (A*) a : (B*) b
2380 // where B is a subclass of A.
2381 //
2382 // Additionally, as for assignment, if either type is 'id'
2383 // allow silent coercion. Finally, if the types are
2384 // incompatible then make sure to use 'id' as the composite
2385 // type so the result is acceptable for sending messages to.
2386
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002387 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2388 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002389 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2390 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2391 if (LHSIface && RHSIface &&
2392 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002393 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002394 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002395 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002396 compositeType = RHSTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002397 } else if (Context.isObjCIdStructType(lhptee) ||
2398 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002399 compositeType = Context.getObjCIdType();
2400 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002401 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2402 << LHSTy << RHSTy
2403 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002404 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002405 ImpCastExprToType(LHS, incompatTy);
2406 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002407 return incompatTy;
2408 }
2409 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2410 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002411 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2412 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002413 // In this situation, we assume void* type. No especially good
2414 // reason, but this is what gcc does, and we do have to pick
2415 // to get a consistent AST.
2416 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002417 ImpCastExprToType(LHS, incompatTy);
2418 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002419 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002420 }
2421 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002422 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2423 // differently qualified versions of compatible types, the result type is
2424 // a pointer to an appropriately qualified version of the *composite*
2425 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002426 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002427 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002428 ImpCastExprToType(LHS, compositeType);
2429 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002430 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002431 }
Chris Lattner4b009652007-07-25 00:24:17 +00002432 }
Chris Lattner9c039b52009-02-18 04:38:20 +00002433
2434 // Selection between block pointer types is ok as long as they are the same.
2435 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2436 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2437 return LHSTy;
2438
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002439 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2440 // evaluates to "struct objc_object *" (and is handled above when comparing
2441 // id with statically typed objects).
Chris Lattnere2897262009-02-18 04:28:32 +00002442 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002443 // GCC allows qualified id and any Objective-C type to devolve to
2444 // id. Currently localizing to here until clear this should be
2445 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002446 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
2447 (LHSTy->isObjCQualifiedIdType() &&
2448 Context.isObjCObjectPointerType(RHSTy)) ||
2449 (RHSTy->isObjCQualifiedIdType() &&
2450 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002451 // FIXME: This is not the correct composite type. This only
2452 // happens to work because id can more or less be used anywhere,
2453 // however this may change the type of method sends.
2454 // FIXME: gcc adds some type-checking of the arguments and emits
2455 // (confusing) incompatible comparison warnings in some
2456 // cases. Investigate.
2457 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002458 ImpCastExprToType(LHS, compositeType);
2459 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002460 return compositeType;
2461 }
2462 }
2463
Chris Lattner992ae932008-01-06 22:42:25 +00002464 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002465 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2466 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002467 return QualType();
2468}
2469
Steve Naroff87d58b42007-09-16 03:34:24 +00002470/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002471/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002472Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2473 SourceLocation ColonLoc,
2474 ExprArg Cond, ExprArg LHS,
2475 ExprArg RHS) {
2476 Expr *CondExpr = (Expr *) Cond.get();
2477 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002478
2479 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2480 // was the condition.
2481 bool isLHSNull = LHSExpr == 0;
2482 if (isLHSNull)
2483 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002484
2485 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002486 RHSExpr, QuestionLoc);
2487 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002488 return ExprError();
2489
2490 Cond.release();
2491 LHS.release();
2492 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002493 return Owned(new (Context) ConditionalOperator(CondExpr,
2494 isLHSNull ? 0 : LHSExpr,
2495 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002496}
2497
Chris Lattner4b009652007-07-25 00:24:17 +00002498
2499// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2500// being closely modeled after the C99 spec:-). The odd characteristic of this
2501// routine is it effectively iqnores the qualifiers on the top level pointee.
2502// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2503// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002504Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002505Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2506 QualType lhptee, rhptee;
2507
2508 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002509 lhptee = lhsType->getAsPointerType()->getPointeeType();
2510 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002511
2512 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002513 lhptee = Context.getCanonicalType(lhptee);
2514 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002515
Chris Lattner005ed752008-01-04 18:04:52 +00002516 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002517
2518 // C99 6.5.16.1p1: This following citation is common to constraints
2519 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2520 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002521 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002522 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002523 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002524
2525 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2526 // incomplete type and the other is a pointer to a qualified or unqualified
2527 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002528 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002529 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002530 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002531
2532 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002533 assert(rhptee->isFunctionType());
2534 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002535 }
2536
2537 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002538 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002539 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002540
2541 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002542 assert(lhptee->isFunctionType());
2543 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002544 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002545
2546 // Check for ObjC interfaces
2547 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2548 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2549 if (LHSIface && RHSIface &&
2550 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2551 return ConvTy;
2552
2553 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002554 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002555 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002556 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002557 return ConvTy;
2558
Chris Lattner4b009652007-07-25 00:24:17 +00002559 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2560 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002561 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2562 rhptee.getUnqualifiedType()))
2563 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002564 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002565}
2566
Steve Naroff3454b6c2008-09-04 15:10:53 +00002567/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2568/// block pointer types are compatible or whether a block and normal pointer
2569/// are compatible. It is more restrict than comparing two function pointer
2570// types.
2571Sema::AssignConvertType
2572Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2573 QualType rhsType) {
2574 QualType lhptee, rhptee;
2575
2576 // get the "pointed to" type (ignoring qualifiers at the top level)
2577 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2578 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2579
2580 // make sure we operate on the canonical type
2581 lhptee = Context.getCanonicalType(lhptee);
2582 rhptee = Context.getCanonicalType(rhptee);
2583
2584 AssignConvertType ConvTy = Compatible;
2585
2586 // For blocks we enforce that qualifiers are identical.
2587 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2588 ConvTy = CompatiblePointerDiscardsQualifiers;
2589
2590 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2591 return IncompatibleBlockPointer;
2592 return ConvTy;
2593}
2594
Chris Lattner4b009652007-07-25 00:24:17 +00002595/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2596/// has code to accommodate several GCC extensions when type checking
2597/// pointers. Here are some objectionable examples that GCC considers warnings:
2598///
2599/// int a, *pint;
2600/// short *pshort;
2601/// struct foo *pfoo;
2602///
2603/// pint = pshort; // warning: assignment from incompatible pointer type
2604/// a = pint; // warning: assignment makes integer from pointer without a cast
2605/// pint = a; // warning: assignment makes pointer from integer without a cast
2606/// pint = pfoo; // warning: assignment from incompatible pointer type
2607///
2608/// As a result, the code for dealing with pointers is more complex than the
2609/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002610///
Chris Lattner005ed752008-01-04 18:04:52 +00002611Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002612Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002613 // Get canonical types. We're not formatting these types, just comparing
2614 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002615 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2616 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002617
2618 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002619 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002620
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002621 // If the left-hand side is a reference type, then we are in a
2622 // (rare!) case where we've allowed the use of references in C,
2623 // e.g., as a parameter type in a built-in function. In this case,
2624 // just make sure that the type referenced is compatible with the
2625 // right-hand side type. The caller is responsible for adjusting
2626 // lhsType so that the resulting expression does not have reference
2627 // type.
2628 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2629 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002630 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002631 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002632 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002633
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002634 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2635 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002636 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002637 // Relax integer conversions like we do for pointers below.
2638 if (rhsType->isIntegerType())
2639 return IntToPointer;
2640 if (lhsType->isIntegerType())
2641 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002642 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002643 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002644
Nate Begemanc5f0f652008-07-14 18:02:46 +00002645 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002646 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002647 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2648 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002649 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002650
Nate Begemanc5f0f652008-07-14 18:02:46 +00002651 // If we are allowing lax vector conversions, and LHS and RHS are both
2652 // vectors, the total size only needs to be the same. This is a bitcast;
2653 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002654 if (getLangOptions().LaxVectorConversions &&
2655 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002656 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002657 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002658 }
2659 return Incompatible;
2660 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002661
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002662 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002663 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002664
Chris Lattner390564e2008-04-07 06:49:41 +00002665 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002666 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002667 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002668
Chris Lattner390564e2008-04-07 06:49:41 +00002669 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002670 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002671
Steve Naroffa982c712008-09-29 18:10:17 +00002672 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002673 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002674 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002675
2676 // Treat block pointers as objects.
2677 if (getLangOptions().ObjC1 &&
2678 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2679 return Compatible;
2680 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002681 return Incompatible;
2682 }
2683
2684 if (isa<BlockPointerType>(lhsType)) {
2685 if (rhsType->isIntegerType())
2686 return IntToPointer;
2687
Steve Naroffa982c712008-09-29 18:10:17 +00002688 // Treat block pointers as objects.
2689 if (getLangOptions().ObjC1 &&
2690 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2691 return Compatible;
2692
Steve Naroff3454b6c2008-09-04 15:10:53 +00002693 if (rhsType->isBlockPointerType())
2694 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2695
2696 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2697 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002698 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002699 }
Chris Lattner1853da22008-01-04 23:18:45 +00002700 return Incompatible;
2701 }
2702
Chris Lattner390564e2008-04-07 06:49:41 +00002703 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002704 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002705 if (lhsType == Context.BoolTy)
2706 return Compatible;
2707
2708 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002709 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002710
Chris Lattner390564e2008-04-07 06:49:41 +00002711 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002712 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002713
2714 if (isa<BlockPointerType>(lhsType) &&
2715 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002716 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002717 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002718 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002719
Chris Lattner1853da22008-01-04 23:18:45 +00002720 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002721 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002722 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002723 }
2724 return Incompatible;
2725}
2726
Chris Lattner005ed752008-01-04 18:04:52 +00002727Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002728Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002729 if (getLangOptions().CPlusPlus) {
2730 if (!lhsType->isRecordType()) {
2731 // C++ 5.17p3: If the left operand is not of class type, the
2732 // expression is implicitly converted (C++ 4) to the
2733 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002734 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2735 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002736 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002737 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002738 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002739 }
2740
2741 // FIXME: Currently, we fall through and treat C++ classes like C
2742 // structures.
2743 }
2744
Steve Naroffcdee22d2007-11-27 17:58:44 +00002745 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2746 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002747 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2748 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002749 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002750 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002751 return Compatible;
2752 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002753
2754 // We don't allow conversion of non-null-pointer constants to integers.
2755 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2756 return IntToBlockPointer;
2757
Chris Lattner5f505bf2007-10-16 02:55:40 +00002758 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002759 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002760 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002761 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002762 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002763 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002764 if (!lhsType->isReferenceType())
2765 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002766
Chris Lattner005ed752008-01-04 18:04:52 +00002767 Sema::AssignConvertType result =
2768 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002769
2770 // C99 6.5.16.1p2: The value of the right operand is converted to the
2771 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002772 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2773 // so that we can use references in built-in functions even in C.
2774 // The getNonReferenceType() call makes sure that the resulting expression
2775 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002776 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002777 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002778 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002779}
2780
Chris Lattner005ed752008-01-04 18:04:52 +00002781Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002782Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2783 return CheckAssignmentConstraints(lhsType, rhsType);
2784}
2785
Chris Lattner1eafdea2008-11-18 01:30:42 +00002786QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002787 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002788 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002789 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002790 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002791}
2792
Chris Lattner1eafdea2008-11-18 01:30:42 +00002793inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002794 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002795 // For conversion purposes, we ignore any qualifiers.
2796 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002797 QualType lhsType =
2798 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2799 QualType rhsType =
2800 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002801
Nate Begemanc5f0f652008-07-14 18:02:46 +00002802 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002803 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002804 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002805
Nate Begemanc5f0f652008-07-14 18:02:46 +00002806 // Handle the case of a vector & extvector type of the same size and element
2807 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002808 if (getLangOptions().LaxVectorConversions) {
2809 // FIXME: Should we warn here?
2810 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002811 if (const VectorType *RV = rhsType->getAsVectorType())
2812 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002813 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002814 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002815 }
2816 }
2817 }
2818
Nate Begemanc5f0f652008-07-14 18:02:46 +00002819 // If the lhs is an extended vector and the rhs is a scalar of the same type
2820 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002821 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002822 QualType eltType = V->getElementType();
2823
2824 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2825 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2826 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002827 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002828 return lhsType;
2829 }
2830 }
2831
Nate Begemanc5f0f652008-07-14 18:02:46 +00002832 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002833 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002834 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002835 QualType eltType = V->getElementType();
2836
2837 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2838 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2839 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002840 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002841 return rhsType;
2842 }
2843 }
2844
Chris Lattner4b009652007-07-25 00:24:17 +00002845 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002846 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002847 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002848 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002849 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002850}
2851
Chris Lattner4b009652007-07-25 00:24:17 +00002852inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002853 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002854{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002855 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002856 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002857
Steve Naroff8f708362007-08-24 19:07:16 +00002858 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002859
Chris Lattner4b009652007-07-25 00:24:17 +00002860 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002861 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002862 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002863}
2864
2865inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002866 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002867{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002868 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2869 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2870 return CheckVectorOperands(Loc, lex, rex);
2871 return InvalidOperands(Loc, lex, rex);
2872 }
Chris Lattner4b009652007-07-25 00:24:17 +00002873
Steve Naroff8f708362007-08-24 19:07:16 +00002874 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002875
Chris Lattner4b009652007-07-25 00:24:17 +00002876 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002877 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002878 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002879}
2880
2881inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002882 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002883{
2884 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002885 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002886
Steve Naroff8f708362007-08-24 19:07:16 +00002887 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002888
Chris Lattner4b009652007-07-25 00:24:17 +00002889 // handle the common case first (both operands are arithmetic).
2890 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002891 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002892
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002893 // Put any potential pointer into PExp
2894 Expr* PExp = lex, *IExp = rex;
2895 if (IExp->getType()->isPointerType())
2896 std::swap(PExp, IExp);
2897
2898 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2899 if (IExp->getType()->isIntegerType()) {
2900 // Check for arithmetic on pointers to incomplete types
2901 if (!PTy->getPointeeType()->isObjectType()) {
2902 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002903 if (getLangOptions().CPlusPlus) {
2904 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2905 << lex->getSourceRange() << rex->getSourceRange();
2906 return QualType();
2907 }
2908
2909 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002910 Diag(Loc, diag::ext_gnu_void_ptr)
2911 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002912 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002913 if (getLangOptions().CPlusPlus) {
2914 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2915 << lex->getType() << lex->getSourceRange();
2916 return QualType();
2917 }
2918
2919 // GNU extension: arithmetic on pointer to function
2920 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002921 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002922 } else {
2923 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2924 diag::err_typecheck_arithmetic_incomplete_type,
2925 lex->getSourceRange(), SourceRange(),
2926 lex->getType());
2927 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002928 }
2929 }
2930 return PExp->getType();
2931 }
2932 }
2933
Chris Lattner1eafdea2008-11-18 01:30:42 +00002934 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002935}
2936
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002937// C99 6.5.6
2938QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002939 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002940 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002941 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002942
Steve Naroff8f708362007-08-24 19:07:16 +00002943 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002944
Chris Lattnerf6da2912007-12-09 21:53:25 +00002945 // Enforce type constraints: C99 6.5.6p3.
2946
2947 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002948 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002949 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002950
2951 // Either ptr - int or ptr - ptr.
2952 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002953 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002954
Chris Lattnerf6da2912007-12-09 21:53:25 +00002955 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002956 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002957 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002958 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002959 Diag(Loc, diag::ext_gnu_void_ptr)
2960 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002961 } else if (lpointee->isFunctionType()) {
2962 if (getLangOptions().CPlusPlus) {
2963 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2964 << lex->getType() << lex->getSourceRange();
2965 return QualType();
2966 }
2967
2968 // GNU extension: arithmetic on pointer to function
2969 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2970 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002971 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002972 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002973 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002974 return QualType();
2975 }
2976 }
2977
2978 // The result type of a pointer-int computation is the pointer type.
2979 if (rex->getType()->isIntegerType())
2980 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002981
Chris Lattnerf6da2912007-12-09 21:53:25 +00002982 // Handle pointer-pointer subtractions.
2983 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002984 QualType rpointee = RHSPTy->getPointeeType();
2985
Chris Lattnerf6da2912007-12-09 21:53:25 +00002986 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002987 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002988 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002989 if (rpointee->isVoidType()) {
2990 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002991 Diag(Loc, diag::ext_gnu_void_ptr)
2992 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002993 } else if (rpointee->isFunctionType()) {
2994 if (getLangOptions().CPlusPlus) {
2995 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2996 << rex->getType() << rex->getSourceRange();
2997 return QualType();
2998 }
2999
3000 // GNU extension: arithmetic on pointer to function
3001 if (!lpointee->isFunctionType())
3002 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3003 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003004 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003005 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003006 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003007 return QualType();
3008 }
3009 }
3010
3011 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003012 if (!Context.typesAreCompatible(
3013 Context.getCanonicalType(lpointee).getUnqualifiedType(),
3014 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003015 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003016 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003017 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003018 return QualType();
3019 }
3020
3021 return Context.getPointerDiffType();
3022 }
3023 }
3024
Chris Lattner1eafdea2008-11-18 01:30:42 +00003025 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003026}
3027
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003028// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003029QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003030 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003031 // C99 6.5.7p2: Each of the operands shall have integer type.
3032 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003033 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003034
Chris Lattner2c8bff72007-12-12 05:47:28 +00003035 // Shifts don't perform usual arithmetic conversions, they just do integer
3036 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003037 if (!isCompAssign)
3038 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003039 UsualUnaryConversions(rex);
3040
3041 // "The type of the result is that of the promoted left operand."
3042 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003043}
3044
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003045// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003046QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003047 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003048 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003049 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003050
Chris Lattner254f3bc2007-08-26 01:18:55 +00003051 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003052 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3053 UsualArithmeticConversions(lex, rex);
3054 else {
3055 UsualUnaryConversions(lex);
3056 UsualUnaryConversions(rex);
3057 }
Chris Lattner4b009652007-07-25 00:24:17 +00003058 QualType lType = lex->getType();
3059 QualType rType = rex->getType();
3060
Ted Kremenek486509e2007-10-29 17:13:39 +00003061 // For non-floating point types, check for self-comparisons of the form
3062 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3063 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003064 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003065 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3066 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003067 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003068 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003069 }
3070
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003071 // The result of comparisons is 'bool' in C++, 'int' in C.
3072 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3073
Chris Lattner254f3bc2007-08-26 01:18:55 +00003074 if (isRelational) {
3075 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003076 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003077 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003078 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003079 if (lType->isFloatingType()) {
3080 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003081 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003082 }
3083
Chris Lattner254f3bc2007-08-26 01:18:55 +00003084 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003085 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003086 }
Chris Lattner4b009652007-07-25 00:24:17 +00003087
Chris Lattner22be8422007-08-26 01:10:14 +00003088 bool LHSIsNull = lex->isNullPointerConstant(Context);
3089 bool RHSIsNull = rex->isNullPointerConstant(Context);
3090
Chris Lattner254f3bc2007-08-26 01:18:55 +00003091 // All of the following pointer related warnings are GCC extensions, except
3092 // when handling null pointer constants. One day, we can consider making them
3093 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003094 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003095 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003096 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003097 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003098 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00003099
Steve Naroff3b435622007-11-13 14:57:38 +00003100 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003101 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3102 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003103 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003104 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003105 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003106 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003107 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003108 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003109 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003110 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003111 // Handle block pointer types.
3112 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3113 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3114 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3115
3116 if (!LHSIsNull && !RHSIsNull &&
3117 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003118 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003119 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003120 }
3121 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003122 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003123 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003124 // Allow block pointers to be compared with null pointer constants.
3125 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3126 (lType->isPointerType() && rType->isBlockPointerType())) {
3127 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003128 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003129 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003130 }
3131 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003132 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003133 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003134
Steve Naroff936c4362008-06-03 14:04:54 +00003135 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003136 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003137 const PointerType *LPT = lType->getAsPointerType();
3138 const PointerType *RPT = rType->getAsPointerType();
3139 bool LPtrToVoid = LPT ?
3140 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3141 bool RPtrToVoid = RPT ?
3142 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3143
3144 if (!LPtrToVoid && !RPtrToVoid &&
3145 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003146 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003147 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003148 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003149 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003150 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003151 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003152 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003153 }
Steve Naroff936c4362008-06-03 14:04:54 +00003154 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3155 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003156 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003157 } else {
3158 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003159 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003160 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003161 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003162 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003163 }
Steve Naroff936c4362008-06-03 14:04:54 +00003164 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003165 }
Steve Naroff936c4362008-06-03 14:04:54 +00003166 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3167 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003168 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003169 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003170 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003171 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003172 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003173 }
Steve Naroff936c4362008-06-03 14:04:54 +00003174 if (lType->isIntegerType() &&
3175 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003176 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003177 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003178 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003179 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003180 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003181 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003182 // Handle block pointers.
3183 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3184 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003185 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003186 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003187 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003188 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003189 }
3190 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3191 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003192 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003193 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003194 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003195 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003196 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003197 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003198}
3199
Nate Begemanc5f0f652008-07-14 18:02:46 +00003200/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3201/// operates on extended vector types. Instead of producing an IntTy result,
3202/// like a scalar comparison, a vector comparison produces a vector of integer
3203/// types.
3204QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003205 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003206 bool isRelational) {
3207 // Check to make sure we're operating on vectors of the same type and width,
3208 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003209 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003210 if (vType.isNull())
3211 return vType;
3212
3213 QualType lType = lex->getType();
3214 QualType rType = rex->getType();
3215
3216 // For non-floating point types, check for self-comparisons of the form
3217 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3218 // often indicate logic errors in the program.
3219 if (!lType->isFloatingType()) {
3220 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3221 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3222 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003223 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003224 }
3225
3226 // Check for comparisons of floating point operands using != and ==.
3227 if (!isRelational && lType->isFloatingType()) {
3228 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003229 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003230 }
3231
3232 // Return the type for the comparison, which is the same as vector type for
3233 // integer vectors, or an integer type of identical size and number of
3234 // elements for floating point vectors.
3235 if (lType->isIntegerType())
3236 return lType;
3237
3238 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003239 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003240 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003241 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003242 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3243 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3244
3245 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3246 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003247 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3248}
3249
Chris Lattner4b009652007-07-25 00:24:17 +00003250inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003251 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003252{
3253 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003254 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003255
Steve Naroff8f708362007-08-24 19:07:16 +00003256 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003257
3258 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003259 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003260 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003261}
3262
3263inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003264 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003265{
3266 UsualUnaryConversions(lex);
3267 UsualUnaryConversions(rex);
3268
Eli Friedmanbea3f842008-05-13 20:16:47 +00003269 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003270 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003271 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003272}
3273
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003274/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3275/// is a read-only property; return true if so. A readonly property expression
3276/// depends on various declarations and thus must be treated specially.
3277///
3278static bool IsReadonlyProperty(Expr *E, Sema &S)
3279{
3280 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3281 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3282 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3283 QualType BaseType = PropExpr->getBase()->getType();
3284 if (const PointerType *PTy = BaseType->getAsPointerType())
3285 if (const ObjCInterfaceType *IFTy =
3286 PTy->getPointeeType()->getAsObjCInterfaceType())
3287 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3288 if (S.isPropertyReadonly(PDecl, IFace))
3289 return true;
3290 }
3291 }
3292 return false;
3293}
3294
Chris Lattner4c2642c2008-11-18 01:22:49 +00003295/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3296/// emit an error and return true. If so, return false.
3297static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003298 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3299 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3300 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003301 if (IsLV == Expr::MLV_Valid)
3302 return false;
3303
3304 unsigned Diag = 0;
3305 bool NeedType = false;
3306 switch (IsLV) { // C99 6.5.16p2
3307 default: assert(0 && "Unknown result from isModifiableLvalue!");
3308 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003309 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003310 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3311 NeedType = true;
3312 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003313 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003314 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3315 NeedType = true;
3316 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003317 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003318 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3319 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003320 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003321 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3322 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003323 case Expr::MLV_IncompleteType:
3324 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003325 return S.DiagnoseIncompleteType(Loc, E->getType(),
3326 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3327 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003328 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003329 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3330 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003331 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003332 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3333 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003334 case Expr::MLV_ReadonlyProperty:
3335 Diag = diag::error_readonly_property_assignment;
3336 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003337 case Expr::MLV_NoSetterProperty:
3338 Diag = diag::error_nosetter_property_assignment;
3339 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003340 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003341
Chris Lattner4c2642c2008-11-18 01:22:49 +00003342 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003343 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003344 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003345 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003346 return true;
3347}
3348
3349
3350
3351// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003352QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3353 SourceLocation Loc,
3354 QualType CompoundType) {
3355 // Verify that LHS is a modifiable lvalue, and emit error if not.
3356 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003357 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003358
3359 QualType LHSType = LHS->getType();
3360 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003361
Chris Lattner005ed752008-01-04 18:04:52 +00003362 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003363 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003364 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003365 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003366 // Special case of NSObject attributes on c-style pointer types.
3367 if (ConvTy == IncompatiblePointer &&
3368 ((Context.isObjCNSObjectType(LHSType) &&
3369 Context.isObjCObjectPointerType(RHSType)) ||
3370 (Context.isObjCNSObjectType(RHSType) &&
3371 Context.isObjCObjectPointerType(LHSType))))
3372 ConvTy = Compatible;
3373
Chris Lattner34c85082008-08-21 18:04:13 +00003374 // If the RHS is a unary plus or minus, check to see if they = and + are
3375 // right next to each other. If so, the user may have typo'd "x =+ 4"
3376 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003377 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003378 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3379 RHSCheck = ICE->getSubExpr();
3380 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3381 if ((UO->getOpcode() == UnaryOperator::Plus ||
3382 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003383 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003384 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003385 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003386 Diag(Loc, diag::warn_not_compound_assign)
3387 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3388 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003389 }
3390 } else {
3391 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003392 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003393 }
Chris Lattner005ed752008-01-04 18:04:52 +00003394
Chris Lattner1eafdea2008-11-18 01:30:42 +00003395 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3396 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003397 return QualType();
3398
Chris Lattner4b009652007-07-25 00:24:17 +00003399 // C99 6.5.16p3: The type of an assignment expression is the type of the
3400 // left operand unless the left operand has qualified type, in which case
3401 // it is the unqualified version of the type of the left operand.
3402 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3403 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003404 // C++ 5.17p1: the type of the assignment expression is that of its left
3405 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003406 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003407}
3408
Chris Lattner1eafdea2008-11-18 01:30:42 +00003409// C99 6.5.17
3410QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3411 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003412
3413 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003414 DefaultFunctionArrayConversion(RHS);
3415 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003416}
3417
3418/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3419/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003420QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3421 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003422 QualType ResType = Op->getType();
3423 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003424
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003425 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3426 // Decrement of bool is not allowed.
3427 if (!isInc) {
3428 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3429 return QualType();
3430 }
3431 // Increment of bool sets it to true, but is deprecated.
3432 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3433 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003434 // OK!
3435 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3436 // C99 6.5.2.4p2, 6.5.6p2
3437 if (PT->getPointeeType()->isObjectType()) {
3438 // Pointer to object is ok!
3439 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003440 if (getLangOptions().CPlusPlus) {
3441 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3442 << Op->getSourceRange();
3443 return QualType();
3444 }
3445
3446 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003447 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003448 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003449 if (getLangOptions().CPlusPlus) {
3450 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3451 << Op->getType() << Op->getSourceRange();
3452 return QualType();
3453 }
3454
3455 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003456 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003457 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003458 } else {
3459 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3460 diag::err_typecheck_arithmetic_incomplete_type,
3461 Op->getSourceRange(), SourceRange(),
3462 ResType);
3463 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003464 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003465 } else if (ResType->isComplexType()) {
3466 // C99 does not support ++/-- on complex types, we allow as an extension.
3467 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003468 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003469 } else {
3470 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003471 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003472 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003473 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003474 // At this point, we know we have a real, complex or pointer type.
3475 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003476 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003477 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003478 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003479}
3480
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003481/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003482/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003483/// where the declaration is needed for type checking. We only need to
3484/// handle cases when the expression references a function designator
3485/// or is an lvalue. Here are some examples:
3486/// - &(x) => x
3487/// - &*****f => f for f a function designator.
3488/// - &s.xx => s
3489/// - &s.zz[1].yy -> s, if zz is an array
3490/// - *(x + 1) -> x, if x is an array
3491/// - &"123"[2] -> 0
3492/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003493static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003494 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003495 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003496 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003497 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003498 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003499 // Fields cannot be declared with a 'register' storage class.
3500 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003501 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003502 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003503 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003504 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003505 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003506
Douglas Gregord2baafd2008-10-21 16:13:35 +00003507 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003508 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003509 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003510 return 0;
3511 else
3512 return VD;
3513 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003514 case Stmt::UnaryOperatorClass: {
3515 UnaryOperator *UO = cast<UnaryOperator>(E);
3516
3517 switch(UO->getOpcode()) {
3518 case UnaryOperator::Deref: {
3519 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003520 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3521 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3522 if (!VD || VD->getType()->isPointerType())
3523 return 0;
3524 return VD;
3525 }
3526 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003527 }
3528 case UnaryOperator::Real:
3529 case UnaryOperator::Imag:
3530 case UnaryOperator::Extension:
3531 return getPrimaryDecl(UO->getSubExpr());
3532 default:
3533 return 0;
3534 }
3535 }
3536 case Stmt::BinaryOperatorClass: {
3537 BinaryOperator *BO = cast<BinaryOperator>(E);
3538
3539 // Handle cases involving pointer arithmetic. The result of an
3540 // Assign or AddAssign is not an lvalue so they can be ignored.
3541
3542 // (x + n) or (n + x) => x
3543 if (BO->getOpcode() == BinaryOperator::Add) {
3544 if (BO->getLHS()->getType()->isPointerType()) {
3545 return getPrimaryDecl(BO->getLHS());
3546 } else if (BO->getRHS()->getType()->isPointerType()) {
3547 return getPrimaryDecl(BO->getRHS());
3548 }
3549 }
3550
3551 return 0;
3552 }
Chris Lattner4b009652007-07-25 00:24:17 +00003553 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003554 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003555 case Stmt::ImplicitCastExprClass:
3556 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003557 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003558 default:
3559 return 0;
3560 }
3561}
3562
3563/// CheckAddressOfOperand - The operand of & must be either a function
3564/// designator or an lvalue designating an object. If it is an lvalue, the
3565/// object cannot be declared with storage class register or be a bit field.
3566/// Note: The usual conversions are *not* applied to the operand of the &
3567/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003568/// In C++, the operand might be an overloaded function name, in which case
3569/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003570QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003571 if (op->isTypeDependent())
3572 return Context.DependentTy;
3573
Steve Naroff9c6c3592008-01-13 17:10:08 +00003574 if (getLangOptions().C99) {
3575 // Implement C99-only parts of addressof rules.
3576 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3577 if (uOp->getOpcode() == UnaryOperator::Deref)
3578 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3579 // (assuming the deref expression is valid).
3580 return uOp->getSubExpr()->getType();
3581 }
3582 // Technically, there should be a check for array subscript
3583 // expressions here, but the result of one is always an lvalue anyway.
3584 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003585 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003586 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003587
Chris Lattner4b009652007-07-25 00:24:17 +00003588 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003589 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3590 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003591 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3592 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003593 return QualType();
3594 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003595 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003596 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3597 if (Field->isBitField()) {
3598 Diag(OpLoc, diag::err_typecheck_address_of)
3599 << "bit-field" << op->getSourceRange();
3600 return QualType();
3601 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003602 }
3603 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003604 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3605 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003606 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003607 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003608 return QualType();
3609 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003610 // We have an lvalue with a decl. Make sure the decl is not declared
3611 // with the register storage-class specifier.
3612 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3613 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003614 Diag(OpLoc, diag::err_typecheck_address_of)
3615 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003616 return QualType();
3617 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003618 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003619 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003620 } else if (isa<FieldDecl>(dcl)) {
3621 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003622 // Could be a pointer to member, though, if there is an explicit
3623 // scope qualifier for the class.
3624 if (isa<QualifiedDeclRefExpr>(op)) {
3625 DeclContext *Ctx = dcl->getDeclContext();
3626 if (Ctx && Ctx->isRecord())
3627 return Context.getMemberPointerType(op->getType(),
3628 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3629 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003630 } else if (isa<FunctionDecl>(dcl)) {
3631 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003632 // As above.
3633 if (isa<QualifiedDeclRefExpr>(op)) {
3634 DeclContext *Ctx = dcl->getDeclContext();
3635 if (Ctx && Ctx->isRecord())
3636 return Context.getMemberPointerType(op->getType(),
3637 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3638 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003639 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003640 else
Chris Lattner4b009652007-07-25 00:24:17 +00003641 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003642 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003643
Chris Lattner4b009652007-07-25 00:24:17 +00003644 // If the operand has type "type", the result has type "pointer to type".
3645 return Context.getPointerType(op->getType());
3646}
3647
Chris Lattnerda5c0872008-11-23 09:13:29 +00003648QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3649 UsualUnaryConversions(Op);
3650 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003651
Chris Lattnerda5c0872008-11-23 09:13:29 +00003652 // Note that per both C89 and C99, this is always legal, even if ptype is an
3653 // incomplete type or void. It would be possible to warn about dereferencing
3654 // a void pointer, but it's completely well-defined, and such a warning is
3655 // unlikely to catch any mistakes.
3656 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003657 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003658
Chris Lattner77d52da2008-11-20 06:06:08 +00003659 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003660 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003661 return QualType();
3662}
3663
3664static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3665 tok::TokenKind Kind) {
3666 BinaryOperator::Opcode Opc;
3667 switch (Kind) {
3668 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003669 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3670 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003671 case tok::star: Opc = BinaryOperator::Mul; break;
3672 case tok::slash: Opc = BinaryOperator::Div; break;
3673 case tok::percent: Opc = BinaryOperator::Rem; break;
3674 case tok::plus: Opc = BinaryOperator::Add; break;
3675 case tok::minus: Opc = BinaryOperator::Sub; break;
3676 case tok::lessless: Opc = BinaryOperator::Shl; break;
3677 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3678 case tok::lessequal: Opc = BinaryOperator::LE; break;
3679 case tok::less: Opc = BinaryOperator::LT; break;
3680 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3681 case tok::greater: Opc = BinaryOperator::GT; break;
3682 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3683 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3684 case tok::amp: Opc = BinaryOperator::And; break;
3685 case tok::caret: Opc = BinaryOperator::Xor; break;
3686 case tok::pipe: Opc = BinaryOperator::Or; break;
3687 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3688 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3689 case tok::equal: Opc = BinaryOperator::Assign; break;
3690 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3691 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3692 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3693 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3694 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3695 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3696 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3697 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3698 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3699 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3700 case tok::comma: Opc = BinaryOperator::Comma; break;
3701 }
3702 return Opc;
3703}
3704
3705static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3706 tok::TokenKind Kind) {
3707 UnaryOperator::Opcode Opc;
3708 switch (Kind) {
3709 default: assert(0 && "Unknown unary op!");
3710 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3711 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3712 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3713 case tok::star: Opc = UnaryOperator::Deref; break;
3714 case tok::plus: Opc = UnaryOperator::Plus; break;
3715 case tok::minus: Opc = UnaryOperator::Minus; break;
3716 case tok::tilde: Opc = UnaryOperator::Not; break;
3717 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003718 case tok::kw___real: Opc = UnaryOperator::Real; break;
3719 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3720 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3721 }
3722 return Opc;
3723}
3724
Douglas Gregord7f915e2008-11-06 23:29:22 +00003725/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3726/// operator @p Opc at location @c TokLoc. This routine only supports
3727/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003728Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3729 unsigned Op,
3730 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003731 QualType ResultTy; // Result type of the binary operator.
3732 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3733 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3734
3735 switch (Opc) {
3736 default:
3737 assert(0 && "Unknown binary expr!");
3738 case BinaryOperator::Assign:
3739 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3740 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003741 case BinaryOperator::PtrMemD:
3742 case BinaryOperator::PtrMemI:
3743 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3744 Opc == BinaryOperator::PtrMemI);
3745 break;
3746 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003747 case BinaryOperator::Div:
3748 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3749 break;
3750 case BinaryOperator::Rem:
3751 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3752 break;
3753 case BinaryOperator::Add:
3754 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3755 break;
3756 case BinaryOperator::Sub:
3757 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3758 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003759 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003760 case BinaryOperator::Shr:
3761 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3762 break;
3763 case BinaryOperator::LE:
3764 case BinaryOperator::LT:
3765 case BinaryOperator::GE:
3766 case BinaryOperator::GT:
3767 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3768 break;
3769 case BinaryOperator::EQ:
3770 case BinaryOperator::NE:
3771 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3772 break;
3773 case BinaryOperator::And:
3774 case BinaryOperator::Xor:
3775 case BinaryOperator::Or:
3776 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3777 break;
3778 case BinaryOperator::LAnd:
3779 case BinaryOperator::LOr:
3780 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3781 break;
3782 case BinaryOperator::MulAssign:
3783 case BinaryOperator::DivAssign:
3784 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3785 if (!CompTy.isNull())
3786 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3787 break;
3788 case BinaryOperator::RemAssign:
3789 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3790 if (!CompTy.isNull())
3791 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3792 break;
3793 case BinaryOperator::AddAssign:
3794 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3795 if (!CompTy.isNull())
3796 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3797 break;
3798 case BinaryOperator::SubAssign:
3799 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3800 if (!CompTy.isNull())
3801 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3802 break;
3803 case BinaryOperator::ShlAssign:
3804 case BinaryOperator::ShrAssign:
3805 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3806 if (!CompTy.isNull())
3807 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3808 break;
3809 case BinaryOperator::AndAssign:
3810 case BinaryOperator::XorAssign:
3811 case BinaryOperator::OrAssign:
3812 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3813 if (!CompTy.isNull())
3814 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3815 break;
3816 case BinaryOperator::Comma:
3817 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3818 break;
3819 }
3820 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003821 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003822 if (CompTy.isNull())
3823 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3824 else
3825 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003826 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003827}
3828
Chris Lattner4b009652007-07-25 00:24:17 +00003829// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003830Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3831 tok::TokenKind Kind,
3832 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003833 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003834 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003835
Steve Naroff87d58b42007-09-16 03:34:24 +00003836 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3837 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003838
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003839 // If either expression is type-dependent, just build the AST.
3840 // FIXME: We'll need to perform some caching of the result of name
3841 // lookup for operator+.
3842 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003843 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3844 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003845 Context.DependentTy,
3846 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003847 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003848 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3849 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003850 }
3851
Sebastian Redl95216a62009-02-07 00:15:38 +00003852 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003853 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3854 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003855 // If this is one of the assignment operators, we only perform
3856 // overload resolution if the left-hand side is a class or
3857 // enumeration type (C++ [expr.ass]p3).
3858 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3859 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3860 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3861 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003862
Douglas Gregord7f915e2008-11-06 23:29:22 +00003863 // Determine which overloaded operator we're dealing with.
3864 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003865 // Overloading .* is not possible.
3866 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003867 OO_Star, OO_Slash, OO_Percent,
3868 OO_Plus, OO_Minus,
3869 OO_LessLess, OO_GreaterGreater,
3870 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3871 OO_EqualEqual, OO_ExclaimEqual,
3872 OO_Amp,
3873 OO_Caret,
3874 OO_Pipe,
3875 OO_AmpAmp,
3876 OO_PipePipe,
3877 OO_Equal, OO_StarEqual,
3878 OO_SlashEqual, OO_PercentEqual,
3879 OO_PlusEqual, OO_MinusEqual,
3880 OO_LessLessEqual, OO_GreaterGreaterEqual,
3881 OO_AmpEqual, OO_CaretEqual,
3882 OO_PipeEqual,
3883 OO_Comma
3884 };
3885 OverloadedOperatorKind OverOp = OverOps[Opc];
3886
Douglas Gregor5ed15042008-11-18 23:14:02 +00003887 // Add the appropriate overloaded operators (C++ [over.match.oper])
3888 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003889 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003890 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003891 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3892 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003893
3894 // Perform overload resolution.
3895 OverloadCandidateSet::iterator Best;
3896 switch (BestViableFunction(CandidateSet, Best)) {
3897 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003898 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003899 FunctionDecl *FnDecl = Best->Function;
3900
Douglas Gregor70d26122008-11-12 17:17:38 +00003901 if (FnDecl) {
3902 // We matched an overloaded operator. Build a call to that
3903 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003904
Douglas Gregor70d26122008-11-12 17:17:38 +00003905 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3907 if (PerformObjectArgumentInitialization(lhs, Method) ||
3908 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3909 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003910 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003911 } else {
3912 // Convert the arguments.
3913 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3914 "passing") ||
3915 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3916 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003917 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003918 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003919
Douglas Gregor70d26122008-11-12 17:17:38 +00003920 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003921 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003922 = FnDecl->getType()->getAsFunctionType()->getResultType();
3923 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003924
Douglas Gregor70d26122008-11-12 17:17:38 +00003925 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003926 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3927 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003928 UsualUnaryConversions(FnExpr);
3929
Ted Kremenek362abcd2009-02-09 20:51:47 +00003930 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003931 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003932 } else {
3933 // We matched a built-in operator. Convert the arguments, then
3934 // break out so that we will build the appropriate built-in
3935 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003936 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3937 Best->Conversions[0], "passing") ||
3938 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3939 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003940 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003941
3942 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003943 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003944 }
3945
3946 case OR_No_Viable_Function:
3947 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003948 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003949 break;
3950
3951 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003952 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3953 << BinaryOperator::getOpcodeStr(Opc)
3954 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003955 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003956 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00003957
3958 case OR_Deleted:
3959 Diag(TokLoc, diag::err_ovl_deleted_oper)
3960 << Best->Function->isDeleted()
3961 << BinaryOperator::getOpcodeStr(Opc)
3962 << lhs->getSourceRange() << rhs->getSourceRange();
3963 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3964 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003965 }
3966
Douglas Gregor70d26122008-11-12 17:17:38 +00003967 // Either we found no viable overloaded operator or we matched a
3968 // built-in operator. In either case, fall through to trying to
3969 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003970 }
3971
Douglas Gregord7f915e2008-11-06 23:29:22 +00003972 // Build a built-in binary operation.
3973 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003974}
3975
3976// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003977Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3978 tok::TokenKind Op, ExprArg input) {
3979 // FIXME: Input is modified later, but smart pointer not reassigned.
3980 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003981 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003982
3983 if (getLangOptions().CPlusPlus &&
3984 (Input->getType()->isRecordType()
3985 || Input->getType()->isEnumeralType())) {
3986 // Determine which overloaded operator we're dealing with.
3987 static const OverloadedOperatorKind OverOps[] = {
3988 OO_None, OO_None,
3989 OO_PlusPlus, OO_MinusMinus,
3990 OO_Amp, OO_Star,
3991 OO_Plus, OO_Minus,
3992 OO_Tilde, OO_Exclaim,
3993 OO_None, OO_None,
3994 OO_None,
3995 OO_None
3996 };
3997 OverloadedOperatorKind OverOp = OverOps[Opc];
3998
3999 // Add the appropriate overloaded operators (C++ [over.match.oper])
4000 // to the candidate set.
4001 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00004002 if (OverOp != OO_None &&
4003 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4004 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004005
4006 // Perform overload resolution.
4007 OverloadCandidateSet::iterator Best;
4008 switch (BestViableFunction(CandidateSet, Best)) {
4009 case OR_Success: {
4010 // We found a built-in operator or an overloaded operator.
4011 FunctionDecl *FnDecl = Best->Function;
4012
4013 if (FnDecl) {
4014 // We matched an overloaded operator. Build a call to that
4015 // operator.
4016
4017 // Convert the arguments.
4018 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4019 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004020 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004021 } else {
4022 // Convert the arguments.
4023 if (PerformCopyInitialization(Input,
4024 FnDecl->getParamDecl(0)->getType(),
4025 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004026 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004027 }
4028
4029 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004030 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004031 = FnDecl->getType()->getAsFunctionType()->getResultType();
4032 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004033
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004034 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00004035 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4036 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004037 UsualUnaryConversions(FnExpr);
4038
Sebastian Redl8b769972009-01-19 00:08:26 +00004039 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00004040 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00004041 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004042 } else {
4043 // We matched a built-in operator. Convert the arguments, then
4044 // break out so that we will build the appropriate built-in
4045 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004046 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4047 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004048 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004049
4050 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004051 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004052 }
4053
4054 case OR_No_Viable_Function:
4055 // No viable function; fall through to handling this as a
4056 // built-in operator, which will produce an error message for us.
4057 break;
4058
4059 case OR_Ambiguous:
4060 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4061 << UnaryOperator::getOpcodeStr(Opc)
4062 << Input->getSourceRange();
4063 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004064 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004065
4066 case OR_Deleted:
4067 Diag(OpLoc, diag::err_ovl_deleted_oper)
4068 << Best->Function->isDeleted()
4069 << UnaryOperator::getOpcodeStr(Opc)
4070 << Input->getSourceRange();
4071 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4072 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004073 }
4074
4075 // Either we found no viable overloaded operator or we matched a
4076 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004077 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004078 }
4079
Chris Lattner4b009652007-07-25 00:24:17 +00004080 QualType resultType;
4081 switch (Opc) {
4082 default:
4083 assert(0 && "Unimplemented unary expr!");
4084 case UnaryOperator::PreInc:
4085 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004086 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4087 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004088 break;
4089 case UnaryOperator::AddrOf:
4090 resultType = CheckAddressOfOperand(Input, OpLoc);
4091 break;
4092 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004093 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004094 resultType = CheckIndirectionOperand(Input, OpLoc);
4095 break;
4096 case UnaryOperator::Plus:
4097 case UnaryOperator::Minus:
4098 UsualUnaryConversions(Input);
4099 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004100 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4101 break;
4102 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4103 resultType->isEnumeralType())
4104 break;
4105 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4106 Opc == UnaryOperator::Plus &&
4107 resultType->isPointerType())
4108 break;
4109
Sebastian Redl8b769972009-01-19 00:08:26 +00004110 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4111 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004112 case UnaryOperator::Not: // bitwise complement
4113 UsualUnaryConversions(Input);
4114 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004115 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4116 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4117 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004118 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004119 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004120 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004121 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4122 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004123 break;
4124 case UnaryOperator::LNot: // logical negation
4125 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4126 DefaultFunctionArrayConversion(Input);
4127 resultType = Input->getType();
4128 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004129 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4130 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004131 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004132 // In C++, it's bool. C++ 5.3.1p8
4133 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004134 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004135 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004136 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004137 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004138 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004139 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004140 resultType = Input->getType();
4141 break;
4142 }
4143 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004144 return ExprError();
4145 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004146 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004147}
4148
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004149/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4150Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004151 SourceLocation LabLoc,
4152 IdentifierInfo *LabelII) {
4153 // Look up the record for this label identifier.
4154 LabelStmt *&LabelDecl = LabelMap[LabelII];
4155
Daniel Dunbar879788d2008-08-04 16:51:22 +00004156 // If we haven't seen this label yet, create a forward reference. It
4157 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004158 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004159 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004160
4161 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004162 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4163 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004164}
4165
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004166Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004167 SourceLocation RPLoc) { // "({..})"
4168 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4169 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4170 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4171
Eli Friedmanbc941e12009-01-24 23:09:00 +00004172 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4173 if (isFileScope) {
4174 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4175 }
4176
Chris Lattner4b009652007-07-25 00:24:17 +00004177 // FIXME: there are a variety of strange constraints to enforce here, for
4178 // example, it is not possible to goto into a stmt expression apparently.
4179 // More semantic analysis is needed.
4180
4181 // FIXME: the last statement in the compount stmt has its value used. We
4182 // should not warn about it being unused.
4183
4184 // If there are sub stmts in the compound stmt, take the type of the last one
4185 // as the type of the stmtexpr.
4186 QualType Ty = Context.VoidTy;
4187
Chris Lattner200964f2008-07-26 19:51:01 +00004188 if (!Compound->body_empty()) {
4189 Stmt *LastStmt = Compound->body_back();
4190 // If LastStmt is a label, skip down through into the body.
4191 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4192 LastStmt = Label->getSubStmt();
4193
4194 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004195 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004196 }
Chris Lattner4b009652007-07-25 00:24:17 +00004197
Steve Naroff774e4152009-01-21 00:14:39 +00004198 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004199}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004200
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004201Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4202 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004203 SourceLocation TypeLoc,
4204 TypeTy *argty,
4205 OffsetOfComponent *CompPtr,
4206 unsigned NumComponents,
4207 SourceLocation RPLoc) {
4208 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4209 assert(!ArgTy.isNull() && "Missing type argument!");
4210
4211 // We must have at least one component that refers to the type, and the first
4212 // one is known to be a field designator. Verify that the ArgTy represents
4213 // a struct/union/class.
4214 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004215 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004216
4217 // Otherwise, create a compound literal expression as the base, and
4218 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004219 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004220 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004221 IList->setType(ArgTy);
4222 Expr *Res =
4223 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4224
Chris Lattnerb37522e2007-08-31 21:49:13 +00004225 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4226 // GCC extension, diagnose them.
4227 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004228 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4229 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004230
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004231 for (unsigned i = 0; i != NumComponents; ++i) {
4232 const OffsetOfComponent &OC = CompPtr[i];
4233 if (OC.isBrackets) {
4234 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004235 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004236 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004237 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004238 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004239 }
4240
Chris Lattner2af6a802007-08-30 17:59:59 +00004241 // FIXME: C++: Verify that operator[] isn't overloaded.
4242
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004243 // C99 6.5.2.1p1
4244 Expr *Idx = static_cast<Expr*>(OC.U.E);
4245 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004246 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4247 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004248
Steve Naroff774e4152009-01-21 00:14:39 +00004249 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4250 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004251 continue;
4252 }
4253
4254 const RecordType *RC = Res->getType()->getAsRecordType();
4255 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004256 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004257 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004258 }
4259
4260 // Get the decl corresponding to this.
4261 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004262 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004263 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4264 LookupMemberName)
4265 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004266 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004267 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4268 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004269
4270 // FIXME: C++: Verify that MemberDecl isn't a static field.
4271 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004272 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4273 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004274 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4275 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004276 }
4277
Steve Naroff774e4152009-01-21 00:14:39 +00004278 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4279 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004280}
4281
4282
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004283Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004284 TypeTy *arg1, TypeTy *arg2,
4285 SourceLocation RPLoc) {
4286 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4287 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4288
4289 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4290
Steve Naroff774e4152009-01-21 00:14:39 +00004291 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4292 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004293}
4294
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004295Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004296 ExprTy *expr1, ExprTy *expr2,
4297 SourceLocation RPLoc) {
4298 Expr *CondExpr = static_cast<Expr*>(cond);
4299 Expr *LHSExpr = static_cast<Expr*>(expr1);
4300 Expr *RHSExpr = static_cast<Expr*>(expr2);
4301
4302 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4303
4304 // The conditional expression is required to be a constant expression.
4305 llvm::APSInt condEval(32);
4306 SourceLocation ExpLoc;
4307 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004308 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4309 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004310
4311 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4312 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4313 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004314 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4315 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004316}
4317
Steve Naroff52a81c02008-09-03 18:15:37 +00004318//===----------------------------------------------------------------------===//
4319// Clang Extensions.
4320//===----------------------------------------------------------------------===//
4321
4322/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004323void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004324 // Analyze block parameters.
4325 BlockSemaInfo *BSI = new BlockSemaInfo();
4326
4327 // Add BSI to CurBlock.
4328 BSI->PrevBlockInfo = CurBlock;
4329 CurBlock = BSI;
4330
4331 BSI->ReturnType = 0;
4332 BSI->TheScope = BlockScope;
4333
Steve Naroff52059382008-10-10 01:28:17 +00004334 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004335 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004336}
4337
Mike Stumpc1fddff2009-02-04 22:31:32 +00004338void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4339 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4340
4341 if (ParamInfo.getNumTypeObjects() == 0
4342 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4343 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4344
4345 // The type is entirely optional as well, if none, use DependentTy.
4346 if (T.isNull())
4347 T = Context.DependentTy;
4348
4349 // The parameter list is optional, if there was none, assume ().
4350 if (!T->isFunctionType())
4351 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4352
4353 CurBlock->hasPrototype = true;
4354 CurBlock->isVariadic = false;
4355 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4356 .getTypePtr();
4357
4358 if (!RetTy->isDependentType())
4359 CurBlock->ReturnType = RetTy;
4360 return;
4361 }
4362
Steve Naroff52a81c02008-09-03 18:15:37 +00004363 // Analyze arguments to block.
4364 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4365 "Not a function declarator!");
4366 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004367
Steve Naroff52059382008-10-10 01:28:17 +00004368 CurBlock->hasPrototype = FTI.hasPrototype;
4369 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004370
4371 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4372 // no arguments, not a function that takes a single void argument.
4373 if (FTI.hasPrototype &&
4374 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4375 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4376 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4377 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004378 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004379 } else if (FTI.hasPrototype) {
4380 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004381 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4382 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004383 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4384
4385 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4386 .getTypePtr();
4387
4388 if (!RetTy->isDependentType())
4389 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004390 }
Steve Naroff52059382008-10-10 01:28:17 +00004391 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4392
4393 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4394 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4395 // If this has an identifier, add it to the scope stack.
4396 if ((*AI)->getIdentifier())
4397 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004398}
4399
4400/// ActOnBlockError - If there is an error parsing a block, this callback
4401/// is invoked to pop the information about the block from the action impl.
4402void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4403 // Ensure that CurBlock is deleted.
4404 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4405
4406 // Pop off CurBlock, handle nested blocks.
4407 CurBlock = CurBlock->PrevBlockInfo;
4408
4409 // FIXME: Delete the ParmVarDecl objects as well???
4410
4411}
4412
4413/// ActOnBlockStmtExpr - This is called when the body of a block statement
4414/// literal was successfully completed. ^(int x){...}
4415Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4416 Scope *CurScope) {
4417 // Ensure that CurBlock is deleted.
4418 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004419 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004420
Steve Naroff52059382008-10-10 01:28:17 +00004421 PopDeclContext();
4422
Steve Naroff52a81c02008-09-03 18:15:37 +00004423 // Pop off CurBlock, handle nested blocks.
4424 CurBlock = CurBlock->PrevBlockInfo;
4425
4426 QualType RetTy = Context.VoidTy;
4427 if (BSI->ReturnType)
4428 RetTy = QualType(BSI->ReturnType, 0);
4429
4430 llvm::SmallVector<QualType, 8> ArgTypes;
4431 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4432 ArgTypes.push_back(BSI->Params[i]->getType());
4433
4434 QualType BlockTy;
4435 if (!BSI->hasPrototype)
4436 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4437 else
4438 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004439 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004440
4441 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004442
Steve Naroff95029d92008-10-08 18:44:00 +00004443 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004444 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004445}
4446
Anders Carlsson36760332007-10-15 20:28:48 +00004447Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4448 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004449 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004450 Expr *E = static_cast<Expr*>(expr);
4451 QualType T = QualType::getFromOpaquePtr(type);
4452
4453 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004454
4455 // Get the va_list type
4456 QualType VaListType = Context.getBuiltinVaListType();
4457 // Deal with implicit array decay; for example, on x86-64,
4458 // va_list is an array, but it's supposed to decay to
4459 // a pointer for va_arg.
4460 if (VaListType->isArrayType())
4461 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004462 // Make sure the input expression also decays appropriately.
4463 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004464
4465 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004466 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004467 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004468 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004469
4470 // FIXME: Warn if a non-POD type is passed in.
4471
Steve Naroff774e4152009-01-21 00:14:39 +00004472 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004473}
4474
Douglas Gregorad4b3792008-11-29 04:51:27 +00004475Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4476 // The type of __null will be int or long, depending on the size of
4477 // pointers on the target.
4478 QualType Ty;
4479 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4480 Ty = Context.IntTy;
4481 else
4482 Ty = Context.LongTy;
4483
Steve Naroff774e4152009-01-21 00:14:39 +00004484 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004485}
4486
Chris Lattner005ed752008-01-04 18:04:52 +00004487bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4488 SourceLocation Loc,
4489 QualType DstType, QualType SrcType,
4490 Expr *SrcExpr, const char *Flavor) {
4491 // Decode the result (notice that AST's are still created for extensions).
4492 bool isInvalid = false;
4493 unsigned DiagKind;
4494 switch (ConvTy) {
4495 default: assert(0 && "Unknown conversion type");
4496 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004497 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004498 DiagKind = diag::ext_typecheck_convert_pointer_int;
4499 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004500 case IntToPointer:
4501 DiagKind = diag::ext_typecheck_convert_int_pointer;
4502 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004503 case IncompatiblePointer:
4504 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4505 break;
4506 case FunctionVoidPointer:
4507 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4508 break;
4509 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004510 // If the qualifiers lost were because we were applying the
4511 // (deprecated) C++ conversion from a string literal to a char*
4512 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4513 // Ideally, this check would be performed in
4514 // CheckPointerTypesForAssignment. However, that would require a
4515 // bit of refactoring (so that the second argument is an
4516 // expression, rather than a type), which should be done as part
4517 // of a larger effort to fix CheckPointerTypesForAssignment for
4518 // C++ semantics.
4519 if (getLangOptions().CPlusPlus &&
4520 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4521 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004522 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4523 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004524 case IntToBlockPointer:
4525 DiagKind = diag::err_int_to_block_pointer;
4526 break;
4527 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004528 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004529 break;
Steve Naroff19608432008-10-14 22:18:38 +00004530 case IncompatibleObjCQualifiedId:
4531 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4532 // it can give a more specific diagnostic.
4533 DiagKind = diag::warn_incompatible_qualified_id;
4534 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004535 case IncompatibleVectors:
4536 DiagKind = diag::warn_incompatible_vectors;
4537 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004538 case Incompatible:
4539 DiagKind = diag::err_typecheck_convert_incompatible;
4540 isInvalid = true;
4541 break;
4542 }
4543
Chris Lattner271d4c22008-11-24 05:29:24 +00004544 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4545 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004546 return isInvalid;
4547}
Anders Carlssond5201b92008-11-30 19:50:32 +00004548
4549bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4550{
4551 Expr::EvalResult EvalResult;
4552
4553 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4554 EvalResult.HasSideEffects) {
4555 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4556
4557 if (EvalResult.Diag) {
4558 // We only show the note if it's not the usual "invalid subexpression"
4559 // or if it's actually in a subexpression.
4560 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4561 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4562 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4563 }
4564
4565 return true;
4566 }
4567
4568 if (EvalResult.Diag) {
4569 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4570 E->getSourceRange();
4571
4572 // Print the reason it's not a constant.
4573 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4574 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4575 }
4576
4577 if (Result)
4578 *Result = EvalResult.Val.getInt();
4579 return false;
4580}