blob: 43cbe98d875d62eeea5b01397797cf66c94b3e44 [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.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000074 if (FD->isDeleted()) {
75 Diag(Loc, diag::err_deleted_function_use);
76 Diag(D->getLocation(), diag::note_unavailable_here) << true;
77 return true;
78 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000079 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000080
81 // See if the decl is unavailable
82 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000083 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000084 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85 }
86
Douglas Gregor6f8c3682009-02-24 04:26:15 +000087 if (D->getDeclContext()->isFunctionOrMethod() &&
88 !D->getDeclContext()->Encloses(CurContext)) {
89 // We've found the name of a function or variable that was
90 // declared with external linkage within another function (and,
91 // therefore, a scope where we wouldn't normally see the
92 // declaration). Once we've made sure that no previous declaration
93 // was properly made visible, produce a warning.
94 bool HasGlobalScopedDeclaration = false;
95 for (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); FD;
96 FD = FD->getPreviousDeclaration()) {
97 if (FD->getDeclContext()->isFileContext()) {
98 HasGlobalScopedDeclaration = true;
99 break;
100 }
101 }
102 // FIXME: do the same thing for variable declarations
103
104 if (!HasGlobalScopedDeclaration) {
105 Diag(Loc, diag::warn_use_out_of_scope_declaration) << D;
106 Diag(D->getLocation(), diag::note_previous_declaration);
107 }
108 }
Douglas Gregoraa57e862009-02-18 21:56:37 +0000109
110 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000111}
112
Douglas Gregor3bb30002009-02-26 21:00:50 +0000113SourceRange Sema::getExprRange(ExprTy *E) const {
114 Expr *Ex = (Expr *)E;
115 return Ex? Ex->getSourceRange() : SourceRange();
116}
117
Chris Lattner299b8842008-07-25 21:10:04 +0000118//===----------------------------------------------------------------------===//
119// Standard Promotions and Conversions
120//===----------------------------------------------------------------------===//
121
Chris Lattner299b8842008-07-25 21:10:04 +0000122/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
123void Sema::DefaultFunctionArrayConversion(Expr *&E) {
124 QualType Ty = E->getType();
125 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
126
Chris Lattner299b8842008-07-25 21:10:04 +0000127 if (Ty->isFunctionType())
128 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000129 else if (Ty->isArrayType()) {
130 // In C90 mode, arrays only promote to pointers if the array expression is
131 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
132 // type 'array of type' is converted to an expression that has type 'pointer
133 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
134 // that has type 'array of type' ...". The relevant change is "an lvalue"
135 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000136 //
137 // C++ 4.2p1:
138 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
139 // T" can be converted to an rvalue of type "pointer to T".
140 //
141 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
142 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000143 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
144 }
Chris Lattner299b8842008-07-25 21:10:04 +0000145}
146
147/// UsualUnaryConversions - Performs various conversions that are common to most
148/// operators (C99 6.3). The conversions of array and function types are
149/// sometimes surpressed. For example, the array->pointer conversion doesn't
150/// apply if the array is an argument to the sizeof or address (&) operators.
151/// In these instances, this routine should *not* be called.
152Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
153 QualType Ty = Expr->getType();
154 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
155
Chris Lattner299b8842008-07-25 21:10:04 +0000156 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
157 ImpCastExprToType(Expr, Context.IntTy);
158 else
159 DefaultFunctionArrayConversion(Expr);
160
161 return Expr;
162}
163
Chris Lattner9305c3d2008-07-25 22:25:12 +0000164/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
165/// do not have a prototype. Arguments that have type float are promoted to
166/// double. All other argument types are converted by UsualUnaryConversions().
167void Sema::DefaultArgumentPromotion(Expr *&Expr) {
168 QualType Ty = Expr->getType();
169 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
170
171 // If this is a 'float' (CVR qualified or typedef) promote to double.
172 if (const BuiltinType *BT = Ty->getAsBuiltinType())
173 if (BT->getKind() == BuiltinType::Float)
174 return ImpCastExprToType(Expr, Context.DoubleTy);
175
176 UsualUnaryConversions(Expr);
177}
178
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000179// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
180// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000181void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000182 DefaultArgumentPromotion(Expr);
183
184 if (!Expr->getType()->isPODType()) {
185 Diag(Expr->getLocStart(),
186 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
187 Expr->getType() << CT;
188 }
189}
190
191
Chris Lattner299b8842008-07-25 21:10:04 +0000192/// UsualArithmeticConversions - Performs various conversions that are common to
193/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
194/// routine returns the first non-arithmetic type found. The client is
195/// responsible for emitting appropriate error diagnostics.
196/// FIXME: verify the conversion rules for "complex int" are consistent with
197/// GCC.
198QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
199 bool isCompAssign) {
200 if (!isCompAssign) {
201 UsualUnaryConversions(lhsExpr);
202 UsualUnaryConversions(rhsExpr);
203 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000204
Chris Lattner299b8842008-07-25 21:10:04 +0000205 // For conversion purposes, we ignore any qualifiers.
206 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000207 QualType lhs =
208 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
209 QualType rhs =
210 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000211
212 // If both types are identical, no conversion is needed.
213 if (lhs == rhs)
214 return lhs;
215
216 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
217 // The caller can deal with this (e.g. pointer + int).
218 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
219 return lhs;
220
221 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
222 if (!isCompAssign) {
223 ImpCastExprToType(lhsExpr, destType);
224 ImpCastExprToType(rhsExpr, destType);
225 }
226 return destType;
227}
228
229QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
230 // Perform the usual unary conversions. We do this early so that
231 // integral promotions to "int" can allow us to exit early, in the
232 // lhs == rhs check. Also, for conversion purposes, we ignore any
233 // qualifiers. For example, "const float" and "float" are
234 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000235 if (lhs->isPromotableIntegerType())
236 lhs = Context.IntTy;
237 else
238 lhs = lhs.getUnqualifiedType();
239 if (rhs->isPromotableIntegerType())
240 rhs = Context.IntTy;
241 else
242 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000243
Chris Lattner299b8842008-07-25 21:10:04 +0000244 // If both types are identical, no conversion is needed.
245 if (lhs == rhs)
246 return lhs;
247
248 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
249 // The caller can deal with this (e.g. pointer + int).
250 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
251 return lhs;
252
253 // At this point, we have two different arithmetic types.
254
255 // Handle complex types first (C99 6.3.1.8p1).
256 if (lhs->isComplexType() || rhs->isComplexType()) {
257 // if we have an integer operand, the result is the complex type.
258 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
259 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000260 return lhs;
261 }
262 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
263 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000264 return rhs;
265 }
266 // This handles complex/complex, complex/float, or float/complex.
267 // When both operands are complex, the shorter operand is converted to the
268 // type of the longer, and that is the type of the result. This corresponds
269 // to what is done when combining two real floating-point operands.
270 // The fun begins when size promotion occur across type domains.
271 // From H&S 6.3.4: When one operand is complex and the other is a real
272 // floating-point type, the less precise type is converted, within it's
273 // real or complex domain, to the precision of the other type. For example,
274 // when combining a "long double" with a "double _Complex", the
275 // "double _Complex" is promoted to "long double _Complex".
276 int result = Context.getFloatingTypeOrder(lhs, rhs);
277
278 if (result > 0) { // The left side is bigger, convert rhs.
279 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000280 } else if (result < 0) { // The right side is bigger, convert lhs.
281 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000282 }
283 // At this point, lhs and rhs have the same rank/size. Now, make sure the
284 // domains match. This is a requirement for our implementation, C99
285 // does not require this promotion.
286 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
287 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000288 return rhs;
289 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000290 return lhs;
291 }
292 }
293 return lhs; // The domain/size match exactly.
294 }
295 // Now handle "real" floating types (i.e. float, double, long double).
296 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
297 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000298 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000299 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000300 return lhs;
301 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000302 if (rhs->isComplexIntegerType()) {
303 // convert rhs to the complex floating point type.
304 return Context.getComplexType(lhs);
305 }
306 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000307 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000308 return rhs;
309 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000310 if (lhs->isComplexIntegerType()) {
311 // convert lhs to the complex floating point type.
312 return Context.getComplexType(rhs);
313 }
Chris Lattner299b8842008-07-25 21:10:04 +0000314 // We have two real floating types, float/complex combos were handled above.
315 // Convert the smaller operand to the bigger result.
316 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000317 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000318 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000319 assert(result < 0 && "illegal float comparison");
320 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000321 }
322 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
323 // Handle GCC complex int extension.
324 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
325 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
326
327 if (lhsComplexInt && rhsComplexInt) {
328 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000329 rhsComplexInt->getElementType()) >= 0)
330 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000331 return rhs;
332 } else if (lhsComplexInt && rhs->isIntegerType()) {
333 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000334 return lhs;
335 } else if (rhsComplexInt && lhs->isIntegerType()) {
336 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000337 return rhs;
338 }
339 }
340 // Finally, we have two differing integer types.
341 // The rules for this case are in C99 6.3.1.8
342 int compare = Context.getIntegerTypeOrder(lhs, rhs);
343 bool lhsSigned = lhs->isSignedIntegerType(),
344 rhsSigned = rhs->isSignedIntegerType();
345 QualType destType;
346 if (lhsSigned == rhsSigned) {
347 // Same signedness; use the higher-ranked type
348 destType = compare >= 0 ? lhs : rhs;
349 } else if (compare != (lhsSigned ? 1 : -1)) {
350 // The unsigned type has greater than or equal rank to the
351 // signed type, so use the unsigned type
352 destType = lhsSigned ? rhs : lhs;
353 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
354 // The two types are different widths; if we are here, that
355 // means the signed type is larger than the unsigned type, so
356 // use the signed type.
357 destType = lhsSigned ? lhs : rhs;
358 } else {
359 // The signed type is higher-ranked than the unsigned type,
360 // but isn't actually any bigger (like unsigned int and long
361 // on most 32-bit systems). Use the unsigned type corresponding
362 // to the signed type.
363 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
364 }
Chris Lattner299b8842008-07-25 21:10:04 +0000365 return destType;
366}
367
368//===----------------------------------------------------------------------===//
369// Semantic Analysis for various Expression Types
370//===----------------------------------------------------------------------===//
371
372
Steve Naroff87d58b42007-09-16 03:34:24 +0000373/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000374/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
375/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
376/// multiple tokens. However, the common case is that StringToks points to one
377/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000378///
379Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000380Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000381 assert(NumStringToks && "Must have at least one string!");
382
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000383 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000384 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000385 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000386
387 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
388 for (unsigned i = 0; i != NumStringToks; ++i)
389 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000390
Chris Lattnera6dcce32008-02-11 00:02:17 +0000391 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000392 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000393 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000394
395 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
396 if (getLangOptions().CPlusPlus)
397 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000398
Chris Lattnera6dcce32008-02-11 00:02:17 +0000399 // Get an array type for the string, according to C99 6.4.5. This includes
400 // the nul terminator character as well as the string length for pascal
401 // strings.
402 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000403 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000404 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000405
Chris Lattner4b009652007-07-25 00:24:17 +0000406 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000407 return Owned(StringLiteral::Create(Context, Literal.GetString(),
408 Literal.GetStringLength(),
409 Literal.AnyWide, StrTy,
410 &StringTokLocs[0],
411 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000412}
413
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000414/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
415/// CurBlock to VD should cause it to be snapshotted (as we do for auto
416/// variables defined outside the block) or false if this is not needed (e.g.
417/// for values inside the block or for globals).
418///
419/// FIXME: This will create BlockDeclRefExprs for global variables,
420/// function references, etc which is suboptimal :) and breaks
421/// things like "integer constant expression" tests.
422static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
423 ValueDecl *VD) {
424 // If the value is defined inside the block, we couldn't snapshot it even if
425 // we wanted to.
426 if (CurBlock->TheDecl == VD->getDeclContext())
427 return false;
428
429 // If this is an enum constant or function, it is constant, don't snapshot.
430 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
431 return false;
432
433 // If this is a reference to an extern, static, or global variable, no need to
434 // snapshot it.
435 // FIXME: What about 'const' variables in C++?
436 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
437 return Var->hasLocalStorage();
438
439 return true;
440}
441
442
443
Steve Naroff0acc9c92007-09-15 18:49:24 +0000444/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000445/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000446/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000447/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000448/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000449Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
450 IdentifierInfo &II,
451 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000452 const CXXScopeSpec *SS,
453 bool isAddressOfOperand) {
454 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000455 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000456}
457
Douglas Gregor566782a2009-01-06 05:10:23 +0000458/// BuildDeclRefExpr - Build either a DeclRefExpr or a
459/// QualifiedDeclRefExpr based on whether or not SS is a
460/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000461DeclRefExpr *
462Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
463 bool TypeDependent, bool ValueDependent,
464 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000465 if (SS && !SS->isEmpty())
466 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Mike Stump9afab102009-02-19 03:04:26 +0000467 ValueDependent,
468 SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000469 else
470 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000471}
472
Douglas Gregor723d3332009-01-07 00:43:41 +0000473/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
474/// variable corresponding to the anonymous union or struct whose type
475/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000476static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000477 assert(Record->isAnonymousStructOrUnion() &&
478 "Record must be an anonymous struct or union!");
479
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000480 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000481 // be an O(1) operation rather than a slow walk through DeclContext's
482 // vector (which itself will be eliminated). DeclGroups might make
483 // this even better.
484 DeclContext *Ctx = Record->getDeclContext();
485 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
486 DEnd = Ctx->decls_end();
487 D != DEnd; ++D) {
488 if (*D == Record) {
489 // The object for the anonymous struct/union directly
490 // follows its type in the list of declarations.
491 ++D;
492 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000493 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000494 return *D;
495 }
496 }
497
498 assert(false && "Missing object for anonymous record");
499 return 0;
500}
501
Sebastian Redlcd883f72009-01-18 18:53:16 +0000502Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000503Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
504 FieldDecl *Field,
505 Expr *BaseObjectExpr,
506 SourceLocation OpLoc) {
507 assert(Field->getDeclContext()->isRecord() &&
508 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
509 && "Field must be stored inside an anonymous struct or union");
510
511 // Construct the sequence of field member references
512 // we'll have to perform to get to the field in the anonymous
513 // union/struct. The list of members is built from the field
514 // outward, so traverse it backwards to go from an object in
515 // the current context to the field we found.
516 llvm::SmallVector<FieldDecl *, 4> AnonFields;
517 AnonFields.push_back(Field);
518 VarDecl *BaseObject = 0;
519 DeclContext *Ctx = Field->getDeclContext();
520 do {
521 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000522 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000523 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
524 AnonFields.push_back(AnonField);
525 else {
526 BaseObject = cast<VarDecl>(AnonObject);
527 break;
528 }
529 Ctx = Ctx->getParent();
530 } while (Ctx->isRecord() &&
531 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
532
533 // Build the expression that refers to the base object, from
534 // which we will build a sequence of member references to each
535 // of the anonymous union objects and, eventually, the field we
536 // found via name lookup.
537 bool BaseObjectIsPointer = false;
538 unsigned ExtraQuals = 0;
539 if (BaseObject) {
540 // BaseObject is an anonymous struct/union variable (and is,
541 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000542 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000543 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000544 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000545 ExtraQuals
546 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
547 } else if (BaseObjectExpr) {
548 // The caller provided the base object expression. Determine
549 // whether its a pointer and whether it adds any qualifiers to the
550 // anonymous struct/union fields we're looking into.
551 QualType ObjectType = BaseObjectExpr->getType();
552 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
553 BaseObjectIsPointer = true;
554 ObjectType = ObjectPtr->getPointeeType();
555 }
556 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
557 } else {
558 // We've found a member of an anonymous struct/union that is
559 // inside a non-anonymous struct/union, so in a well-formed
560 // program our base object expression is "this".
561 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
562 if (!MD->isStatic()) {
563 QualType AnonFieldType
564 = Context.getTagDeclType(
565 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
566 QualType ThisType = Context.getTagDeclType(MD->getParent());
567 if ((Context.getCanonicalType(AnonFieldType)
568 == Context.getCanonicalType(ThisType)) ||
569 IsDerivedFrom(ThisType, AnonFieldType)) {
570 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000571 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000572 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000573 BaseObjectIsPointer = true;
574 }
575 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000576 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
577 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000578 }
579 ExtraQuals = MD->getTypeQualifiers();
580 }
581
582 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000583 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
584 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000585 }
586
587 // Build the implicit member references to the field of the
588 // anonymous struct/union.
589 Expr *Result = BaseObjectExpr;
590 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
591 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
592 FI != FIEnd; ++FI) {
593 QualType MemberType = (*FI)->getType();
594 if (!(*FI)->isMutable()) {
595 unsigned combinedQualifiers
596 = MemberType.getCVRQualifiers() | ExtraQuals;
597 MemberType = MemberType.getQualifiedType(combinedQualifiers);
598 }
Steve Naroff774e4152009-01-21 00:14:39 +0000599 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
600 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000601 BaseObjectIsPointer = false;
602 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
603 OpLoc = SourceLocation();
604 }
605
Sebastian Redlcd883f72009-01-18 18:53:16 +0000606 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000607}
608
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000609/// ActOnDeclarationNameExpr - The parser has read some kind of name
610/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
611/// performs lookup on that name and returns an expression that refers
612/// to that name. This routine isn't directly called from the parser,
613/// because the parser doesn't know about DeclarationName. Rather,
614/// this routine is called by ActOnIdentifierExpr,
615/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
616/// which form the DeclarationName from the corresponding syntactic
617/// forms.
618///
619/// HasTrailingLParen indicates whether this identifier is used in a
620/// function call context. LookupCtx is only used for a C++
621/// qualified-id (foo::bar) to indicate the class or namespace that
622/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000623///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000624/// isAddressOfOperand means that this expression is the direct operand
625/// of an address-of operator. This matters because this is the only
626/// situation where a qualified name referencing a non-static member may
627/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000628Sema::OwningExprResult
629Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
630 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000631 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000632 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000633 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000634 if (SS && SS->isInvalid())
635 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000636 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
637 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000638
Douglas Gregor09be81b2009-02-04 17:27:36 +0000639 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000640 if (Lookup.isAmbiguous()) {
641 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
642 SS && SS->isSet() ? SS->getRange()
643 : SourceRange());
644 return ExprError();
645 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000646 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000647
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000648 // If this reference is in an Objective-C method, then ivar lookup happens as
649 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000650 IdentifierInfo *II = Name.getAsIdentifierInfo();
651 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000652 // There are two cases to handle here. 1) scoped lookup could have failed,
653 // in which case we should look for an ivar. 2) scoped lookup could have
654 // found a decl, but that decl is outside the current method (i.e. a global
655 // variable). In these two cases, we do a lookup for an ivar with this
656 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000657 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000658 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000659 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000660 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000661 if (DiagnoseUseOfDecl(IV, Loc))
662 return ExprError();
Chris Lattner2a3bef92009-02-16 17:19:12 +0000663
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000664 // FIXME: This should use a new expr for a direct reference, don't turn
665 // this into Self->ivar, just return a BareIVarExpr or something.
666 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000667 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Mike Stump9afab102009-02-19 03:04:26 +0000668 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +0000669 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000670 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000671 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000672 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000673 }
674 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000675 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000676 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000677 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000678 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000679 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000680 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000681 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000682
Douglas Gregoraa57e862009-02-18 21:56:37 +0000683 // Determine whether this name might be a candidate for
684 // argument-dependent lookup.
685 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
686 HasTrailingLParen;
687
688 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000689 // We've seen something of the form
690 //
691 // identifier(
692 //
693 // and we did not find any entity by the name
694 // "identifier". However, this identifier is still subject to
695 // argument-dependent lookup, so keep track of the name.
696 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
697 Context.OverloadTy,
698 Loc));
699 }
700
Chris Lattner4b009652007-07-25 00:24:17 +0000701 if (D == 0) {
702 // Otherwise, this could be an implicitly declared function reference (legal
703 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000704 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000705 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000706 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000707 else {
708 // If this name wasn't predeclared and if this is not a function call,
709 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000710 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000711 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
712 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000713 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
714 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000715 return ExprError(Diag(Loc, diag::err_undeclared_use)
716 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000717 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000718 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000719 }
720 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000721
Sebastian Redl0c9da212009-02-03 20:19:35 +0000722 // If this is an expression of the form &Class::member, don't build an
723 // implicit member ref, because we want a pointer to the member in general,
724 // not any specific instance's member.
725 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000726 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000727 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000728 QualType DType;
729 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
730 DType = FD->getType().getNonReferenceType();
731 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
732 DType = Method->getType();
733 } else if (isa<OverloadedFunctionDecl>(D)) {
734 DType = Context.OverloadTy;
735 }
736 // Could be an inner type. That's diagnosed below, so ignore it here.
737 if (!DType.isNull()) {
738 // The pointer is type- and value-dependent if it points into something
739 // dependent.
740 bool Dependent = false;
741 for (; DC; DC = DC->getParent()) {
742 // FIXME: could stop early at namespace scope.
743 if (DC->isRecord()) {
744 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
745 if (Context.getTypeDeclType(Record)->isDependentType()) {
746 Dependent = true;
747 break;
748 }
749 }
750 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000751 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000752 }
753 }
754 }
755
Douglas Gregor723d3332009-01-07 00:43:41 +0000756 // We may have found a field within an anonymous union or struct
757 // (C++ [class.union]).
758 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
759 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
760 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000761
Douglas Gregor3257fb52008-12-22 05:46:06 +0000762 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
763 if (!MD->isStatic()) {
764 // C++ [class.mfct.nonstatic]p2:
765 // [...] if name lookup (3.4.1) resolves the name in the
766 // id-expression to a nonstatic nontype member of class X or of
767 // a base class of X, the id-expression is transformed into a
768 // class member access expression (5.2.5) using (*this) (9.3.2)
769 // as the postfix-expression to the left of the '.' operator.
770 DeclContext *Ctx = 0;
771 QualType MemberType;
772 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
773 Ctx = FD->getDeclContext();
774 MemberType = FD->getType();
775
776 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
777 MemberType = RefType->getPointeeType();
778 else if (!FD->isMutable()) {
779 unsigned combinedQualifiers
780 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
781 MemberType = MemberType.getQualifiedType(combinedQualifiers);
782 }
783 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
784 if (!Method->isStatic()) {
785 Ctx = Method->getParent();
786 MemberType = Method->getType();
787 }
788 } else if (OverloadedFunctionDecl *Ovl
789 = dyn_cast<OverloadedFunctionDecl>(D)) {
790 for (OverloadedFunctionDecl::function_iterator
791 Func = Ovl->function_begin(),
792 FuncEnd = Ovl->function_end();
793 Func != FuncEnd; ++Func) {
794 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
795 if (!DMethod->isStatic()) {
796 Ctx = Ovl->getDeclContext();
797 MemberType = Context.OverloadTy;
798 break;
799 }
800 }
801 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000802
803 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000804 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
805 QualType ThisType = Context.getTagDeclType(MD->getParent());
806 if ((Context.getCanonicalType(CtxType)
807 == Context.getCanonicalType(ThisType)) ||
808 IsDerivedFrom(ThisType, CtxType)) {
809 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000810 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000811 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000812 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000813 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000814 }
815 }
816 }
817 }
818
Douglas Gregor8acb7272008-12-11 16:49:14 +0000819 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000820 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
821 if (MD->isStatic())
822 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000823 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
824 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000825 }
826
Douglas Gregor3257fb52008-12-22 05:46:06 +0000827 // Any other ways we could have found the field in a well-formed
828 // program would have been turned into implicit member expressions
829 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000830 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
831 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000832 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000833
Chris Lattner4b009652007-07-25 00:24:17 +0000834 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000835 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000836 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000837 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000838 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000839 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000840
Steve Naroffd6163f32008-09-05 22:11:13 +0000841 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000842 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000843 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
844 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000845 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
846 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
847 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000848 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000849
Douglas Gregoraa57e862009-02-18 21:56:37 +0000850 // Check whether this declaration can be used. Note that we suppress
851 // this check when we're going to perform argument-dependent lookup
852 // on this function name, because this might not be the function
853 // that overload resolution actually selects.
854 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
855 return ExprError();
856
Douglas Gregor48840c72008-12-10 23:01:14 +0000857 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000858 // Warn about constructs like:
859 // if (void *X = foo()) { ... } else { X }.
860 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000861 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
862 Scope *CheckS = S;
863 while (CheckS) {
864 if (CheckS->isWithinElse() &&
865 CheckS->getControlParent()->isDeclScope(Var)) {
866 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000867 ExprError(Diag(Loc, diag::warn_value_always_false)
868 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000869 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000870 ExprError(Diag(Loc, diag::warn_value_always_zero)
871 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000872 break;
873 }
874
875 // Move up one more control parent to check again.
876 CheckS = CheckS->getControlParent();
877 if (CheckS)
878 CheckS = CheckS->getParent();
879 }
880 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000881 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
882 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
883 // C99 DR 316 says that, if a function type comes from a
884 // function definition (without a prototype), that type is only
885 // used for checking compatibility. Therefore, when referencing
886 // the function, we pretend that we don't have the full function
887 // type.
888 QualType T = Func->getType();
889 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000890 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
891 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000892 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
893 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000894 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000895
896 // Only create DeclRefExpr's for valid Decl's.
897 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000898 return ExprError();
899
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000900 // If the identifier reference is inside a block, and it refers to a value
901 // that is outside the block, create a BlockDeclRefExpr instead of a
902 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
903 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000904 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000905 // We do not do this for things like enum constants, global variables, etc,
906 // as they do not get snapshotted.
907 //
908 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000909 // Blocks that have these can't be constant.
910 CurBlock->hasBlockDeclRefExprs = true;
911
Steve Naroff52059382008-10-10 01:28:17 +0000912 // The BlocksAttr indicates the variable is bound by-reference.
913 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000914 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000915 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000916
Steve Naroff52059382008-10-10 01:28:17 +0000917 // Variable will be bound by-copy, make it const within the closure.
918 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000919 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000920 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000921 }
922 // If this reference is not in a block or if the referenced variable is
923 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000924
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000925 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000926 bool ValueDependent = false;
927 if (getLangOptions().CPlusPlus) {
928 // C++ [temp.dep.expr]p3:
929 // An id-expression is type-dependent if it contains:
930 // - an identifier that was declared with a dependent type,
931 if (VD->getType()->isDependentType())
932 TypeDependent = true;
933 // - FIXME: a template-id that is dependent,
934 // - a conversion-function-id that specifies a dependent type,
935 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
936 Name.getCXXNameType()->isDependentType())
937 TypeDependent = true;
938 // - a nested-name-specifier that contains a class-name that
939 // names a dependent type.
940 else if (SS && !SS->isEmpty()) {
941 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
942 DC; DC = DC->getParent()) {
943 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000944 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000945 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
946 if (Context.getTypeDeclType(Record)->isDependentType()) {
947 TypeDependent = true;
948 break;
949 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000950 }
951 }
952 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000953
Douglas Gregora5d84612008-12-10 20:57:37 +0000954 // C++ [temp.dep.constexpr]p2:
955 //
956 // An identifier is value-dependent if it is:
957 // - a name declared with a dependent type,
958 if (TypeDependent)
959 ValueDependent = true;
960 // - the name of a non-type template parameter,
961 else if (isa<NonTypeTemplateParmDecl>(VD))
962 ValueDependent = true;
963 // - a constant with integral or enumeration type and is
964 // initialized with an expression that is value-dependent
965 // (FIXME!).
966 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000967
Sebastian Redlcd883f72009-01-18 18:53:16 +0000968 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
969 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000970}
971
Sebastian Redlcd883f72009-01-18 18:53:16 +0000972Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
973 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000974 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000975
Chris Lattner4b009652007-07-25 00:24:17 +0000976 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000977 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000978 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
979 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
980 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000981 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000982
Chris Lattner7e637512008-01-12 08:14:25 +0000983 // Pre-defined identifiers are of type char[x], where x is the length of the
984 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000985 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000986 if (FunctionDecl *FD = getCurFunctionDecl())
987 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000988 else if (ObjCMethodDecl *MD = getCurMethodDecl())
989 Length = MD->getSynthesizedMethodSize();
990 else {
991 Diag(Loc, diag::ext_predef_outside_function);
992 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
993 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
994 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000995
996
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000997 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000998 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000999 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001000 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001001}
1002
Sebastian Redlcd883f72009-01-18 18:53:16 +00001003Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001004 llvm::SmallString<16> CharBuffer;
1005 CharBuffer.resize(Tok.getLength());
1006 const char *ThisTokBegin = &CharBuffer[0];
1007 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001008
Chris Lattner4b009652007-07-25 00:24:17 +00001009 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1010 Tok.getLocation(), PP);
1011 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001012 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001013
1014 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1015
Sebastian Redl75324932009-01-20 22:23:13 +00001016 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1017 Literal.isWide(),
1018 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001019}
1020
Sebastian Redlcd883f72009-01-18 18:53:16 +00001021Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1022 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001023 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1024 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001025 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001026 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001027 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001028 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001029 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001030
Chris Lattner4b009652007-07-25 00:24:17 +00001031 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001032 // Add padding so that NumericLiteralParser can overread by one character.
1033 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001034 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001035
Chris Lattner4b009652007-07-25 00:24:17 +00001036 // Get the spelling of the token, which eliminates trigraphs, etc.
1037 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001038
Chris Lattner4b009652007-07-25 00:24:17 +00001039 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1040 Tok.getLocation(), PP);
1041 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001042 return ExprError();
1043
Chris Lattner1de66eb2007-08-26 03:42:43 +00001044 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001045
Chris Lattner1de66eb2007-08-26 03:42:43 +00001046 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001047 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001048 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001049 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001050 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001051 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001052 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001053 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001054
1055 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1056
Ted Kremenekddedbe22007-11-29 00:56:49 +00001057 // isExact will be set by GetFloatValue().
1058 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001059 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1060 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001061
Chris Lattner1de66eb2007-08-26 03:42:43 +00001062 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001063 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001064 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001065 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001066
Neil Booth7421e9c2007-08-29 22:00:19 +00001067 // long long is a C99 feature.
1068 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001069 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001070 Diag(Tok.getLocation(), diag::ext_longlong);
1071
Chris Lattner4b009652007-07-25 00:24:17 +00001072 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001073 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001074
Chris Lattner4b009652007-07-25 00:24:17 +00001075 if (Literal.GetIntegerValue(ResultVal)) {
1076 // If this value didn't fit into uintmax_t, warn and force to ull.
1077 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001078 Ty = Context.UnsignedLongLongTy;
1079 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001080 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001081 } else {
1082 // If this value fits into a ULL, try to figure out what else it fits into
1083 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001084
Chris Lattner4b009652007-07-25 00:24:17 +00001085 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1086 // be an unsigned int.
1087 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1088
1089 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001090 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001091 if (!Literal.isLong && !Literal.isLongLong) {
1092 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001093 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001094
Chris Lattner4b009652007-07-25 00:24:17 +00001095 // Does it fit in a unsigned int?
1096 if (ResultVal.isIntN(IntSize)) {
1097 // Does it fit in a signed int?
1098 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001099 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001100 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001101 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001102 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001103 }
Chris Lattner4b009652007-07-25 00:24:17 +00001104 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001105
Chris Lattner4b009652007-07-25 00:24:17 +00001106 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001107 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001108 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001109
Chris Lattner4b009652007-07-25 00:24:17 +00001110 // Does it fit in a unsigned long?
1111 if (ResultVal.isIntN(LongSize)) {
1112 // Does it fit in a signed long?
1113 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001114 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001115 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001116 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001117 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001118 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001119 }
1120
Chris Lattner4b009652007-07-25 00:24:17 +00001121 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001122 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001123 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001124
Chris Lattner4b009652007-07-25 00:24:17 +00001125 // Does it fit in a unsigned long long?
1126 if (ResultVal.isIntN(LongLongSize)) {
1127 // Does it fit in a signed long long?
1128 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001129 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001130 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001131 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001132 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001133 }
1134 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001135
Chris Lattner4b009652007-07-25 00:24:17 +00001136 // If we still couldn't decide a type, we probably have something that
1137 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001138 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001139 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001140 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001141 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001142 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001143
Chris Lattnere4068872008-05-09 05:59:00 +00001144 if (ResultVal.getBitWidth() != Width)
1145 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001146 }
Sebastian Redl75324932009-01-20 22:23:13 +00001147 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001148 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001149
Chris Lattner1de66eb2007-08-26 03:42:43 +00001150 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1151 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001152 Res = new (Context) ImaginaryLiteral(Res,
1153 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001154
1155 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001156}
1157
Sebastian Redlcd883f72009-01-18 18:53:16 +00001158Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1159 SourceLocation R, ExprArg Val) {
1160 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001161 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001162 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001163}
1164
1165/// The UsualUnaryConversions() function is *not* called by this routine.
1166/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001167bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001168 SourceLocation OpLoc,
1169 const SourceRange &ExprRange,
1170 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001171 if (exprType->isDependentType())
1172 return false;
1173
Chris Lattner4b009652007-07-25 00:24:17 +00001174 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001175 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001176 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001177 if (isSizeof)
1178 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1179 return false;
1180 }
1181
1182 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001183 Diag(OpLoc, diag::ext_sizeof_void_type)
1184 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001185 return false;
1186 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001187
Chris Lattner159fe082009-01-24 19:46:37 +00001188 return DiagnoseIncompleteType(OpLoc, exprType,
1189 isSizeof ? diag::err_sizeof_incomplete_type :
1190 diag::err_alignof_incomplete_type,
1191 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001192}
1193
Chris Lattner8d9f7962009-01-24 20:17:12 +00001194bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1195 const SourceRange &ExprRange) {
1196 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001197
Chris Lattner8d9f7962009-01-24 20:17:12 +00001198 // alignof decl is always ok.
1199 if (isa<DeclRefExpr>(E))
1200 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001201
1202 // Cannot know anything else if the expression is dependent.
1203 if (E->isTypeDependent())
1204 return false;
1205
Chris Lattner8d9f7962009-01-24 20:17:12 +00001206 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1207 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1208 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001209 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001210 return true;
1211 }
1212 // Other fields are ok.
1213 return false;
1214 }
1215 }
1216 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1217}
1218
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001219/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1220/// the same for @c alignof and @c __alignof
1221/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001222Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001223Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1224 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001225 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001226 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001227
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001228 QualType ArgTy;
1229 SourceRange Range;
1230 if (isType) {
1231 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1232 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001233
1234 // Verify that the operand is valid.
1235 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1236 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001237 } else {
1238 // Get the end location.
1239 Expr *ArgEx = (Expr *)TyOrEx;
1240 Range = ArgEx->getSourceRange();
1241 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001242
1243 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001244 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001245 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001246 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001247 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1248 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1249 isInvalid = true;
1250 } else {
1251 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1252 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001253
1254 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001255 DeleteExpr(ArgEx);
1256 return ExprError();
1257 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001258 }
1259
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001260 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001261 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001262 Context.getSizeType(), OpLoc,
1263 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001264}
1265
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001266QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001267 if (V->isTypeDependent())
1268 return Context.DependentTy;
1269
Chris Lattner03931a72007-08-24 21:16:53 +00001270 DefaultFunctionArrayConversion(V);
1271
Chris Lattnera16e42d2007-08-26 05:39:26 +00001272 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001273 if (const ComplexType *CT = V->getType()->getAsComplexType())
1274 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001275
1276 // Otherwise they pass through real integer and floating point types here.
1277 if (V->getType()->isArithmeticType())
1278 return V->getType();
1279
1280 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001281 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1282 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001283 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001284}
1285
1286
Chris Lattner4b009652007-07-25 00:24:17 +00001287
Sebastian Redl8b769972009-01-19 00:08:26 +00001288Action::OwningExprResult
1289Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1290 tok::TokenKind Kind, ExprArg Input) {
1291 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001292
Chris Lattner4b009652007-07-25 00:24:17 +00001293 UnaryOperator::Opcode Opc;
1294 switch (Kind) {
1295 default: assert(0 && "Unknown unary op!");
1296 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1297 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1298 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001299
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001300 if (getLangOptions().CPlusPlus &&
1301 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1302 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001303 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001304 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1305
1306 // C++ [over.inc]p1:
1307 //
1308 // [...] If the function is a member function with one
1309 // parameter (which shall be of type int) or a non-member
1310 // function with two parameters (the second of which shall be
1311 // of type int), it defines the postfix increment operator ++
1312 // for objects of that type. When the postfix increment is
1313 // called as a result of using the ++ operator, the int
1314 // argument will have value zero.
1315 Expr *Args[2] = {
1316 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001317 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1318 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001319 };
1320
1321 // Build the candidate set for overloading
1322 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001323 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1324 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001325
1326 // Perform overload resolution.
1327 OverloadCandidateSet::iterator Best;
1328 switch (BestViableFunction(CandidateSet, Best)) {
1329 case OR_Success: {
1330 // We found a built-in operator or an overloaded operator.
1331 FunctionDecl *FnDecl = Best->Function;
1332
1333 if (FnDecl) {
1334 // We matched an overloaded operator. Build a call to that
1335 // operator.
1336
1337 // Convert the arguments.
1338 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1339 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001340 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001341 } else {
1342 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001343 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001344 FnDecl->getParamDecl(0)->getType(),
1345 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001346 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001347 }
1348
1349 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001350 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001351 = FnDecl->getType()->getAsFunctionType()->getResultType();
1352 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001353
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001354 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001355 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001356 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001357 UsualUnaryConversions(FnExpr);
1358
Sebastian Redl8b769972009-01-19 00:08:26 +00001359 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001360 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1361 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001362 } else {
1363 // We matched a built-in operator. Convert the arguments, then
1364 // break out so that we will build the appropriate built-in
1365 // operator node.
1366 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1367 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001368 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001369
1370 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001371 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001372 }
1373
1374 case OR_No_Viable_Function:
1375 // No viable function; fall through to handling this as a
1376 // built-in operator, which will produce an error message for us.
1377 break;
1378
1379 case OR_Ambiguous:
1380 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1381 << UnaryOperator::getOpcodeStr(Opc)
1382 << Arg->getSourceRange();
1383 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001384 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001385
1386 case OR_Deleted:
1387 Diag(OpLoc, diag::err_ovl_deleted_oper)
1388 << Best->Function->isDeleted()
1389 << UnaryOperator::getOpcodeStr(Opc)
1390 << Arg->getSourceRange();
1391 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1392 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001393 }
1394
1395 // Either we found no viable overloaded operator or we matched a
1396 // built-in operator. In either case, fall through to trying to
1397 // build a built-in operation.
1398 }
1399
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001400 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1401 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001402 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001403 return ExprError();
1404 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001405 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001406}
1407
Sebastian Redl8b769972009-01-19 00:08:26 +00001408Action::OwningExprResult
1409Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1410 ExprArg Idx, SourceLocation RLoc) {
1411 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1412 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001413
Douglas Gregor80723c52008-11-19 17:17:41 +00001414 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001415 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001416 LHSExp->getType()->isEnumeralType() ||
1417 RHSExp->getType()->isRecordType() ||
1418 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001419 // Add the appropriate overloaded operators (C++ [over.match.oper])
1420 // to the candidate set.
1421 OverloadCandidateSet CandidateSet;
1422 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001423 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1424 SourceRange(LLoc, RLoc)))
1425 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001426
Douglas Gregor80723c52008-11-19 17:17:41 +00001427 // Perform overload resolution.
1428 OverloadCandidateSet::iterator Best;
1429 switch (BestViableFunction(CandidateSet, Best)) {
1430 case OR_Success: {
1431 // We found a built-in operator or an overloaded operator.
1432 FunctionDecl *FnDecl = Best->Function;
1433
1434 if (FnDecl) {
1435 // We matched an overloaded operator. Build a call to that
1436 // operator.
1437
1438 // Convert the arguments.
1439 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1440 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1441 PerformCopyInitialization(RHSExp,
1442 FnDecl->getParamDecl(0)->getType(),
1443 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001444 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001445 } else {
1446 // Convert the arguments.
1447 if (PerformCopyInitialization(LHSExp,
1448 FnDecl->getParamDecl(0)->getType(),
1449 "passing") ||
1450 PerformCopyInitialization(RHSExp,
1451 FnDecl->getParamDecl(1)->getType(),
1452 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001453 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001454 }
1455
1456 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001457 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001458 = FnDecl->getType()->getAsFunctionType()->getResultType();
1459 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001460
Douglas Gregor80723c52008-11-19 17:17:41 +00001461 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001462 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1463 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001464 UsualUnaryConversions(FnExpr);
1465
Sebastian Redl8b769972009-01-19 00:08:26 +00001466 Base.release();
1467 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001468 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001469 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001470 } else {
1471 // We matched a built-in operator. Convert the arguments, then
1472 // break out so that we will build the appropriate built-in
1473 // operator node.
1474 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1475 "passing") ||
1476 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1477 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001478 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001479
1480 break;
1481 }
1482 }
1483
1484 case OR_No_Viable_Function:
1485 // No viable function; fall through to handling this as a
1486 // built-in operator, which will produce an error message for us.
1487 break;
1488
1489 case OR_Ambiguous:
1490 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1491 << "[]"
1492 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1493 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001494 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001495
1496 case OR_Deleted:
1497 Diag(LLoc, diag::err_ovl_deleted_oper)
1498 << Best->Function->isDeleted()
1499 << "[]"
1500 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1501 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1502 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001503 }
1504
1505 // Either we found no viable overloaded operator or we matched a
1506 // built-in operator. In either case, fall through to trying to
1507 // build a built-in operation.
1508 }
1509
Chris Lattner4b009652007-07-25 00:24:17 +00001510 // Perform default conversions.
1511 DefaultFunctionArrayConversion(LHSExp);
1512 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001513
Chris Lattner4b009652007-07-25 00:24:17 +00001514 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1515
1516 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001517 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001518 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001519 // and index from the expression types.
1520 Expr *BaseExpr, *IndexExpr;
1521 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001522 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1523 BaseExpr = LHSExp;
1524 IndexExpr = RHSExp;
1525 ResultType = Context.DependentTy;
1526 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001527 BaseExpr = LHSExp;
1528 IndexExpr = RHSExp;
1529 // FIXME: need to deal with const...
1530 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001531 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001532 // Handle the uncommon case of "123[Ptr]".
1533 BaseExpr = RHSExp;
1534 IndexExpr = LHSExp;
1535 // FIXME: need to deal with const...
1536 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001537 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1538 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001539 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001540
Chris Lattner4b009652007-07-25 00:24:17 +00001541 // FIXME: need to deal with const...
1542 ResultType = VTy->getElementType();
1543 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001544 return ExprError(Diag(LHSExp->getLocStart(),
1545 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1546 }
Chris Lattner4b009652007-07-25 00:24:17 +00001547 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001548 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001549 return ExprError(Diag(IndexExpr->getLocStart(),
1550 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001551
1552 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1553 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001554 // void (*)(int)) and pointers to incomplete types. Functions are not
1555 // objects in C99.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001556 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001557 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001558 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001559 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001560
Sebastian Redl8b769972009-01-19 00:08:26 +00001561 Base.release();
1562 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001563 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001564 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001565}
1566
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001567QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001568CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001569 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001570 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001571
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001572 // The vector accessor can't exceed the number of elements.
1573 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001574
Mike Stump9afab102009-02-19 03:04:26 +00001575 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001576 // special names that indicate a subset of exactly half the elements are
1577 // to be selected.
1578 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001579
Nate Begeman1486b502009-01-18 01:47:54 +00001580 // This flag determines whether or not CompName has an 's' char prefix,
1581 // indicating that it is a string of hex values to be used as vector indices.
1582 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001583
1584 // Check that we've found one of the special components, or that the component
1585 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001586 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001587 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1588 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001589 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001590 do
1591 compStr++;
1592 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001593 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001594 do
1595 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001596 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001597 }
Nate Begeman1486b502009-01-18 01:47:54 +00001598
Mike Stump9afab102009-02-19 03:04:26 +00001599 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001600 // We didn't get to the end of the string. This means the component names
1601 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001602 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1603 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001604 return QualType();
1605 }
Mike Stump9afab102009-02-19 03:04:26 +00001606
Nate Begeman1486b502009-01-18 01:47:54 +00001607 // Ensure no component accessor exceeds the width of the vector type it
1608 // operates on.
1609 if (!HalvingSwizzle) {
1610 compStr = CompName.getName();
1611
1612 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001613 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001614
1615 while (*compStr) {
1616 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1617 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1618 << baseType << SourceRange(CompLoc);
1619 return QualType();
1620 }
1621 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001622 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001623
Nate Begeman1486b502009-01-18 01:47:54 +00001624 // If this is a halving swizzle, verify that the base type has an even
1625 // number of elements.
1626 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001627 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001628 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001629 return QualType();
1630 }
Mike Stump9afab102009-02-19 03:04:26 +00001631
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001632 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001633 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001634 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001635 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001636 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001637 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1638 : CompName.getLength();
1639 if (HexSwizzle)
1640 CompSize--;
1641
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001642 if (CompSize == 1)
1643 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001644
Nate Begemanaf6ed502008-04-18 23:10:10 +00001645 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001646 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001647 // diagostics look bad. We want extended vector types to appear built-in.
1648 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1649 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1650 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001651 }
1652 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001653}
1654
Chris Lattner2cb744b2009-02-15 22:43:40 +00001655
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001656/// constructSetterName - Return the setter name for the given
1657/// identifier, i.e. "set" + Name where the initial character of Name
1658/// has been capitalized.
1659// FIXME: Merge with same routine in Parser. But where should this
1660// live?
1661static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1662 const IdentifierInfo *Name) {
1663 llvm::SmallString<100> SelectorName;
1664 SelectorName = "set";
1665 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1666 SelectorName[3] = toupper(SelectorName[3]);
1667 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1668}
1669
Sebastian Redl8b769972009-01-19 00:08:26 +00001670Action::OwningExprResult
1671Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1672 tok::TokenKind OpKind, SourceLocation MemberLoc,
1673 IdentifierInfo &Member) {
1674 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001675 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001676
1677 // Perform default conversions.
1678 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001679
Steve Naroff2cb66382007-07-26 03:11:44 +00001680 QualType BaseType = BaseExpr->getType();
1681 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001682
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001683 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1684 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001685 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001686 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001687 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001688 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001689 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1690 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001691 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001692 return ExprError(Diag(MemberLoc,
1693 diag::err_typecheck_member_reference_arrow)
1694 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001695 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001696
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001697 // Handle field access to simple records. This also handles access to fields
1698 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001699 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001700 RecordDecl *RDecl = RTy->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00001701 if (DiagnoseIncompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001702 diag::err_typecheck_incomplete_tag,
1703 BaseExpr->getSourceRange()))
1704 return ExprError();
1705
Steve Naroff2cb66382007-07-26 03:11:44 +00001706 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001707 // FIXME: Qualified name lookup for C++ is a bit more complicated
1708 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001709 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001710 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001711 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001712
Douglas Gregor09be81b2009-02-04 17:27:36 +00001713 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001714 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001715 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1716 << &Member << BaseExpr->getSourceRange());
1717 else if (Result.isAmbiguous()) {
1718 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1719 MemberLoc, BaseExpr->getSourceRange());
1720 return ExprError();
1721 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001722 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001723
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001724 // If the decl being referenced had an error, return an error for this
1725 // sub-expr without emitting another error, in order to avoid cascading
1726 // error cases.
1727 if (MemberDecl->isInvalidDecl())
1728 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001729
Douglas Gregoraa57e862009-02-18 21:56:37 +00001730 // Check the use of this field
1731 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1732 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001733
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001734 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001735 // We may have found a field within an anonymous union or struct
1736 // (C++ [class.union]).
1737 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001738 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001739 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001740
Douglas Gregor82d44772008-12-20 23:49:58 +00001741 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1742 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001743 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001744 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1745 MemberType = Ref->getPointeeType();
1746 else {
1747 unsigned combinedQualifiers =
1748 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001749 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001750 combinedQualifiers &= ~QualType::Const;
1751 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1752 }
Eli Friedman76b49832008-02-06 22:48:16 +00001753
Steve Naroff774e4152009-01-21 00:14:39 +00001754 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1755 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001756 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001757 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001758 Var, MemberLoc,
1759 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001760 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001761 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001762 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001763 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001764 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001765 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001766 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001767 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001768 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1769 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001770 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001771 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1772 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001773
Douglas Gregor82d44772008-12-20 23:49:58 +00001774 // We found a declaration kind that we didn't expect. This is a
1775 // generic error message that tells the user that she can't refer
1776 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001777 return ExprError(Diag(MemberLoc,
1778 diag::err_typecheck_member_reference_unknown)
1779 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001780 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001781
Chris Lattnere9d71612008-07-21 04:59:05 +00001782 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1783 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001784 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001785 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001786 // If the decl being referenced had an error, return an error for this
1787 // sub-expr without emitting another error, in order to avoid cascading
1788 // error cases.
1789 if (IV->isInvalidDecl())
1790 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001791
1792 // Check whether we can reference this field.
1793 if (DiagnoseUseOfDecl(IV, MemberLoc))
1794 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001795
1796 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001797 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001798 OpKind == tok::arrow);
1799 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001800 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001801 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001802 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1803 << IFTy->getDecl()->getDeclName() << &Member
1804 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001805 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001806
Chris Lattnere9d71612008-07-21 04:59:05 +00001807 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1808 // pointer to a (potentially qualified) interface type.
1809 const PointerType *PTy;
1810 const ObjCInterfaceType *IFTy;
1811 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1812 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1813 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001814
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001815 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001816 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001817 // Check whether we can reference this property.
1818 if (DiagnoseUseOfDecl(PD, MemberLoc))
1819 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001820
Steve Naroff774e4152009-01-21 00:14:39 +00001821 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001822 MemberLoc, BaseExpr));
1823 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001824
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001825 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001826 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1827 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001828 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001829 // Check whether we can reference this property.
1830 if (DiagnoseUseOfDecl(PD, MemberLoc))
1831 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001832
Steve Naroff774e4152009-01-21 00:14:39 +00001833 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001834 MemberLoc, BaseExpr));
1835 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001836
1837 // If that failed, look for an "implicit" property by seeing if the nullary
1838 // selector is implemented.
1839
1840 // FIXME: The logic for looking up nullary and unary selectors should be
1841 // shared with the code in ActOnInstanceMessage.
1842
1843 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1844 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001845
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001846 // If this reference is in an @implementation, check for 'private' methods.
1847 if (!Getter)
1848 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1849 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001850 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001851 ObjCImplementations[ClassDecl->getIdentifier()])
1852 Getter = ImpDecl->getInstanceMethod(Sel);
1853
Steve Naroff04151f32008-10-22 19:16:27 +00001854 // Look through local category implementations associated with the class.
1855 if (!Getter) {
1856 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1857 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1858 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1859 }
1860 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001861 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001862 // Check if we can reference this property.
1863 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1864 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001865
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001866 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001867 // will look for the matching setter, in case it is needed.
1868 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1869 &Member);
1870 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1871 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1872 if (!Setter) {
Mike Stump9afab102009-02-19 03:04:26 +00001873 // If this reference is in an @implementation, also check for 'private'
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001874 // methods.
1875 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1876 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001877 if (ObjCImplementationDecl *ImpDecl =
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001878 ObjCImplementations[ClassDecl->getIdentifier()])
1879 Setter = ImpDecl->getInstanceMethod(SetterSel);
1880 }
1881 // Look through local category implementations associated with the class.
1882 if (!Setter) {
1883 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1884 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1885 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1886 }
1887 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001888
Douglas Gregoraa57e862009-02-18 21:56:37 +00001889 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1890 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001891
Sebastian Redl8b769972009-01-19 00:08:26 +00001892 // FIXME: we must check that the setter has property type.
Mike Stump9afab102009-02-19 03:04:26 +00001893 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001894 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001895 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001896
1897 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1898 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001899 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001900 // Handle properties on qualified "id" protocols.
1901 const ObjCQualifiedIdType *QIdTy;
1902 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1903 // Check protocols on qualified interfaces.
1904 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001905 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001906 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001907 // Check the use of this declaration
1908 if (DiagnoseUseOfDecl(PD, MemberLoc))
1909 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001910
Steve Naroff774e4152009-01-21 00:14:39 +00001911 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001912 MemberLoc, BaseExpr));
1913 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001914 // Also must look for a getter name which uses property syntax.
1915 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1916 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001917 // Check the use of this method.
1918 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1919 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001920
1921 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001922 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001923 }
1924 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001925
1926 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1927 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001928 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001929 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001930 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001931 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1932 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001933 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001934 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00001935 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001936 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001937
1938 return ExprError(Diag(MemberLoc,
1939 diag::err_typecheck_member_reference_struct_union)
1940 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001941}
1942
Douglas Gregor3257fb52008-12-22 05:46:06 +00001943/// ConvertArgumentsForCall - Converts the arguments specified in
1944/// Args/NumArgs to the parameter types of the function FDecl with
1945/// function prototype Proto. Call is the call expression itself, and
1946/// Fn is the function expression. For a C++ member function, this
1947/// routine does not attempt to convert the object argument. Returns
1948/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00001949bool
1950Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001951 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001952 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001953 Expr **Args, unsigned NumArgs,
1954 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00001955 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00001956 // assignment, to the types of the corresponding parameter, ...
1957 unsigned NumArgsInProto = Proto->getNumArgs();
1958 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001959 bool Invalid = false;
1960
Douglas Gregor3257fb52008-12-22 05:46:06 +00001961 // If too few arguments are available (and we don't have default
1962 // arguments for the remaining parameters), don't make the call.
1963 if (NumArgs < NumArgsInProto) {
1964 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1965 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1966 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1967 // Use default arguments for missing arguments
1968 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001969 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001970 }
1971
1972 // If too many are passed and not variadic, error on the extras and drop
1973 // them.
1974 if (NumArgs > NumArgsInProto) {
1975 if (!Proto->isVariadic()) {
1976 Diag(Args[NumArgsInProto]->getLocStart(),
1977 diag::err_typecheck_call_too_many_args)
1978 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1979 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1980 Args[NumArgs-1]->getLocEnd());
1981 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001982 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001983 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001984 }
1985 NumArgsToCheck = NumArgsInProto;
1986 }
Mike Stump9afab102009-02-19 03:04:26 +00001987
Douglas Gregor3257fb52008-12-22 05:46:06 +00001988 // Continue to check argument types (even if we have too few/many args).
1989 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1990 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00001991
Douglas Gregor3257fb52008-12-22 05:46:06 +00001992 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001993 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001994 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001995
1996 // Pass the argument.
1997 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1998 return true;
Mike Stump9afab102009-02-19 03:04:26 +00001999 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002000 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002001 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002002 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002003
Douglas Gregor3257fb52008-12-22 05:46:06 +00002004 Call->setArg(i, Arg);
2005 }
Mike Stump9afab102009-02-19 03:04:26 +00002006
Douglas Gregor3257fb52008-12-22 05:46:06 +00002007 // If this is a variadic call, handle args passed through "...".
2008 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002009 VariadicCallType CallType = VariadicFunction;
2010 if (Fn->getType()->isBlockPointerType())
2011 CallType = VariadicBlock; // Block
2012 else if (isa<MemberExpr>(Fn))
2013 CallType = VariadicMethod;
2014
Douglas Gregor3257fb52008-12-22 05:46:06 +00002015 // Promote the arguments (C99 6.5.2.2p7).
2016 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2017 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002018 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002019 Call->setArg(i, Arg);
2020 }
2021 }
2022
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002023 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002024}
2025
Steve Naroff87d58b42007-09-16 03:34:24 +00002026/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002027/// This provides the location of the left/right parens and a list of comma
2028/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002029Action::OwningExprResult
2030Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2031 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002032 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002033 unsigned NumArgs = args.size();
2034 Expr *Fn = static_cast<Expr *>(fn.release());
2035 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002036 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002037 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002038 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002039
Douglas Gregor3257fb52008-12-22 05:46:06 +00002040 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002041 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002042 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002043 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2044 bool Dependent = false;
2045 if (Fn->isTypeDependent())
2046 Dependent = true;
2047 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2048 Dependent = true;
2049
2050 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002051 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002052 Context.DependentTy, RParenLoc));
2053
2054 // Determine whether this is a call to an object (C++ [over.call.object]).
2055 if (Fn->getType()->isRecordType())
2056 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2057 CommaLocs, RParenLoc));
2058
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002059 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002060 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2061 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2062 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002063 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2064 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002065 }
2066
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002067 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002068 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002069 Expr *FnExpr = Fn;
2070 bool ADL = true;
2071 while (true) {
2072 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2073 FnExpr = IcExpr->getSubExpr();
2074 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002075 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002076 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002077 ADL = false;
2078 FnExpr = PExpr->getSubExpr();
2079 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002080 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002081 == UnaryOperator::AddrOf) {
2082 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002083 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2084 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2085 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2086 break;
Mike Stump9afab102009-02-19 03:04:26 +00002087 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002088 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2089 UnqualifiedName = DepName->getName();
2090 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002091 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002092 // Any kind of name that does not refer to a declaration (or
2093 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2094 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002095 break;
2096 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002097 }
Mike Stump9afab102009-02-19 03:04:26 +00002098
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002099 OverloadedFunctionDecl *Ovl = 0;
2100 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002101 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002102 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2103 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002104
Douglas Gregorfcb19192009-02-11 23:02:49 +00002105 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002106 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002107 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002108 ADL = false;
2109
Douglas Gregorfcb19192009-02-11 23:02:49 +00002110 // We don't perform ADL in C.
2111 if (!getLangOptions().CPlusPlus)
2112 ADL = false;
2113
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002114 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002115 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2116 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002117 NumArgs, CommaLocs, RParenLoc, ADL);
2118 if (!FDecl)
2119 return ExprError();
2120
2121 // Update Fn to refer to the actual function selected.
2122 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002123 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002124 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stump9afab102009-02-19 03:04:26 +00002125 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2126 QDRExpr->getLocation(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002127 false, false,
2128 QDRExpr->getSourceRange().getBegin());
2129 else
Mike Stump9afab102009-02-19 03:04:26 +00002130 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002131 Fn->getSourceRange().getBegin());
2132 Fn->Destroy(Context);
2133 Fn = NewFn;
2134 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002135 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002136
2137 // Promote the function operand.
2138 UsualUnaryConversions(Fn);
2139
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002140 // Make the call expr early, before semantic checks. This guarantees cleanup
2141 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002142 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2143 Args, NumArgs,
2144 Context.BoolTy,
2145 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002146
Steve Naroffd6163f32008-09-05 22:11:13 +00002147 const FunctionType *FuncT;
2148 if (!Fn->getType()->isBlockPointerType()) {
2149 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2150 // have type pointer to function".
2151 const PointerType *PT = Fn->getType()->getAsPointerType();
2152 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002153 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2154 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002155 FuncT = PT->getPointeeType()->getAsFunctionType();
2156 } else { // This is a block call.
2157 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2158 getAsFunctionType();
2159 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002160 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002161 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2162 << Fn->getType() << Fn->getSourceRange());
2163
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002164 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002165 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002166
Douglas Gregor4fa58902009-02-26 23:50:07 +00002167 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002168 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002169 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002170 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002171 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002172 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002173
Steve Naroffdb65e052007-08-28 23:30:39 +00002174 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002175 for (unsigned i = 0; i != NumArgs; i++) {
2176 Expr *Arg = Args[i];
2177 DefaultArgumentPromotion(Arg);
2178 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002179 }
Chris Lattner4b009652007-07-25 00:24:17 +00002180 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002181
Douglas Gregor3257fb52008-12-22 05:46:06 +00002182 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2183 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002184 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2185 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002186
Chris Lattner2e64c072007-08-10 20:18:51 +00002187 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002188 if (FDecl)
2189 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002190
Sebastian Redl8b769972009-01-19 00:08:26 +00002191 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002192}
2193
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002194Action::OwningExprResult
2195Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2196 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002197 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002198 QualType literalType = QualType::getFromOpaquePtr(Ty);
2199 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002200 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002201 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002202
Eli Friedman8c2173d2008-05-20 05:22:08 +00002203 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002204 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002205 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2206 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002207 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2208 diag::err_typecheck_decl_incomplete_type,
2209 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002210 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002211
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002212 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002213 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002214 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002215
Chris Lattnere5cb5862008-12-04 23:50:19 +00002216 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002217 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002218 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002219 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002220 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002221 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002222 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002223 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002224}
2225
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002226Action::OwningExprResult
2227Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2228 InitListDesignations &Designators,
2229 SourceLocation RBraceLoc) {
2230 unsigned NumInit = initlist.size();
2231 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002232
Steve Naroff0acc9c92007-09-15 18:49:24 +00002233 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002234 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002235
Mike Stump9afab102009-02-19 03:04:26 +00002236 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002237 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002238 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002239 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002240}
2241
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002242/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002243bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002244 UsualUnaryConversions(castExpr);
2245
2246 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2247 // type needs to be scalar.
2248 if (castType->isVoidType()) {
2249 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002250 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2251 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002252 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002253 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2254 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2255 (castType->isStructureType() || castType->isUnionType())) {
2256 // GCC struct/union extension: allow cast to self.
2257 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2258 << castType << castExpr->getSourceRange();
2259 } else if (castType->isUnionType()) {
2260 // GCC cast to union extension
2261 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2262 RecordDecl::field_iterator Field, FieldEnd;
2263 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2264 Field != FieldEnd; ++Field) {
2265 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2266 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2267 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2268 << castExpr->getSourceRange();
2269 break;
2270 }
2271 }
2272 if (Field == FieldEnd)
2273 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2274 << castExpr->getType() << castExpr->getSourceRange();
2275 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002276 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002277 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002278 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002279 }
Mike Stump9afab102009-02-19 03:04:26 +00002280 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002281 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002282 return Diag(castExpr->getLocStart(),
2283 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002284 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002285 } else if (castExpr->getType()->isVectorType()) {
2286 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2287 return true;
2288 } else if (castType->isVectorType()) {
2289 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2290 return true;
2291 }
2292 return false;
2293}
2294
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002295bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002296 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002297
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002298 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002299 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002300 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002301 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002302 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002303 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002304 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002305 } else
2306 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002307 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002308 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002309
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002310 return false;
2311}
2312
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002313Action::OwningExprResult
2314Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2315 SourceLocation RParenLoc, ExprArg Op) {
2316 assert((Ty != 0) && (Op.get() != 0) &&
2317 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002318
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002319 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002320 QualType castType = QualType::getFromOpaquePtr(Ty);
2321
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002322 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002323 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002324 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002325 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002326}
2327
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002328/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2329/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002330/// C99 6.5.15
2331QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2332 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002333 UsualUnaryConversions(Cond);
2334 UsualUnaryConversions(LHS);
2335 UsualUnaryConversions(RHS);
2336 QualType CondTy = Cond->getType();
2337 QualType LHSTy = LHS->getType();
2338 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002339
2340 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002341 if (!Cond->isTypeDependent()) {
2342 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2343 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2344 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002345 return QualType();
2346 }
Chris Lattner4b009652007-07-25 00:24:17 +00002347 }
Mike Stump9afab102009-02-19 03:04:26 +00002348
Chris Lattner992ae932008-01-06 22:42:25 +00002349 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002350 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002351 return Context.DependentTy;
2352
Chris Lattner992ae932008-01-06 22:42:25 +00002353 // If both operands have arithmetic type, do the usual arithmetic conversions
2354 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002355 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2356 UsualArithmeticConversions(LHS, RHS);
2357 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002358 }
Mike Stump9afab102009-02-19 03:04:26 +00002359
Chris Lattner992ae932008-01-06 22:42:25 +00002360 // If both operands are the same structure or union type, the result is that
2361 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002362 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2363 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002364 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002365 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002366 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002367 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002368 }
Mike Stump9afab102009-02-19 03:04:26 +00002369
Chris Lattner992ae932008-01-06 22:42:25 +00002370 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002371 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002372 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2373 if (!LHSTy->isVoidType())
2374 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2375 << RHS->getSourceRange();
2376 if (!RHSTy->isVoidType())
2377 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2378 << LHS->getSourceRange();
2379 ImpCastExprToType(LHS, Context.VoidTy);
2380 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002381 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002382 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002383 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2384 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002385 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2386 Context.isObjCObjectPointerType(LHSTy)) &&
2387 RHS->isNullPointerConstant(Context)) {
2388 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2389 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002390 }
Chris Lattnere2897262009-02-18 04:28:32 +00002391 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2392 Context.isObjCObjectPointerType(RHSTy)) &&
2393 LHS->isNullPointerConstant(Context)) {
2394 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2395 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002396 }
Mike Stump9afab102009-02-19 03:04:26 +00002397
Chris Lattner0ac51632008-01-06 22:50:31 +00002398 // Handle the case where both operands are pointers before we handle null
2399 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002400 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2401 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002402 // get the "pointed to" types
2403 QualType lhptee = LHSPT->getPointeeType();
2404 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002405
Chris Lattner71225142007-07-31 21:27:01 +00002406 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2407 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002408 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002409 // Figure out necessary qualifiers (C99 6.5.15p6)
2410 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002411 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002412 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2413 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002414 return destType;
2415 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002416 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002417 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002418 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002419 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2420 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002421 return destType;
2422 }
Chris Lattner4b009652007-07-25 00:24:17 +00002423
Chris Lattner9c039b52009-02-18 04:38:20 +00002424 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002425 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002426 return LHSTy;
2427 }
Mike Stump9afab102009-02-19 03:04:26 +00002428
Chris Lattnere2897262009-02-18 04:28:32 +00002429 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002430
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002431 // If either type is an Objective-C object type then check
2432 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002433 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002434 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002435 // If both operands are interfaces and either operand can be
2436 // assigned to the other, use that type as the composite
2437 // type. This allows
2438 // xxx ? (A*) a : (B*) b
2439 // where B is a subclass of A.
2440 //
2441 // Additionally, as for assignment, if either type is 'id'
2442 // allow silent coercion. Finally, if the types are
2443 // incompatible then make sure to use 'id' as the composite
2444 // type so the result is acceptable for sending messages to.
2445
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002446 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002447 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002448 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2449 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2450 if (LHSIface && RHSIface &&
2451 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002452 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002453 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002454 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002455 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002456 } else if (Context.isObjCIdStructType(lhptee) ||
2457 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002458 compositeType = Context.getObjCIdType();
2459 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002460 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002461 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002462 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002463 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002464 ImpCastExprToType(LHS, incompatTy);
2465 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002466 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002467 }
Mike Stump9afab102009-02-19 03:04:26 +00002468 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002469 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002470 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2471 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002472 // In this situation, we assume void* type. No especially good
2473 // reason, but this is what gcc does, and we do have to pick
2474 // to get a consistent AST.
2475 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002476 ImpCastExprToType(LHS, incompatTy);
2477 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002478 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002479 }
2480 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002481 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2482 // differently qualified versions of compatible types, the result type is
2483 // a pointer to an appropriately qualified version of the *composite*
2484 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002485 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002486 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002487 ImpCastExprToType(LHS, compositeType);
2488 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002489 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002490 }
Chris Lattner4b009652007-07-25 00:24:17 +00002491 }
Mike Stump9afab102009-02-19 03:04:26 +00002492
Chris Lattner9c039b52009-02-18 04:38:20 +00002493 // Selection between block pointer types is ok as long as they are the same.
2494 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2495 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2496 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002497
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002498 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2499 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002500 // id with statically typed objects).
2501 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002502 // GCC allows qualified id and any Objective-C type to devolve to
2503 // id. Currently localizing to here until clear this should be
2504 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002505 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002506 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002507 Context.isObjCObjectPointerType(RHSTy)) ||
2508 (RHSTy->isObjCQualifiedIdType() &&
2509 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002510 // FIXME: This is not the correct composite type. This only
2511 // happens to work because id can more or less be used anywhere,
2512 // however this may change the type of method sends.
2513 // FIXME: gcc adds some type-checking of the arguments and emits
2514 // (confusing) incompatible comparison warnings in some
2515 // cases. Investigate.
2516 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002517 ImpCastExprToType(LHS, compositeType);
2518 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002519 return compositeType;
2520 }
2521 }
2522
Chris Lattner992ae932008-01-06 22:42:25 +00002523 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002524 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2525 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002526 return QualType();
2527}
2528
Steve Naroff87d58b42007-09-16 03:34:24 +00002529/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002530/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002531Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2532 SourceLocation ColonLoc,
2533 ExprArg Cond, ExprArg LHS,
2534 ExprArg RHS) {
2535 Expr *CondExpr = (Expr *) Cond.get();
2536 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002537
2538 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2539 // was the condition.
2540 bool isLHSNull = LHSExpr == 0;
2541 if (isLHSNull)
2542 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002543
2544 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002545 RHSExpr, QuestionLoc);
2546 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002547 return ExprError();
2548
2549 Cond.release();
2550 LHS.release();
2551 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002552 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002553 isLHSNull ? 0 : LHSExpr,
2554 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002555}
2556
Chris Lattner4b009652007-07-25 00:24:17 +00002557
2558// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002559// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002560// routine is it effectively iqnores the qualifiers on the top level pointee.
2561// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2562// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002563Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002564Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2565 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002566
Chris Lattner4b009652007-07-25 00:24:17 +00002567 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002568 lhptee = lhsType->getAsPointerType()->getPointeeType();
2569 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002570
Chris Lattner4b009652007-07-25 00:24:17 +00002571 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002572 lhptee = Context.getCanonicalType(lhptee);
2573 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002574
Chris Lattner005ed752008-01-04 18:04:52 +00002575 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002576
2577 // C99 6.5.16.1p1: This following citation is common to constraints
2578 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2579 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002580 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002581 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002582 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002583
Mike Stump9afab102009-02-19 03:04:26 +00002584 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2585 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002586 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002587 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002588 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002589 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002590
Chris Lattner4ca3d772008-01-03 22:56:36 +00002591 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002592 assert(rhptee->isFunctionType());
2593 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002594 }
Mike Stump9afab102009-02-19 03:04:26 +00002595
Chris Lattner4ca3d772008-01-03 22:56:36 +00002596 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002597 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002598 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002599
2600 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002601 assert(lhptee->isFunctionType());
2602 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002603 }
Mike Stump9afab102009-02-19 03:04:26 +00002604 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002605 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002606 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002607 rhptee.getUnqualifiedType()))
2608 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002609 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002610}
2611
Steve Naroff3454b6c2008-09-04 15:10:53 +00002612/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2613/// block pointer types are compatible or whether a block and normal pointer
2614/// are compatible. It is more restrict than comparing two function pointer
2615// types.
Mike Stump9afab102009-02-19 03:04:26 +00002616Sema::AssignConvertType
2617Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002618 QualType rhsType) {
2619 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002620
Steve Naroff3454b6c2008-09-04 15:10:53 +00002621 // get the "pointed to" type (ignoring qualifiers at the top level)
2622 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002623 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2624
Steve Naroff3454b6c2008-09-04 15:10:53 +00002625 // make sure we operate on the canonical type
2626 lhptee = Context.getCanonicalType(lhptee);
2627 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002628
Steve Naroff3454b6c2008-09-04 15:10:53 +00002629 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002630
Steve Naroff3454b6c2008-09-04 15:10:53 +00002631 // For blocks we enforce that qualifiers are identical.
2632 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2633 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002634
Steve Naroff3454b6c2008-09-04 15:10:53 +00002635 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002636 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002637 return ConvTy;
2638}
2639
Mike Stump9afab102009-02-19 03:04:26 +00002640/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2641/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002642/// pointers. Here are some objectionable examples that GCC considers warnings:
2643///
2644/// int a, *pint;
2645/// short *pshort;
2646/// struct foo *pfoo;
2647///
2648/// pint = pshort; // warning: assignment from incompatible pointer type
2649/// a = pint; // warning: assignment makes integer from pointer without a cast
2650/// pint = a; // warning: assignment makes pointer from integer without a cast
2651/// pint = pfoo; // warning: assignment from incompatible pointer type
2652///
2653/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002654/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002655///
Chris Lattner005ed752008-01-04 18:04:52 +00002656Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002657Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002658 // Get canonical types. We're not formatting these types, just comparing
2659 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002660 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2661 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002662
2663 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002664 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002665
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002666 // If the left-hand side is a reference type, then we are in a
2667 // (rare!) case where we've allowed the use of references in C,
2668 // e.g., as a parameter type in a built-in function. In this case,
2669 // just make sure that the type referenced is compatible with the
2670 // right-hand side type. The caller is responsible for adjusting
2671 // lhsType so that the resulting expression does not have reference
2672 // type.
2673 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2674 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002675 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002676 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002677 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002678
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002679 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2680 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002681 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002682 // Relax integer conversions like we do for pointers below.
2683 if (rhsType->isIntegerType())
2684 return IntToPointer;
2685 if (lhsType->isIntegerType())
2686 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002687 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002688 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002689
Nate Begemanc5f0f652008-07-14 18:02:46 +00002690 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002691 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002692 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2693 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002694 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002695
Nate Begemanc5f0f652008-07-14 18:02:46 +00002696 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002697 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002698 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002699 if (getLangOptions().LaxVectorConversions &&
2700 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002701 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002702 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002703 }
2704 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002705 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002706
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002707 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002708 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002709
Chris Lattner390564e2008-04-07 06:49:41 +00002710 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002711 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002712 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002713
Chris Lattner390564e2008-04-07 06:49:41 +00002714 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002715 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002716
Steve Naroffa982c712008-09-29 18:10:17 +00002717 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002718 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002719 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002720
2721 // Treat block pointers as objects.
2722 if (getLangOptions().ObjC1 &&
2723 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2724 return Compatible;
2725 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002726 return Incompatible;
2727 }
2728
2729 if (isa<BlockPointerType>(lhsType)) {
2730 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002731 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002732
Steve Naroffa982c712008-09-29 18:10:17 +00002733 // Treat block pointers as objects.
2734 if (getLangOptions().ObjC1 &&
2735 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2736 return Compatible;
2737
Steve Naroff3454b6c2008-09-04 15:10:53 +00002738 if (rhsType->isBlockPointerType())
2739 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002740
Steve Naroff3454b6c2008-09-04 15:10:53 +00002741 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2742 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002743 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002744 }
Chris Lattner1853da22008-01-04 23:18:45 +00002745 return Incompatible;
2746 }
2747
Chris Lattner390564e2008-04-07 06:49:41 +00002748 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002749 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002750 if (lhsType == Context.BoolTy)
2751 return Compatible;
2752
2753 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002754 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002755
Mike Stump9afab102009-02-19 03:04:26 +00002756 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002757 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002758
2759 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002760 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002761 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002762 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002763 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002764
Chris Lattner1853da22008-01-04 23:18:45 +00002765 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002766 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002767 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002768 }
2769 return Incompatible;
2770}
2771
Chris Lattner005ed752008-01-04 18:04:52 +00002772Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002773Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002774 if (getLangOptions().CPlusPlus) {
2775 if (!lhsType->isRecordType()) {
2776 // C++ 5.17p3: If the left operand is not of class type, the
2777 // expression is implicitly converted (C++ 4) to the
2778 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002779 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2780 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002781 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002782 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002783 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002784 }
2785
2786 // FIXME: Currently, we fall through and treat C++ classes like C
2787 // structures.
2788 }
2789
Steve Naroffcdee22d2007-11-27 17:58:44 +00002790 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2791 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002792 if ((lhsType->isPointerType() ||
2793 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002794 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002795 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002796 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002797 return Compatible;
2798 }
Mike Stump9afab102009-02-19 03:04:26 +00002799
Chris Lattner5f505bf2007-10-16 02:55:40 +00002800 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002801 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002802 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002803 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002804 //
Mike Stump9afab102009-02-19 03:04:26 +00002805 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002806 if (!lhsType->isReferenceType())
2807 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002808
Chris Lattner005ed752008-01-04 18:04:52 +00002809 Sema::AssignConvertType result =
2810 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002811
Steve Naroff0f32f432007-08-24 22:33:52 +00002812 // C99 6.5.16.1p2: The value of the right operand is converted to the
2813 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002814 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2815 // so that we can use references in built-in functions even in C.
2816 // The getNonReferenceType() call makes sure that the resulting expression
2817 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002818 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002819 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002820 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002821}
2822
Chris Lattner005ed752008-01-04 18:04:52 +00002823Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002824Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2825 return CheckAssignmentConstraints(lhsType, rhsType);
2826}
2827
Chris Lattner1eafdea2008-11-18 01:30:42 +00002828QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002829 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002830 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002831 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002832 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002833}
2834
Mike Stump9afab102009-02-19 03:04:26 +00002835inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002836 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002837 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002838 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002839 QualType lhsType =
2840 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2841 QualType rhsType =
2842 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002843
Nate Begemanc5f0f652008-07-14 18:02:46 +00002844 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002845 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002846 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002847
Nate Begemanc5f0f652008-07-14 18:02:46 +00002848 // Handle the case of a vector & extvector type of the same size and element
2849 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002850 if (getLangOptions().LaxVectorConversions) {
2851 // FIXME: Should we warn here?
2852 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002853 if (const VectorType *RV = rhsType->getAsVectorType())
2854 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002855 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002856 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002857 }
2858 }
2859 }
Mike Stump9afab102009-02-19 03:04:26 +00002860
Nate Begemanc5f0f652008-07-14 18:02:46 +00002861 // If the lhs is an extended vector and the rhs is a scalar of the same type
2862 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002863 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002864 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002865
2866 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002867 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2868 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002869 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002870 return lhsType;
2871 }
2872 }
2873
Nate Begemanc5f0f652008-07-14 18:02:46 +00002874 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002875 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002876 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002877 QualType eltType = V->getElementType();
2878
Mike Stump9afab102009-02-19 03:04:26 +00002879 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002880 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2881 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002882 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002883 return rhsType;
2884 }
2885 }
2886
Chris Lattner4b009652007-07-25 00:24:17 +00002887 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002888 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002889 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002890 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002891 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002892}
2893
Chris Lattner4b009652007-07-25 00:24:17 +00002894inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002895 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002896{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002897 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002898 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002899
Steve Naroff8f708362007-08-24 19:07:16 +00002900 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002901
Chris Lattner4b009652007-07-25 00:24:17 +00002902 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002903 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002904 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002905}
2906
2907inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002908 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002909{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002910 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2911 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2912 return CheckVectorOperands(Loc, lex, rex);
2913 return InvalidOperands(Loc, lex, rex);
2914 }
Chris Lattner4b009652007-07-25 00:24:17 +00002915
Steve Naroff8f708362007-08-24 19:07:16 +00002916 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002917
Chris Lattner4b009652007-07-25 00:24:17 +00002918 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002919 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002920 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002921}
2922
2923inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00002924 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002925{
2926 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002927 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002928
Steve Naroff8f708362007-08-24 19:07:16 +00002929 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002930
Chris Lattner4b009652007-07-25 00:24:17 +00002931 // handle the common case first (both operands are arithmetic).
2932 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002933 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002934
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002935 // Put any potential pointer into PExp
2936 Expr* PExp = lex, *IExp = rex;
2937 if (IExp->getType()->isPointerType())
2938 std::swap(PExp, IExp);
2939
2940 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2941 if (IExp->getType()->isIntegerType()) {
2942 // Check for arithmetic on pointers to incomplete types
2943 if (!PTy->getPointeeType()->isObjectType()) {
2944 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002945 if (getLangOptions().CPlusPlus) {
2946 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2947 << lex->getSourceRange() << rex->getSourceRange();
2948 return QualType();
2949 }
2950
2951 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002952 Diag(Loc, diag::ext_gnu_void_ptr)
2953 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002954 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002955 if (getLangOptions().CPlusPlus) {
2956 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2957 << lex->getType() << lex->getSourceRange();
2958 return QualType();
2959 }
2960
2961 // GNU extension: arithmetic on pointer to function
2962 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002963 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002964 } else {
Mike Stump9afab102009-02-19 03:04:26 +00002965 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002966 diag::err_typecheck_arithmetic_incomplete_type,
2967 lex->getSourceRange(), SourceRange(),
2968 lex->getType());
2969 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002970 }
2971 }
2972 return PExp->getType();
2973 }
2974 }
2975
Chris Lattner1eafdea2008-11-18 01:30:42 +00002976 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002977}
2978
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002979// C99 6.5.6
2980QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002981 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002982 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002983 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002984
Steve Naroff8f708362007-08-24 19:07:16 +00002985 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002986
Chris Lattnerf6da2912007-12-09 21:53:25 +00002987 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00002988
Chris Lattnerf6da2912007-12-09 21:53:25 +00002989 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002990 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002991 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00002992
Chris Lattnerf6da2912007-12-09 21:53:25 +00002993 // Either ptr - int or ptr - ptr.
2994 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002995 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002996
Chris Lattnerf6da2912007-12-09 21:53:25 +00002997 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002998 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002999 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003000 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003001 Diag(Loc, diag::ext_gnu_void_ptr)
3002 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00003003 } else if (lpointee->isFunctionType()) {
3004 if (getLangOptions().CPlusPlus) {
3005 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3006 << lex->getType() << lex->getSourceRange();
3007 return QualType();
3008 }
3009
3010 // GNU extension: arithmetic on pointer to function
3011 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3012 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003013 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003014 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003015 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003016 return QualType();
3017 }
3018 }
3019
3020 // The result type of a pointer-int computation is the pointer type.
3021 if (rex->getType()->isIntegerType())
3022 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003023
Chris Lattnerf6da2912007-12-09 21:53:25 +00003024 // Handle pointer-pointer subtractions.
3025 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003026 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003027
Chris Lattnerf6da2912007-12-09 21:53:25 +00003028 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00003029 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003030 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003031 if (rpointee->isVoidType()) {
3032 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00003033 Diag(Loc, diag::ext_gnu_void_ptr)
3034 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00003035 } else if (rpointee->isFunctionType()) {
3036 if (getLangOptions().CPlusPlus) {
3037 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3038 << rex->getType() << rex->getSourceRange();
3039 return QualType();
3040 }
Mike Stump9afab102009-02-19 03:04:26 +00003041
Douglas Gregorf93eda12009-01-23 19:03:35 +00003042 // GNU extension: arithmetic on pointer to function
3043 if (!lpointee->isFunctionType())
3044 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3045 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003046 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003047 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003048 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003049 return QualType();
3050 }
3051 }
Mike Stump9afab102009-02-19 03:04:26 +00003052
Chris Lattnerf6da2912007-12-09 21:53:25 +00003053 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003054 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003055 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003056 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003057 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003058 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003059 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003060 return QualType();
3061 }
Mike Stump9afab102009-02-19 03:04:26 +00003062
Chris Lattnerf6da2912007-12-09 21:53:25 +00003063 return Context.getPointerDiffType();
3064 }
3065 }
Mike Stump9afab102009-02-19 03:04:26 +00003066
Chris Lattner1eafdea2008-11-18 01:30:42 +00003067 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003068}
3069
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003070// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003071QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003072 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003073 // C99 6.5.7p2: Each of the operands shall have integer type.
3074 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003075 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003076
Chris Lattner2c8bff72007-12-12 05:47:28 +00003077 // Shifts don't perform usual arithmetic conversions, they just do integer
3078 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003079 if (!isCompAssign)
3080 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003081 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003082
Chris Lattner2c8bff72007-12-12 05:47:28 +00003083 // "The type of the result is that of the promoted left operand."
3084 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003085}
3086
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003087// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003088QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003089 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003090 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003091 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003092
Chris Lattner254f3bc2007-08-26 01:18:55 +00003093 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003094 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3095 UsualArithmeticConversions(lex, rex);
3096 else {
3097 UsualUnaryConversions(lex);
3098 UsualUnaryConversions(rex);
3099 }
Chris Lattner4b009652007-07-25 00:24:17 +00003100 QualType lType = lex->getType();
3101 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003102
Ted Kremenek486509e2007-10-29 17:13:39 +00003103 // For non-floating point types, check for self-comparisons of the form
3104 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3105 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003106 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003107 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3108 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003109 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003110 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003111 }
Mike Stump9afab102009-02-19 03:04:26 +00003112
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003113 // The result of comparisons is 'bool' in C++, 'int' in C.
3114 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3115
Chris Lattner254f3bc2007-08-26 01:18:55 +00003116 if (isRelational) {
3117 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003118 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003119 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003120 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003121 if (lType->isFloatingType()) {
3122 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003123 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003124 }
Mike Stump9afab102009-02-19 03:04:26 +00003125
Chris Lattner254f3bc2007-08-26 01:18:55 +00003126 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003127 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003128 }
Mike Stump9afab102009-02-19 03:04:26 +00003129
Chris Lattner22be8422007-08-26 01:10:14 +00003130 bool LHSIsNull = lex->isNullPointerConstant(Context);
3131 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003132
Chris Lattner254f3bc2007-08-26 01:18:55 +00003133 // All of the following pointer related warnings are GCC extensions, except
3134 // when handling null pointer constants. One day, we can consider making them
3135 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003136 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003137 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003138 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003139 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003140 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003141
Steve Naroff3b435622007-11-13 14:57:38 +00003142 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003143 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3144 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003145 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003146 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003147 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003148 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003149 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003150 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003151 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003152 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003153 // Handle block pointer types.
3154 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3155 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3156 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003157
Steve Naroff3454b6c2008-09-04 15:10:53 +00003158 if (!LHSIsNull && !RHSIsNull &&
3159 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003160 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003161 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003162 }
3163 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003164 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003165 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003166 // Allow block pointers to be compared with null pointer constants.
3167 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3168 (lType->isPointerType() && rType->isBlockPointerType())) {
3169 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003170 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003171 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003172 }
3173 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003174 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003175 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003176
Steve Naroff936c4362008-06-03 14:04:54 +00003177 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003178 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003179 const PointerType *LPT = lType->getAsPointerType();
3180 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003181 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003182 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003183 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003184 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003185
Steve Naroff030fcda2008-11-17 19:49:16 +00003186 if (!LPtrToVoid && !RPtrToVoid &&
3187 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003188 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003189 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003190 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003191 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003192 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003193 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003194 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003195 }
Steve Naroff936c4362008-06-03 14:04:54 +00003196 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3197 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003198 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003199 } else {
3200 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003201 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003202 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003203 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003204 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003205 }
Steve Naroff936c4362008-06-03 14:04:54 +00003206 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003207 }
Mike Stump9afab102009-02-19 03:04:26 +00003208 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003209 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003210 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003211 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003212 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003213 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003214 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003215 }
Mike Stump9afab102009-02-19 03:04:26 +00003216 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003217 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003218 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003219 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003220 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003221 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003222 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003223 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003224 // Handle block pointers.
3225 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3226 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003227 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003228 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003229 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003230 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003231 }
3232 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3233 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003234 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003235 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003236 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003237 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003238 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003239 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003240}
3241
Nate Begemanc5f0f652008-07-14 18:02:46 +00003242/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003243/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003244/// like a scalar comparison, a vector comparison produces a vector of integer
3245/// types.
3246QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003247 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003248 bool isRelational) {
3249 // Check to make sure we're operating on vectors of the same type and width,
3250 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003251 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003252 if (vType.isNull())
3253 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003254
Nate Begemanc5f0f652008-07-14 18:02:46 +00003255 QualType lType = lex->getType();
3256 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003257
Nate Begemanc5f0f652008-07-14 18:02:46 +00003258 // For non-floating point types, check for self-comparisons of the form
3259 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3260 // often indicate logic errors in the program.
3261 if (!lType->isFloatingType()) {
3262 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3263 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3264 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003265 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003266 }
Mike Stump9afab102009-02-19 03:04:26 +00003267
Nate Begemanc5f0f652008-07-14 18:02:46 +00003268 // Check for comparisons of floating point operands using != and ==.
3269 if (!isRelational && lType->isFloatingType()) {
3270 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003271 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003272 }
Mike Stump9afab102009-02-19 03:04:26 +00003273
Nate Begemanc5f0f652008-07-14 18:02:46 +00003274 // Return the type for the comparison, which is the same as vector type for
3275 // integer vectors, or an integer type of identical size and number of
3276 // elements for floating point vectors.
3277 if (lType->isIntegerType())
3278 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003279
Nate Begemanc5f0f652008-07-14 18:02:46 +00003280 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003281 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003282 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003283 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003284 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3285 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3286
Mike Stump9afab102009-02-19 03:04:26 +00003287 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003288 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003289 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3290}
3291
Chris Lattner4b009652007-07-25 00:24:17 +00003292inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003293 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003294{
3295 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003296 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003297
Steve Naroff8f708362007-08-24 19:07:16 +00003298 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003299
Chris Lattner4b009652007-07-25 00:24:17 +00003300 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003301 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003302 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003303}
3304
3305inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003306 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003307{
3308 UsualUnaryConversions(lex);
3309 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003310
Eli Friedmanbea3f842008-05-13 20:16:47 +00003311 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003312 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003313 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003314}
3315
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003316/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3317/// is a read-only property; return true if so. A readonly property expression
3318/// depends on various declarations and thus must be treated specially.
3319///
Mike Stump9afab102009-02-19 03:04:26 +00003320static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003321{
3322 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3323 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3324 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3325 QualType BaseType = PropExpr->getBase()->getType();
3326 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003327 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003328 PTy->getPointeeType()->getAsObjCInterfaceType())
3329 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3330 if (S.isPropertyReadonly(PDecl, IFace))
3331 return true;
3332 }
3333 }
3334 return false;
3335}
3336
Chris Lattner4c2642c2008-11-18 01:22:49 +00003337/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3338/// emit an error and return true. If so, return false.
3339static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003340 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3341 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3342 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003343 if (IsLV == Expr::MLV_Valid)
3344 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003345
Chris Lattner4c2642c2008-11-18 01:22:49 +00003346 unsigned Diag = 0;
3347 bool NeedType = false;
3348 switch (IsLV) { // C99 6.5.16p2
3349 default: assert(0 && "Unknown result from isModifiableLvalue!");
3350 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003351 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003352 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3353 NeedType = true;
3354 break;
Mike Stump9afab102009-02-19 03:04:26 +00003355 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003356 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3357 NeedType = true;
3358 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003359 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003360 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3361 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003362 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003363 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3364 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003365 case Expr::MLV_IncompleteType:
3366 case Expr::MLV_IncompleteVoidType:
Mike Stump9afab102009-02-19 03:04:26 +00003367 return S.DiagnoseIncompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003368 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3369 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003370 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003371 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3372 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003373 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003374 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3375 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003376 case Expr::MLV_ReadonlyProperty:
3377 Diag = diag::error_readonly_property_assignment;
3378 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003379 case Expr::MLV_NoSetterProperty:
3380 Diag = diag::error_nosetter_property_assignment;
3381 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003382 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003383
Chris Lattner4c2642c2008-11-18 01:22:49 +00003384 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003385 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003386 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003387 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003388 return true;
3389}
3390
3391
3392
3393// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003394QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3395 SourceLocation Loc,
3396 QualType CompoundType) {
3397 // Verify that LHS is a modifiable lvalue, and emit error if not.
3398 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003399 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003400
3401 QualType LHSType = LHS->getType();
3402 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003403
Chris Lattner005ed752008-01-04 18:04:52 +00003404 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003405 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003406 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003407 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003408 // Special case of NSObject attributes on c-style pointer types.
3409 if (ConvTy == IncompatiblePointer &&
3410 ((Context.isObjCNSObjectType(LHSType) &&
3411 Context.isObjCObjectPointerType(RHSType)) ||
3412 (Context.isObjCNSObjectType(RHSType) &&
3413 Context.isObjCObjectPointerType(LHSType))))
3414 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003415
Chris Lattner34c85082008-08-21 18:04:13 +00003416 // If the RHS is a unary plus or minus, check to see if they = and + are
3417 // right next to each other. If so, the user may have typo'd "x =+ 4"
3418 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003419 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003420 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3421 RHSCheck = ICE->getSubExpr();
3422 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3423 if ((UO->getOpcode() == UnaryOperator::Plus ||
3424 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003425 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003426 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003427 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003428 Diag(Loc, diag::warn_not_compound_assign)
3429 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3430 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003431 }
3432 } else {
3433 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003434 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003435 }
Chris Lattner005ed752008-01-04 18:04:52 +00003436
Chris Lattner1eafdea2008-11-18 01:30:42 +00003437 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3438 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003439 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003440
Chris Lattner4b009652007-07-25 00:24:17 +00003441 // C99 6.5.16p3: The type of an assignment expression is the type of the
3442 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003443 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003444 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3445 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003446 // C++ 5.17p1: the type of the assignment expression is that of its left
3447 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003448 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003449}
3450
Chris Lattner1eafdea2008-11-18 01:30:42 +00003451// C99 6.5.17
3452QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3453 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003454
Chris Lattner03c430f2008-07-25 20:54:07 +00003455 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003456 DefaultFunctionArrayConversion(RHS);
3457 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003458}
3459
3460/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3461/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003462QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3463 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003464 if (Op->isTypeDependent())
3465 return Context.DependentTy;
3466
Chris Lattnere65182c2008-11-21 07:05:48 +00003467 QualType ResType = Op->getType();
3468 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003469
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003470 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3471 // Decrement of bool is not allowed.
3472 if (!isInc) {
3473 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3474 return QualType();
3475 }
3476 // Increment of bool sets it to true, but is deprecated.
3477 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3478 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003479 // OK!
3480 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3481 // C99 6.5.2.4p2, 6.5.6p2
3482 if (PT->getPointeeType()->isObjectType()) {
3483 // Pointer to object is ok!
3484 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003485 if (getLangOptions().CPlusPlus) {
3486 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3487 << Op->getSourceRange();
3488 return QualType();
3489 }
3490
3491 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003492 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003493 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003494 if (getLangOptions().CPlusPlus) {
3495 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3496 << Op->getType() << Op->getSourceRange();
3497 return QualType();
3498 }
3499
3500 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003501 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003502 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003503 } else {
Mike Stump9afab102009-02-19 03:04:26 +00003504 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003505 diag::err_typecheck_arithmetic_incomplete_type,
3506 Op->getSourceRange(), SourceRange(),
3507 ResType);
3508 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003509 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003510 } else if (ResType->isComplexType()) {
3511 // C99 does not support ++/-- on complex types, we allow as an extension.
3512 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003513 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003514 } else {
3515 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003516 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003517 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003518 }
Mike Stump9afab102009-02-19 03:04:26 +00003519 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003520 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003521 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003522 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003523 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003524}
3525
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003526/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003527/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003528/// where the declaration is needed for type checking. We only need to
3529/// handle cases when the expression references a function designator
3530/// or is an lvalue. Here are some examples:
3531/// - &(x) => x
3532/// - &*****f => f for f a function designator.
3533/// - &s.xx => s
3534/// - &s.zz[1].yy -> s, if zz is an array
3535/// - *(x + 1) -> x, if x is an array
3536/// - &"123"[2] -> 0
3537/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003538static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003539 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003540 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003541 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003542 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003543 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003544 // Fields cannot be declared with a 'register' storage class.
3545 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003546 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003547 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003548 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003549 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003550 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003551
Douglas Gregord2baafd2008-10-21 16:13:35 +00003552 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003553 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003554 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003555 return 0;
3556 else
3557 return VD;
3558 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003559 case Stmt::UnaryOperatorClass: {
3560 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003561
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003562 switch(UO->getOpcode()) {
3563 case UnaryOperator::Deref: {
3564 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003565 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3566 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3567 if (!VD || VD->getType()->isPointerType())
3568 return 0;
3569 return VD;
3570 }
3571 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003572 }
3573 case UnaryOperator::Real:
3574 case UnaryOperator::Imag:
3575 case UnaryOperator::Extension:
3576 return getPrimaryDecl(UO->getSubExpr());
3577 default:
3578 return 0;
3579 }
3580 }
3581 case Stmt::BinaryOperatorClass: {
3582 BinaryOperator *BO = cast<BinaryOperator>(E);
3583
3584 // Handle cases involving pointer arithmetic. The result of an
3585 // Assign or AddAssign is not an lvalue so they can be ignored.
3586
3587 // (x + n) or (n + x) => x
3588 if (BO->getOpcode() == BinaryOperator::Add) {
3589 if (BO->getLHS()->getType()->isPointerType()) {
3590 return getPrimaryDecl(BO->getLHS());
3591 } else if (BO->getRHS()->getType()->isPointerType()) {
3592 return getPrimaryDecl(BO->getRHS());
3593 }
3594 }
3595
3596 return 0;
3597 }
Chris Lattner4b009652007-07-25 00:24:17 +00003598 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003599 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003600 case Stmt::ImplicitCastExprClass:
3601 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003602 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003603 default:
3604 return 0;
3605 }
3606}
3607
3608/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003609/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003610/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003611/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003612/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003613/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003614/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003615QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003616 if (op->isTypeDependent())
3617 return Context.DependentTy;
3618
Steve Naroff9c6c3592008-01-13 17:10:08 +00003619 if (getLangOptions().C99) {
3620 // Implement C99-only parts of addressof rules.
3621 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3622 if (uOp->getOpcode() == UnaryOperator::Deref)
3623 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3624 // (assuming the deref expression is valid).
3625 return uOp->getSubExpr()->getType();
3626 }
3627 // Technically, there should be a check for array subscript
3628 // expressions here, but the result of one is always an lvalue anyway.
3629 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003630 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003631 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003632
Chris Lattner4b009652007-07-25 00:24:17 +00003633 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003634 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3635 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003636 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3637 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003638 return QualType();
3639 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003640 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003641 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3642 if (Field->isBitField()) {
3643 Diag(OpLoc, diag::err_typecheck_address_of)
3644 << "bit-field" << op->getSourceRange();
3645 return QualType();
3646 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003647 }
3648 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003649 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3650 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003651 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003652 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003653 return QualType();
3654 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003655 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003656 // with the register storage-class specifier.
3657 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3658 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003659 Diag(OpLoc, diag::err_typecheck_address_of)
3660 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003661 return QualType();
3662 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003663 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003664 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003665 } else if (isa<FieldDecl>(dcl)) {
3666 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003667 // Could be a pointer to member, though, if there is an explicit
3668 // scope qualifier for the class.
3669 if (isa<QualifiedDeclRefExpr>(op)) {
3670 DeclContext *Ctx = dcl->getDeclContext();
3671 if (Ctx && Ctx->isRecord())
3672 return Context.getMemberPointerType(op->getType(),
3673 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3674 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003675 } else if (isa<FunctionDecl>(dcl)) {
3676 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003677 // As above.
3678 if (isa<QualifiedDeclRefExpr>(op)) {
3679 DeclContext *Ctx = dcl->getDeclContext();
3680 if (Ctx && Ctx->isRecord())
3681 return Context.getMemberPointerType(op->getType(),
3682 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3683 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003684 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003685 else
Chris Lattner4b009652007-07-25 00:24:17 +00003686 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003687 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003688
Chris Lattner4b009652007-07-25 00:24:17 +00003689 // If the operand has type "type", the result has type "pointer to type".
3690 return Context.getPointerType(op->getType());
3691}
3692
Chris Lattnerda5c0872008-11-23 09:13:29 +00003693QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003694 if (Op->isTypeDependent())
3695 return Context.DependentTy;
3696
Chris Lattnerda5c0872008-11-23 09:13:29 +00003697 UsualUnaryConversions(Op);
3698 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003699
Chris Lattnerda5c0872008-11-23 09:13:29 +00003700 // Note that per both C89 and C99, this is always legal, even if ptype is an
3701 // incomplete type or void. It would be possible to warn about dereferencing
3702 // a void pointer, but it's completely well-defined, and such a warning is
3703 // unlikely to catch any mistakes.
3704 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003705 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003706
Chris Lattner77d52da2008-11-20 06:06:08 +00003707 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003708 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003709 return QualType();
3710}
3711
3712static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3713 tok::TokenKind Kind) {
3714 BinaryOperator::Opcode Opc;
3715 switch (Kind) {
3716 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003717 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3718 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003719 case tok::star: Opc = BinaryOperator::Mul; break;
3720 case tok::slash: Opc = BinaryOperator::Div; break;
3721 case tok::percent: Opc = BinaryOperator::Rem; break;
3722 case tok::plus: Opc = BinaryOperator::Add; break;
3723 case tok::minus: Opc = BinaryOperator::Sub; break;
3724 case tok::lessless: Opc = BinaryOperator::Shl; break;
3725 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3726 case tok::lessequal: Opc = BinaryOperator::LE; break;
3727 case tok::less: Opc = BinaryOperator::LT; break;
3728 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3729 case tok::greater: Opc = BinaryOperator::GT; break;
3730 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3731 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3732 case tok::amp: Opc = BinaryOperator::And; break;
3733 case tok::caret: Opc = BinaryOperator::Xor; break;
3734 case tok::pipe: Opc = BinaryOperator::Or; break;
3735 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3736 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3737 case tok::equal: Opc = BinaryOperator::Assign; break;
3738 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3739 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3740 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3741 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3742 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3743 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3744 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3745 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3746 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3747 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3748 case tok::comma: Opc = BinaryOperator::Comma; break;
3749 }
3750 return Opc;
3751}
3752
3753static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3754 tok::TokenKind Kind) {
3755 UnaryOperator::Opcode Opc;
3756 switch (Kind) {
3757 default: assert(0 && "Unknown unary op!");
3758 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3759 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3760 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3761 case tok::star: Opc = UnaryOperator::Deref; break;
3762 case tok::plus: Opc = UnaryOperator::Plus; break;
3763 case tok::minus: Opc = UnaryOperator::Minus; break;
3764 case tok::tilde: Opc = UnaryOperator::Not; break;
3765 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003766 case tok::kw___real: Opc = UnaryOperator::Real; break;
3767 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3768 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3769 }
3770 return Opc;
3771}
3772
Douglas Gregord7f915e2008-11-06 23:29:22 +00003773/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3774/// operator @p Opc at location @c TokLoc. This routine only supports
3775/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003776Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3777 unsigned Op,
3778 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003779 QualType ResultTy; // Result type of the binary operator.
3780 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3781 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3782
3783 switch (Opc) {
3784 default:
3785 assert(0 && "Unknown binary expr!");
3786 case BinaryOperator::Assign:
3787 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3788 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003789 case BinaryOperator::PtrMemD:
3790 case BinaryOperator::PtrMemI:
3791 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3792 Opc == BinaryOperator::PtrMemI);
3793 break;
3794 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003795 case BinaryOperator::Div:
3796 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3797 break;
3798 case BinaryOperator::Rem:
3799 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3800 break;
3801 case BinaryOperator::Add:
3802 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3803 break;
3804 case BinaryOperator::Sub:
3805 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3806 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003807 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003808 case BinaryOperator::Shr:
3809 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3810 break;
3811 case BinaryOperator::LE:
3812 case BinaryOperator::LT:
3813 case BinaryOperator::GE:
3814 case BinaryOperator::GT:
3815 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3816 break;
3817 case BinaryOperator::EQ:
3818 case BinaryOperator::NE:
3819 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3820 break;
3821 case BinaryOperator::And:
3822 case BinaryOperator::Xor:
3823 case BinaryOperator::Or:
3824 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3825 break;
3826 case BinaryOperator::LAnd:
3827 case BinaryOperator::LOr:
3828 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3829 break;
3830 case BinaryOperator::MulAssign:
3831 case BinaryOperator::DivAssign:
3832 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3833 if (!CompTy.isNull())
3834 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3835 break;
3836 case BinaryOperator::RemAssign:
3837 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3838 if (!CompTy.isNull())
3839 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3840 break;
3841 case BinaryOperator::AddAssign:
3842 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3843 if (!CompTy.isNull())
3844 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3845 break;
3846 case BinaryOperator::SubAssign:
3847 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3848 if (!CompTy.isNull())
3849 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3850 break;
3851 case BinaryOperator::ShlAssign:
3852 case BinaryOperator::ShrAssign:
3853 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3854 if (!CompTy.isNull())
3855 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3856 break;
3857 case BinaryOperator::AndAssign:
3858 case BinaryOperator::XorAssign:
3859 case BinaryOperator::OrAssign:
3860 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3861 if (!CompTy.isNull())
3862 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3863 break;
3864 case BinaryOperator::Comma:
3865 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3866 break;
3867 }
3868 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003869 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003870 if (CompTy.isNull())
3871 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3872 else
3873 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00003874 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003875}
3876
Chris Lattner4b009652007-07-25 00:24:17 +00003877// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003878Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3879 tok::TokenKind Kind,
3880 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003881 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003882 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003883
Steve Naroff87d58b42007-09-16 03:34:24 +00003884 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3885 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003886
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003887 // If either expression is type-dependent, just build the AST.
3888 // FIXME: We'll need to perform some caching of the result of name
3889 // lookup for operator+.
3890 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003891 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3892 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003893 Context.DependentTy,
3894 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003895 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003896 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3897 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003898 }
3899
Sebastian Redl95216a62009-02-07 00:15:38 +00003900 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003901 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3902 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003903 // If this is one of the assignment operators, we only perform
3904 // overload resolution if the left-hand side is a class or
3905 // enumeration type (C++ [expr.ass]p3).
3906 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3907 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3908 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3909 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003910
Douglas Gregord7f915e2008-11-06 23:29:22 +00003911 // Determine which overloaded operator we're dealing with.
3912 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003913 // Overloading .* is not possible.
3914 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003915 OO_Star, OO_Slash, OO_Percent,
3916 OO_Plus, OO_Minus,
3917 OO_LessLess, OO_GreaterGreater,
3918 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3919 OO_EqualEqual, OO_ExclaimEqual,
3920 OO_Amp,
3921 OO_Caret,
3922 OO_Pipe,
3923 OO_AmpAmp,
3924 OO_PipePipe,
3925 OO_Equal, OO_StarEqual,
3926 OO_SlashEqual, OO_PercentEqual,
3927 OO_PlusEqual, OO_MinusEqual,
3928 OO_LessLessEqual, OO_GreaterGreaterEqual,
3929 OO_AmpEqual, OO_CaretEqual,
3930 OO_PipeEqual,
3931 OO_Comma
3932 };
3933 OverloadedOperatorKind OverOp = OverOps[Opc];
3934
Mike Stump9afab102009-02-19 03:04:26 +00003935 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor5ed15042008-11-18 23:14:02 +00003936 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003937 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003938 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003939 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3940 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003941
3942 // Perform overload resolution.
3943 OverloadCandidateSet::iterator Best;
3944 switch (BestViableFunction(CandidateSet, Best)) {
3945 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003946 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003947 FunctionDecl *FnDecl = Best->Function;
3948
Douglas Gregor70d26122008-11-12 17:17:38 +00003949 if (FnDecl) {
3950 // We matched an overloaded operator. Build a call to that
3951 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003952
Douglas Gregor70d26122008-11-12 17:17:38 +00003953 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003954 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3955 if (PerformObjectArgumentInitialization(lhs, Method) ||
3956 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3957 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003958 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003959 } else {
3960 // Convert the arguments.
3961 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3962 "passing") ||
3963 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3964 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003965 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003966 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003967
Douglas Gregor70d26122008-11-12 17:17:38 +00003968 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003969 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003970 = FnDecl->getType()->getAsFunctionType()->getResultType();
3971 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003972
Douglas Gregor70d26122008-11-12 17:17:38 +00003973 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003974 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3975 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003976 UsualUnaryConversions(FnExpr);
3977
Mike Stump9afab102009-02-19 03:04:26 +00003978 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003979 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003980 } else {
3981 // We matched a built-in operator. Convert the arguments, then
3982 // break out so that we will build the appropriate built-in
3983 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003984 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3985 Best->Conversions[0], "passing") ||
3986 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3987 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003988 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003989
3990 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003991 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003992 }
3993
3994 case OR_No_Viable_Function:
3995 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003996 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003997 break;
3998
3999 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00004000 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
4001 << BinaryOperator::getOpcodeStr(Opc)
4002 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00004003 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004004 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004005
4006 case OR_Deleted:
4007 Diag(TokLoc, diag::err_ovl_deleted_oper)
4008 << Best->Function->isDeleted()
4009 << BinaryOperator::getOpcodeStr(Opc)
4010 << lhs->getSourceRange() << rhs->getSourceRange();
4011 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4012 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00004013 }
4014
Douglas Gregor70d26122008-11-12 17:17:38 +00004015 // Either we found no viable overloaded operator or we matched a
4016 // built-in operator. In either case, fall through to trying to
4017 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004018 }
4019
Douglas Gregord7f915e2008-11-06 23:29:22 +00004020 // Build a built-in binary operation.
4021 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004022}
4023
4024// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00004025Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4026 tok::TokenKind Op, ExprArg input) {
4027 // FIXME: Input is modified later, but smart pointer not reassigned.
4028 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004029 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004030
4031 if (getLangOptions().CPlusPlus &&
Mike Stump9afab102009-02-19 03:04:26 +00004032 (Input->getType()->isRecordType()
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004033 || Input->getType()->isEnumeralType())) {
4034 // Determine which overloaded operator we're dealing with.
4035 static const OverloadedOperatorKind OverOps[] = {
4036 OO_None, OO_None,
4037 OO_PlusPlus, OO_MinusMinus,
4038 OO_Amp, OO_Star,
4039 OO_Plus, OO_Minus,
4040 OO_Tilde, OO_Exclaim,
4041 OO_None, OO_None,
Mike Stump9afab102009-02-19 03:04:26 +00004042 OO_None,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004043 OO_None
4044 };
4045 OverloadedOperatorKind OverOp = OverOps[Opc];
4046
Mike Stump9afab102009-02-19 03:04:26 +00004047 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004048 // to the candidate set.
4049 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00004050 if (OverOp != OO_None &&
4051 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4052 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004053
4054 // Perform overload resolution.
4055 OverloadCandidateSet::iterator Best;
4056 switch (BestViableFunction(CandidateSet, Best)) {
4057 case OR_Success: {
4058 // We found a built-in operator or an overloaded operator.
4059 FunctionDecl *FnDecl = Best->Function;
4060
4061 if (FnDecl) {
4062 // We matched an overloaded operator. Build a call to that
4063 // operator.
4064
4065 // Convert the arguments.
4066 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4067 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004068 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004069 } else {
4070 // Convert the arguments.
Mike Stump9afab102009-02-19 03:04:26 +00004071 if (PerformCopyInitialization(Input,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004072 FnDecl->getParamDecl(0)->getType(),
4073 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004074 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004075 }
4076
4077 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004078 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004079 = FnDecl->getType()->getAsFunctionType()->getResultType();
4080 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004081
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004082 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00004083 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004084 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004085 UsualUnaryConversions(FnExpr);
4086
Sebastian Redl8b769972009-01-19 00:08:26 +00004087 input.release();
Mike Stump9afab102009-02-19 03:04:26 +00004088 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4089 1, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004090 } else {
4091 // We matched a built-in operator. Convert the arguments, then
4092 // break out so that we will build the appropriate built-in
4093 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004094 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4095 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004096 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004097
4098 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004099 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004100 }
4101
4102 case OR_No_Viable_Function:
4103 // No viable function; fall through to handling this as a
4104 // built-in operator, which will produce an error message for us.
4105 break;
4106
4107 case OR_Ambiguous:
4108 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4109 << UnaryOperator::getOpcodeStr(Opc)
4110 << Input->getSourceRange();
4111 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004112 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004113
4114 case OR_Deleted:
4115 Diag(OpLoc, diag::err_ovl_deleted_oper)
4116 << Best->Function->isDeleted()
4117 << UnaryOperator::getOpcodeStr(Opc)
4118 << Input->getSourceRange();
4119 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4120 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004121 }
4122
4123 // Either we found no viable overloaded operator or we matched a
4124 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004125 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004126 }
4127
Chris Lattner4b009652007-07-25 00:24:17 +00004128 QualType resultType;
4129 switch (Opc) {
4130 default:
4131 assert(0 && "Unimplemented unary expr!");
4132 case UnaryOperator::PreInc:
4133 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004134 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4135 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004136 break;
Mike Stump9afab102009-02-19 03:04:26 +00004137 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004138 resultType = CheckAddressOfOperand(Input, OpLoc);
4139 break;
Mike Stump9afab102009-02-19 03:04:26 +00004140 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004141 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004142 resultType = CheckIndirectionOperand(Input, OpLoc);
4143 break;
4144 case UnaryOperator::Plus:
4145 case UnaryOperator::Minus:
4146 UsualUnaryConversions(Input);
4147 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004148 if (resultType->isDependentType())
4149 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004150 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4151 break;
4152 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4153 resultType->isEnumeralType())
4154 break;
4155 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4156 Opc == UnaryOperator::Plus &&
4157 resultType->isPointerType())
4158 break;
4159
Sebastian Redl8b769972009-01-19 00:08:26 +00004160 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4161 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004162 case UnaryOperator::Not: // bitwise complement
4163 UsualUnaryConversions(Input);
4164 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004165 if (resultType->isDependentType())
4166 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004167 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4168 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4169 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004170 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004171 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004172 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004173 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4174 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004175 break;
4176 case UnaryOperator::LNot: // logical negation
4177 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4178 DefaultFunctionArrayConversion(Input);
4179 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004180 if (resultType->isDependentType())
4181 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004182 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004183 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4184 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004185 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004186 // In C++, it's bool. C++ 5.3.1p8
4187 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004188 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004189 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004190 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004191 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004192 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004193 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004194 resultType = Input->getType();
4195 break;
4196 }
4197 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004198 return ExprError();
4199 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004200 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004201}
4202
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004203/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stump9afab102009-02-19 03:04:26 +00004204Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004205 SourceLocation LabLoc,
4206 IdentifierInfo *LabelII) {
4207 // Look up the record for this label identifier.
4208 LabelStmt *&LabelDecl = LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004209
Daniel Dunbar879788d2008-08-04 16:51:22 +00004210 // If we haven't seen this label yet, create a forward reference. It
4211 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004212 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004213 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004214
Chris Lattner4b009652007-07-25 00:24:17 +00004215 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004216 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4217 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004218}
4219
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004220Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004221 SourceLocation RPLoc) { // "({..})"
4222 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4223 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4224 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4225
Eli Friedmanbc941e12009-01-24 23:09:00 +00004226 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4227 if (isFileScope) {
4228 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4229 }
4230
Chris Lattner4b009652007-07-25 00:24:17 +00004231 // FIXME: there are a variety of strange constraints to enforce here, for
4232 // example, it is not possible to goto into a stmt expression apparently.
4233 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004234
Chris Lattner4b009652007-07-25 00:24:17 +00004235 // FIXME: the last statement in the compount stmt has its value used. We
4236 // should not warn about it being unused.
4237
4238 // If there are sub stmts in the compound stmt, take the type of the last one
4239 // as the type of the stmtexpr.
4240 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004241
Chris Lattner200964f2008-07-26 19:51:01 +00004242 if (!Compound->body_empty()) {
4243 Stmt *LastStmt = Compound->body_back();
4244 // If LastStmt is a label, skip down through into the body.
4245 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4246 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004247
Chris Lattner200964f2008-07-26 19:51:01 +00004248 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004249 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004250 }
Mike Stump9afab102009-02-19 03:04:26 +00004251
Steve Naroff774e4152009-01-21 00:14:39 +00004252 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004253}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004254
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004255Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4256 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004257 SourceLocation TypeLoc,
4258 TypeTy *argty,
4259 OffsetOfComponent *CompPtr,
4260 unsigned NumComponents,
4261 SourceLocation RPLoc) {
4262 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4263 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004264
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004265 bool Dependent = ArgTy->isDependentType();
4266
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004267 // We must have at least one component that refers to the type, and the first
4268 // one is known to be a field designator. Verify that the ArgTy represents
4269 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004270 if (!Dependent && !ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004271 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stump9afab102009-02-19 03:04:26 +00004272
Eli Friedman342d9432009-02-27 06:44:11 +00004273 // Otherwise, create a null pointer as the base, and iteratively process
4274 // the offsetof designators.
4275 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4276 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
4277 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
4278 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004279
Chris Lattnerb37522e2007-08-31 21:49:13 +00004280 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4281 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004282 // FIXME: This diagnostic isn't actually visible because the location is in
4283 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004284 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004285 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4286 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004287
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004288 if (!Dependent) {
4289 // FIXME: Dependent case loses a lot of information here. And probably
4290 // leaks like a sieve.
4291 for (unsigned i = 0; i != NumComponents; ++i) {
4292 const OffsetOfComponent &OC = CompPtr[i];
4293 if (OC.isBrackets) {
4294 // Offset of an array sub-field. TODO: Should we allow vector elements?
4295 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4296 if (!AT) {
4297 Res->Destroy(Context);
4298 return Diag(OC.LocEnd, diag::err_offsetof_array_type)
4299 << Res->getType();
4300 }
4301
4302 // FIXME: C++: Verify that operator[] isn't overloaded.
4303
Eli Friedman342d9432009-02-27 06:44:11 +00004304 // Promote the array so it looks more like a normal array subscript
4305 // expression.
4306 DefaultFunctionArrayConversion(Res);
4307
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004308 // C99 6.5.2.1p1
4309 Expr *Idx = static_cast<Expr*>(OC.U.E);
4310 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4311 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4312 << Idx->getSourceRange();
4313
4314 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4315 OC.LocEnd);
4316 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004317 }
Mike Stump9afab102009-02-19 03:04:26 +00004318
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004319 const RecordType *RC = Res->getType()->getAsRecordType();
4320 if (!RC) {
4321 Res->Destroy(Context);
4322 return Diag(OC.LocEnd, diag::err_offsetof_record_type)
4323 << Res->getType();
4324 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004325
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004326 // Get the decl corresponding to this.
4327 RecordDecl *RD = RC->getDecl();
4328 FieldDecl *MemberDecl
4329 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4330 LookupMemberName)
4331 .getAsDecl());
4332 if (!MemberDecl)
4333 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4334 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004335
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004336 // FIXME: C++: Verify that MemberDecl isn't a static field.
4337 // FIXME: Verify that MemberDecl isn't a bitfield.
4338 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4339 // matter here.
4340 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004341 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004342 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004343 }
Mike Stump9afab102009-02-19 03:04:26 +00004344
4345 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff774e4152009-01-21 00:14:39 +00004346 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004347}
4348
4349
Mike Stump9afab102009-02-19 03:04:26 +00004350Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004351 TypeTy *arg1, TypeTy *arg2,
4352 SourceLocation RPLoc) {
4353 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4354 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004355
Steve Naroff63bad2d2007-08-01 22:05:33 +00004356 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004357
4358 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff774e4152009-01-21 00:14:39 +00004359 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004360}
4361
Mike Stump9afab102009-02-19 03:04:26 +00004362Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004363 ExprTy *expr1, ExprTy *expr2,
4364 SourceLocation RPLoc) {
4365 Expr *CondExpr = static_cast<Expr*>(cond);
4366 Expr *LHSExpr = static_cast<Expr*>(expr1);
4367 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stump9afab102009-02-19 03:04:26 +00004368
Steve Naroff93c53012007-08-03 21:21:27 +00004369 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4370
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004371 QualType resType;
4372 if (CondExpr->isValueDependent()) {
4373 resType = Context.DependentTy;
4374 } else {
4375 // The conditional expression is required to be a constant expression.
4376 llvm::APSInt condEval(32);
4377 SourceLocation ExpLoc;
4378 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4379 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4380 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004381
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004382 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4383 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4384 }
4385
Mike Stump9afab102009-02-19 03:04:26 +00004386 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00004387 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004388}
4389
Steve Naroff52a81c02008-09-03 18:15:37 +00004390//===----------------------------------------------------------------------===//
4391// Clang Extensions.
4392//===----------------------------------------------------------------------===//
4393
4394/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004395void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004396 // Analyze block parameters.
4397 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004398
Steve Naroff52a81c02008-09-03 18:15:37 +00004399 // Add BSI to CurBlock.
4400 BSI->PrevBlockInfo = CurBlock;
4401 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004402
Steve Naroff52a81c02008-09-03 18:15:37 +00004403 BSI->ReturnType = 0;
4404 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004405 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004406
Steve Naroff52059382008-10-10 01:28:17 +00004407 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004408 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004409}
4410
Mike Stumpc1fddff2009-02-04 22:31:32 +00004411void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4412 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4413
4414 if (ParamInfo.getNumTypeObjects() == 0
4415 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4416 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4417
4418 // The type is entirely optional as well, if none, use DependentTy.
4419 if (T.isNull())
4420 T = Context.DependentTy;
4421
4422 // The parameter list is optional, if there was none, assume ().
4423 if (!T->isFunctionType())
4424 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4425
4426 CurBlock->hasPrototype = true;
4427 CurBlock->isVariadic = false;
4428 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4429 .getTypePtr();
4430
4431 if (!RetTy->isDependentType())
4432 CurBlock->ReturnType = RetTy;
4433 return;
4434 }
4435
Steve Naroff52a81c02008-09-03 18:15:37 +00004436 // Analyze arguments to block.
4437 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4438 "Not a function declarator!");
4439 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004440
Steve Naroff52059382008-10-10 01:28:17 +00004441 CurBlock->hasPrototype = FTI.hasPrototype;
4442 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004443
Steve Naroff52a81c02008-09-03 18:15:37 +00004444 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4445 // no arguments, not a function that takes a single void argument.
4446 if (FTI.hasPrototype &&
4447 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4448 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4449 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4450 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004451 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004452 } else if (FTI.hasPrototype) {
4453 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004454 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4455 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004456 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4457
4458 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4459 .getTypePtr();
4460
4461 if (!RetTy->isDependentType())
4462 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004463 }
Steve Naroff52059382008-10-10 01:28:17 +00004464 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004465
Steve Naroff52059382008-10-10 01:28:17 +00004466 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4467 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4468 // If this has an identifier, add it to the scope stack.
4469 if ((*AI)->getIdentifier())
4470 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004471}
4472
4473/// ActOnBlockError - If there is an error parsing a block, this callback
4474/// is invoked to pop the information about the block from the action impl.
4475void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4476 // Ensure that CurBlock is deleted.
4477 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004478
Steve Naroff52a81c02008-09-03 18:15:37 +00004479 // Pop off CurBlock, handle nested blocks.
4480 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004481
Steve Naroff52a81c02008-09-03 18:15:37 +00004482 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stump9afab102009-02-19 03:04:26 +00004483
Steve Naroff52a81c02008-09-03 18:15:37 +00004484}
4485
4486/// ActOnBlockStmtExpr - This is called when the body of a block statement
4487/// literal was successfully completed. ^(int x){...}
4488Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4489 Scope *CurScope) {
4490 // Ensure that CurBlock is deleted.
4491 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004492 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004493
Steve Naroff52059382008-10-10 01:28:17 +00004494 PopDeclContext();
4495
Steve Naroff52a81c02008-09-03 18:15:37 +00004496 // Pop off CurBlock, handle nested blocks.
4497 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004498
Steve Naroff52a81c02008-09-03 18:15:37 +00004499 QualType RetTy = Context.VoidTy;
4500 if (BSI->ReturnType)
4501 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004502
Steve Naroff52a81c02008-09-03 18:15:37 +00004503 llvm::SmallVector<QualType, 8> ArgTypes;
4504 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4505 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004506
Steve Naroff52a81c02008-09-03 18:15:37 +00004507 QualType BlockTy;
4508 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004509 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004510 else
4511 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004512 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004513
Steve Naroff52a81c02008-09-03 18:15:37 +00004514 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004515
Steve Naroff95029d92008-10-08 18:44:00 +00004516 BSI->TheDecl->setBody(Body.take());
Mike Stumpae93d652009-02-19 22:01:56 +00004517 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff52a81c02008-09-03 18:15:37 +00004518}
4519
Anders Carlsson36760332007-10-15 20:28:48 +00004520Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4521 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004522 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004523 Expr *E = static_cast<Expr*>(expr);
4524 QualType T = QualType::getFromOpaquePtr(type);
4525
4526 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004527
4528 // Get the va_list type
4529 QualType VaListType = Context.getBuiltinVaListType();
4530 // Deal with implicit array decay; for example, on x86-64,
4531 // va_list is an array, but it's supposed to decay to
4532 // a pointer for va_arg.
4533 if (VaListType->isArrayType())
4534 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004535 // Make sure the input expression also decays appropriately.
4536 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004537
4538 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004539 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004540 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004541 << E->getType() << E->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004542
Anders Carlsson36760332007-10-15 20:28:48 +00004543 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004544
Steve Naroff774e4152009-01-21 00:14:39 +00004545 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004546}
4547
Douglas Gregorad4b3792008-11-29 04:51:27 +00004548Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4549 // The type of __null will be int or long, depending on the size of
4550 // pointers on the target.
4551 QualType Ty;
4552 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4553 Ty = Context.IntTy;
4554 else
4555 Ty = Context.LongTy;
4556
Steve Naroff774e4152009-01-21 00:14:39 +00004557 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004558}
4559
Chris Lattner005ed752008-01-04 18:04:52 +00004560bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4561 SourceLocation Loc,
4562 QualType DstType, QualType SrcType,
4563 Expr *SrcExpr, const char *Flavor) {
4564 // Decode the result (notice that AST's are still created for extensions).
4565 bool isInvalid = false;
4566 unsigned DiagKind;
4567 switch (ConvTy) {
4568 default: assert(0 && "Unknown conversion type");
4569 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004570 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004571 DiagKind = diag::ext_typecheck_convert_pointer_int;
4572 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004573 case IntToPointer:
4574 DiagKind = diag::ext_typecheck_convert_int_pointer;
4575 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004576 case IncompatiblePointer:
4577 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4578 break;
4579 case FunctionVoidPointer:
4580 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4581 break;
4582 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004583 // If the qualifiers lost were because we were applying the
4584 // (deprecated) C++ conversion from a string literal to a char*
4585 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4586 // Ideally, this check would be performed in
4587 // CheckPointerTypesForAssignment. However, that would require a
4588 // bit of refactoring (so that the second argument is an
4589 // expression, rather than a type), which should be done as part
4590 // of a larger effort to fix CheckPointerTypesForAssignment for
4591 // C++ semantics.
4592 if (getLangOptions().CPlusPlus &&
4593 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4594 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004595 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4596 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004597 case IntToBlockPointer:
4598 DiagKind = diag::err_int_to_block_pointer;
4599 break;
4600 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004601 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004602 break;
Steve Naroff19608432008-10-14 22:18:38 +00004603 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004604 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004605 // it can give a more specific diagnostic.
4606 DiagKind = diag::warn_incompatible_qualified_id;
4607 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004608 case IncompatibleVectors:
4609 DiagKind = diag::warn_incompatible_vectors;
4610 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004611 case Incompatible:
4612 DiagKind = diag::err_typecheck_convert_incompatible;
4613 isInvalid = true;
4614 break;
4615 }
Mike Stump9afab102009-02-19 03:04:26 +00004616
Chris Lattner271d4c22008-11-24 05:29:24 +00004617 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4618 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004619 return isInvalid;
4620}
Anders Carlssond5201b92008-11-30 19:50:32 +00004621
4622bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4623{
4624 Expr::EvalResult EvalResult;
4625
Mike Stump9afab102009-02-19 03:04:26 +00004626 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004627 EvalResult.HasSideEffects) {
4628 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4629
4630 if (EvalResult.Diag) {
4631 // We only show the note if it's not the usual "invalid subexpression"
4632 // or if it's actually in a subexpression.
4633 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4634 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4635 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4636 }
Mike Stump9afab102009-02-19 03:04:26 +00004637
Anders Carlssond5201b92008-11-30 19:50:32 +00004638 return true;
4639 }
4640
4641 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004642 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004643 E->getSourceRange();
4644
4645 // Print the reason it's not a constant.
4646 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4647 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4648 }
Mike Stump9afab102009-02-19 03:04:26 +00004649
Anders Carlssond5201b92008-11-30 19:50:32 +00004650 if (Result)
4651 *Result = EvalResult.Val.getInt();
4652 return false;
4653}