blob: 1a93039b03276fbe4e87e9e5a30b6c120fc49ca7 [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();
Douglas Gregor723d3332009-01-07 00:43:41 +0000603 }
604
Sebastian Redlcd883f72009-01-18 18:53:16 +0000605 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000606}
607
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000608/// ActOnDeclarationNameExpr - The parser has read some kind of name
609/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
610/// performs lookup on that name and returns an expression that refers
611/// to that name. This routine isn't directly called from the parser,
612/// because the parser doesn't know about DeclarationName. Rather,
613/// this routine is called by ActOnIdentifierExpr,
614/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
615/// which form the DeclarationName from the corresponding syntactic
616/// forms.
617///
618/// HasTrailingLParen indicates whether this identifier is used in a
619/// function call context. LookupCtx is only used for a C++
620/// qualified-id (foo::bar) to indicate the class or namespace that
621/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000622///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000623/// isAddressOfOperand means that this expression is the direct operand
624/// of an address-of operator. This matters because this is the only
625/// situation where a qualified name referencing a non-static member may
626/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000627Sema::OwningExprResult
628Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
629 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000630 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000631 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000632 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000633 if (SS && SS->isInvalid())
634 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000635 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
636 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000637
Douglas Gregor09be81b2009-02-04 17:27:36 +0000638 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000639 if (Lookup.isAmbiguous()) {
640 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
641 SS && SS->isSet() ? SS->getRange()
642 : SourceRange());
643 return ExprError();
644 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000645 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000646
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000647 // If this reference is in an Objective-C method, then ivar lookup happens as
648 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000649 IdentifierInfo *II = Name.getAsIdentifierInfo();
650 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000651 // There are two cases to handle here. 1) scoped lookup could have failed,
652 // in which case we should look for an ivar. 2) scoped lookup could have
653 // found a decl, but that decl is outside the current method (i.e. a global
654 // variable). In these two cases, we do a lookup for an ivar with this
655 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000656 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000657 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000658 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000659 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000660 if (DiagnoseUseOfDecl(IV, Loc))
661 return ExprError();
Chris Lattner2a3bef92009-02-16 17:19:12 +0000662
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000663 // FIXME: This should use a new expr for a direct reference, don't turn
664 // this into Self->ivar, just return a BareIVarExpr or something.
665 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000666 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Mike Stump9afab102009-02-19 03:04:26 +0000667 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +0000668 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000669 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000670 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000671 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000672 }
673 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000674 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000675 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000676 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000677 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000678 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000679 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000680 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000681
Douglas Gregoraa57e862009-02-18 21:56:37 +0000682 // Determine whether this name might be a candidate for
683 // argument-dependent lookup.
684 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
685 HasTrailingLParen;
686
687 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000688 // We've seen something of the form
689 //
690 // identifier(
691 //
692 // and we did not find any entity by the name
693 // "identifier". However, this identifier is still subject to
694 // argument-dependent lookup, so keep track of the name.
695 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
696 Context.OverloadTy,
697 Loc));
698 }
699
Chris Lattner4b009652007-07-25 00:24:17 +0000700 if (D == 0) {
701 // Otherwise, this could be an implicitly declared function reference (legal
702 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000703 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000704 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000705 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000706 else {
707 // If this name wasn't predeclared and if this is not a function call,
708 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000709 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000710 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
711 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000712 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
713 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000714 return ExprError(Diag(Loc, diag::err_undeclared_use)
715 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000716 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000717 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000718 }
719 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000720
Sebastian Redl0c9da212009-02-03 20:19:35 +0000721 // If this is an expression of the form &Class::member, don't build an
722 // implicit member ref, because we want a pointer to the member in general,
723 // not any specific instance's member.
724 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000725 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000726 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000727 QualType DType;
728 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
729 DType = FD->getType().getNonReferenceType();
730 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
731 DType = Method->getType();
732 } else if (isa<OverloadedFunctionDecl>(D)) {
733 DType = Context.OverloadTy;
734 }
735 // Could be an inner type. That's diagnosed below, so ignore it here.
736 if (!DType.isNull()) {
737 // The pointer is type- and value-dependent if it points into something
738 // dependent.
739 bool Dependent = false;
740 for (; DC; DC = DC->getParent()) {
741 // FIXME: could stop early at namespace scope.
742 if (DC->isRecord()) {
743 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
744 if (Context.getTypeDeclType(Record)->isDependentType()) {
745 Dependent = true;
746 break;
747 }
748 }
749 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000750 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000751 }
752 }
753 }
754
Douglas Gregor723d3332009-01-07 00:43:41 +0000755 // We may have found a field within an anonymous union or struct
756 // (C++ [class.union]).
757 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
758 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
759 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000760
Douglas Gregor3257fb52008-12-22 05:46:06 +0000761 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
762 if (!MD->isStatic()) {
763 // C++ [class.mfct.nonstatic]p2:
764 // [...] if name lookup (3.4.1) resolves the name in the
765 // id-expression to a nonstatic nontype member of class X or of
766 // a base class of X, the id-expression is transformed into a
767 // class member access expression (5.2.5) using (*this) (9.3.2)
768 // as the postfix-expression to the left of the '.' operator.
769 DeclContext *Ctx = 0;
770 QualType MemberType;
771 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
772 Ctx = FD->getDeclContext();
773 MemberType = FD->getType();
774
775 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
776 MemberType = RefType->getPointeeType();
777 else if (!FD->isMutable()) {
778 unsigned combinedQualifiers
779 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
780 MemberType = MemberType.getQualifiedType(combinedQualifiers);
781 }
782 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
783 if (!Method->isStatic()) {
784 Ctx = Method->getParent();
785 MemberType = Method->getType();
786 }
787 } else if (OverloadedFunctionDecl *Ovl
788 = dyn_cast<OverloadedFunctionDecl>(D)) {
789 for (OverloadedFunctionDecl::function_iterator
790 Func = Ovl->function_begin(),
791 FuncEnd = Ovl->function_end();
792 Func != FuncEnd; ++Func) {
793 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
794 if (!DMethod->isStatic()) {
795 Ctx = Ovl->getDeclContext();
796 MemberType = Context.OverloadTy;
797 break;
798 }
799 }
800 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000801
802 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000803 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
804 QualType ThisType = Context.getTagDeclType(MD->getParent());
805 if ((Context.getCanonicalType(CtxType)
806 == Context.getCanonicalType(ThisType)) ||
807 IsDerivedFrom(ThisType, CtxType)) {
808 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000809 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000810 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000811 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000812 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000813 }
814 }
815 }
816 }
817
Douglas Gregor8acb7272008-12-11 16:49:14 +0000818 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000819 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
820 if (MD->isStatic())
821 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000822 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
823 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000824 }
825
Douglas Gregor3257fb52008-12-22 05:46:06 +0000826 // Any other ways we could have found the field in a well-formed
827 // program would have been turned into implicit member expressions
828 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000829 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
830 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000831 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000832
Chris Lattner4b009652007-07-25 00:24:17 +0000833 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000834 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000835 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000836 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000837 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000838 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000839
Steve Naroffd6163f32008-09-05 22:11:13 +0000840 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000841 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000842 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
843 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000844 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
845 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
846 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000847 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000848
Douglas Gregoraa57e862009-02-18 21:56:37 +0000849 // Check whether this declaration can be used. Note that we suppress
850 // this check when we're going to perform argument-dependent lookup
851 // on this function name, because this might not be the function
852 // that overload resolution actually selects.
853 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
854 return ExprError();
855
Douglas Gregor48840c72008-12-10 23:01:14 +0000856 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000857 // Warn about constructs like:
858 // if (void *X = foo()) { ... } else { X }.
859 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000860 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
861 Scope *CheckS = S;
862 while (CheckS) {
863 if (CheckS->isWithinElse() &&
864 CheckS->getControlParent()->isDeclScope(Var)) {
865 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000866 ExprError(Diag(Loc, diag::warn_value_always_false)
867 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000868 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000869 ExprError(Diag(Loc, diag::warn_value_always_zero)
870 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000871 break;
872 }
873
874 // Move up one more control parent to check again.
875 CheckS = CheckS->getControlParent();
876 if (CheckS)
877 CheckS = CheckS->getParent();
878 }
879 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000880 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
881 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
882 // C99 DR 316 says that, if a function type comes from a
883 // function definition (without a prototype), that type is only
884 // used for checking compatibility. Therefore, when referencing
885 // the function, we pretend that we don't have the full function
886 // type.
887 QualType T = Func->getType();
888 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000889 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
890 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000891 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
892 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000893 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000894
895 // Only create DeclRefExpr's for valid Decl's.
896 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000897 return ExprError();
898
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000899 // If the identifier reference is inside a block, and it refers to a value
900 // that is outside the block, create a BlockDeclRefExpr instead of a
901 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
902 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000903 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000904 // We do not do this for things like enum constants, global variables, etc,
905 // as they do not get snapshotted.
906 //
907 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000908 // Blocks that have these can't be constant.
909 CurBlock->hasBlockDeclRefExprs = true;
910
Steve Naroff52059382008-10-10 01:28:17 +0000911 // The BlocksAttr indicates the variable is bound by-reference.
912 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000913 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000914 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000915
Steve Naroff52059382008-10-10 01:28:17 +0000916 // Variable will be bound by-copy, make it const within the closure.
917 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000918 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000919 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000920 }
921 // If this reference is not in a block or if the referenced variable is
922 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000923
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000924 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000925 bool ValueDependent = false;
926 if (getLangOptions().CPlusPlus) {
927 // C++ [temp.dep.expr]p3:
928 // An id-expression is type-dependent if it contains:
929 // - an identifier that was declared with a dependent type,
930 if (VD->getType()->isDependentType())
931 TypeDependent = true;
932 // - FIXME: a template-id that is dependent,
933 // - a conversion-function-id that specifies a dependent type,
934 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
935 Name.getCXXNameType()->isDependentType())
936 TypeDependent = true;
937 // - a nested-name-specifier that contains a class-name that
938 // names a dependent type.
939 else if (SS && !SS->isEmpty()) {
940 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
941 DC; DC = DC->getParent()) {
942 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000943 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000944 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
945 if (Context.getTypeDeclType(Record)->isDependentType()) {
946 TypeDependent = true;
947 break;
948 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000949 }
950 }
951 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000952
Douglas Gregora5d84612008-12-10 20:57:37 +0000953 // C++ [temp.dep.constexpr]p2:
954 //
955 // An identifier is value-dependent if it is:
956 // - a name declared with a dependent type,
957 if (TypeDependent)
958 ValueDependent = true;
959 // - the name of a non-type template parameter,
960 else if (isa<NonTypeTemplateParmDecl>(VD))
961 ValueDependent = true;
962 // - a constant with integral or enumeration type and is
963 // initialized with an expression that is value-dependent
964 // (FIXME!).
965 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000966
Sebastian Redlcd883f72009-01-18 18:53:16 +0000967 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
968 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000969}
970
Sebastian Redlcd883f72009-01-18 18:53:16 +0000971Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
972 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000973 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000974
Chris Lattner4b009652007-07-25 00:24:17 +0000975 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000976 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000977 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
978 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
979 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000980 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000981
Chris Lattner7e637512008-01-12 08:14:25 +0000982 // Pre-defined identifiers are of type char[x], where x is the length of the
983 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000984 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000985 if (FunctionDecl *FD = getCurFunctionDecl())
986 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000987 else if (ObjCMethodDecl *MD = getCurMethodDecl())
988 Length = MD->getSynthesizedMethodSize();
989 else {
990 Diag(Loc, diag::ext_predef_outside_function);
991 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
992 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
993 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000994
995
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000996 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000997 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000998 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000999 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001000}
1001
Sebastian Redlcd883f72009-01-18 18:53:16 +00001002Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001003 llvm::SmallString<16> CharBuffer;
1004 CharBuffer.resize(Tok.getLength());
1005 const char *ThisTokBegin = &CharBuffer[0];
1006 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001007
Chris Lattner4b009652007-07-25 00:24:17 +00001008 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1009 Tok.getLocation(), PP);
1010 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001011 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001012
1013 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1014
Sebastian Redl75324932009-01-20 22:23:13 +00001015 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1016 Literal.isWide(),
1017 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001018}
1019
Sebastian Redlcd883f72009-01-18 18:53:16 +00001020Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1021 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001022 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1023 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001024 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001025 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001026 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001027 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001028 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001029
Chris Lattner4b009652007-07-25 00:24:17 +00001030 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001031 // Add padding so that NumericLiteralParser can overread by one character.
1032 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001033 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001034
Chris Lattner4b009652007-07-25 00:24:17 +00001035 // Get the spelling of the token, which eliminates trigraphs, etc.
1036 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001037
Chris Lattner4b009652007-07-25 00:24:17 +00001038 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1039 Tok.getLocation(), PP);
1040 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001041 return ExprError();
1042
Chris Lattner1de66eb2007-08-26 03:42:43 +00001043 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001044
Chris Lattner1de66eb2007-08-26 03:42:43 +00001045 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001046 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001047 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001048 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001049 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001050 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001051 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001052 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001053
1054 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1055
Ted Kremenekddedbe22007-11-29 00:56:49 +00001056 // isExact will be set by GetFloatValue().
1057 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001058 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1059 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001060
Chris Lattner1de66eb2007-08-26 03:42:43 +00001061 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001062 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001063 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001064 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001065
Neil Booth7421e9c2007-08-29 22:00:19 +00001066 // long long is a C99 feature.
1067 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001068 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001069 Diag(Tok.getLocation(), diag::ext_longlong);
1070
Chris Lattner4b009652007-07-25 00:24:17 +00001071 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001072 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001073
Chris Lattner4b009652007-07-25 00:24:17 +00001074 if (Literal.GetIntegerValue(ResultVal)) {
1075 // If this value didn't fit into uintmax_t, warn and force to ull.
1076 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001077 Ty = Context.UnsignedLongLongTy;
1078 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001079 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001080 } else {
1081 // If this value fits into a ULL, try to figure out what else it fits into
1082 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001083
Chris Lattner4b009652007-07-25 00:24:17 +00001084 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1085 // be an unsigned int.
1086 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1087
1088 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001089 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001090 if (!Literal.isLong && !Literal.isLongLong) {
1091 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001092 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001093
Chris Lattner4b009652007-07-25 00:24:17 +00001094 // Does it fit in a unsigned int?
1095 if (ResultVal.isIntN(IntSize)) {
1096 // Does it fit in a signed int?
1097 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001098 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001099 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001100 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001101 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001102 }
Chris Lattner4b009652007-07-25 00:24:17 +00001103 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001104
Chris Lattner4b009652007-07-25 00:24:17 +00001105 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001106 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001107 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001108
Chris Lattner4b009652007-07-25 00:24:17 +00001109 // Does it fit in a unsigned long?
1110 if (ResultVal.isIntN(LongSize)) {
1111 // Does it fit in a signed long?
1112 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001113 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001114 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001115 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001116 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001117 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001118 }
1119
Chris Lattner4b009652007-07-25 00:24:17 +00001120 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001121 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001122 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001123
Chris Lattner4b009652007-07-25 00:24:17 +00001124 // Does it fit in a unsigned long long?
1125 if (ResultVal.isIntN(LongLongSize)) {
1126 // Does it fit in a signed long long?
1127 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001128 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001129 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001130 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001131 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001132 }
1133 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001134
Chris Lattner4b009652007-07-25 00:24:17 +00001135 // If we still couldn't decide a type, we probably have something that
1136 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001137 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001138 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001139 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001140 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001141 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001142
Chris Lattnere4068872008-05-09 05:59:00 +00001143 if (ResultVal.getBitWidth() != Width)
1144 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001145 }
Sebastian Redl75324932009-01-20 22:23:13 +00001146 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001147 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001148
Chris Lattner1de66eb2007-08-26 03:42:43 +00001149 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1150 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001151 Res = new (Context) ImaginaryLiteral(Res,
1152 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001153
1154 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001155}
1156
Sebastian Redlcd883f72009-01-18 18:53:16 +00001157Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1158 SourceLocation R, ExprArg Val) {
1159 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001160 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001161 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001162}
1163
1164/// The UsualUnaryConversions() function is *not* called by this routine.
1165/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001166bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001167 SourceLocation OpLoc,
1168 const SourceRange &ExprRange,
1169 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001170 if (exprType->isDependentType())
1171 return false;
1172
Chris Lattner4b009652007-07-25 00:24:17 +00001173 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001174 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001175 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001176 if (isSizeof)
1177 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1178 return false;
1179 }
1180
1181 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001182 Diag(OpLoc, diag::ext_sizeof_void_type)
1183 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001184 return false;
1185 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001186
Chris Lattner159fe082009-01-24 19:46:37 +00001187 return DiagnoseIncompleteType(OpLoc, exprType,
1188 isSizeof ? diag::err_sizeof_incomplete_type :
1189 diag::err_alignof_incomplete_type,
1190 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001191}
1192
Chris Lattner8d9f7962009-01-24 20:17:12 +00001193bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1194 const SourceRange &ExprRange) {
1195 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001196
Chris Lattner8d9f7962009-01-24 20:17:12 +00001197 // alignof decl is always ok.
1198 if (isa<DeclRefExpr>(E))
1199 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001200
1201 // Cannot know anything else if the expression is dependent.
1202 if (E->isTypeDependent())
1203 return false;
1204
Chris Lattner8d9f7962009-01-24 20:17:12 +00001205 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1206 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1207 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001208 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001209 return true;
1210 }
1211 // Other fields are ok.
1212 return false;
1213 }
1214 }
1215 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1216}
1217
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001218/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1219/// the same for @c alignof and @c __alignof
1220/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001221Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001222Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1223 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001224 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001225 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001226
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001227 QualType ArgTy;
1228 SourceRange Range;
1229 if (isType) {
1230 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1231 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001232
1233 // Verify that the operand is valid.
1234 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1235 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001236 } else {
1237 // Get the end location.
1238 Expr *ArgEx = (Expr *)TyOrEx;
1239 Range = ArgEx->getSourceRange();
1240 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001241
1242 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001243 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001244 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001245 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001246 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1247 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1248 isInvalid = true;
1249 } else {
1250 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1251 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001252
1253 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001254 DeleteExpr(ArgEx);
1255 return ExprError();
1256 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001257 }
1258
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001259 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001260 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001261 Context.getSizeType(), OpLoc,
1262 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001263}
1264
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001265QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001266 if (V->isTypeDependent())
1267 return Context.DependentTy;
1268
Chris Lattner03931a72007-08-24 21:16:53 +00001269 DefaultFunctionArrayConversion(V);
1270
Chris Lattnera16e42d2007-08-26 05:39:26 +00001271 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001272 if (const ComplexType *CT = V->getType()->getAsComplexType())
1273 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001274
1275 // Otherwise they pass through real integer and floating point types here.
1276 if (V->getType()->isArithmeticType())
1277 return V->getType();
1278
1279 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001280 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1281 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001282 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001283}
1284
1285
Chris Lattner4b009652007-07-25 00:24:17 +00001286
Sebastian Redl8b769972009-01-19 00:08:26 +00001287Action::OwningExprResult
1288Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1289 tok::TokenKind Kind, ExprArg Input) {
1290 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001291
Chris Lattner4b009652007-07-25 00:24:17 +00001292 UnaryOperator::Opcode Opc;
1293 switch (Kind) {
1294 default: assert(0 && "Unknown unary op!");
1295 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1296 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1297 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001298
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001299 if (getLangOptions().CPlusPlus &&
1300 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1301 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001302 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001303 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1304
1305 // C++ [over.inc]p1:
1306 //
1307 // [...] If the function is a member function with one
1308 // parameter (which shall be of type int) or a non-member
1309 // function with two parameters (the second of which shall be
1310 // of type int), it defines the postfix increment operator ++
1311 // for objects of that type. When the postfix increment is
1312 // called as a result of using the ++ operator, the int
1313 // argument will have value zero.
1314 Expr *Args[2] = {
1315 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001316 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1317 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001318 };
1319
1320 // Build the candidate set for overloading
1321 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001322 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1323 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001324
1325 // Perform overload resolution.
1326 OverloadCandidateSet::iterator Best;
1327 switch (BestViableFunction(CandidateSet, Best)) {
1328 case OR_Success: {
1329 // We found a built-in operator or an overloaded operator.
1330 FunctionDecl *FnDecl = Best->Function;
1331
1332 if (FnDecl) {
1333 // We matched an overloaded operator. Build a call to that
1334 // operator.
1335
1336 // Convert the arguments.
1337 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1338 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001339 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001340 } else {
1341 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001342 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001343 FnDecl->getParamDecl(0)->getType(),
1344 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001345 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001346 }
1347
1348 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001349 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001350 = FnDecl->getType()->getAsFunctionType()->getResultType();
1351 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001352
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001353 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001354 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001355 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001356 UsualUnaryConversions(FnExpr);
1357
Sebastian Redl8b769972009-01-19 00:08:26 +00001358 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001359 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1360 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001361 } else {
1362 // We matched a built-in operator. Convert the arguments, then
1363 // break out so that we will build the appropriate built-in
1364 // operator node.
1365 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1366 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001367 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001368
1369 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001370 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001371 }
1372
1373 case OR_No_Viable_Function:
1374 // No viable function; fall through to handling this as a
1375 // built-in operator, which will produce an error message for us.
1376 break;
1377
1378 case OR_Ambiguous:
1379 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1380 << UnaryOperator::getOpcodeStr(Opc)
1381 << Arg->getSourceRange();
1382 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001383 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001384
1385 case OR_Deleted:
1386 Diag(OpLoc, diag::err_ovl_deleted_oper)
1387 << Best->Function->isDeleted()
1388 << UnaryOperator::getOpcodeStr(Opc)
1389 << Arg->getSourceRange();
1390 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1391 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001392 }
1393
1394 // Either we found no viable overloaded operator or we matched a
1395 // built-in operator. In either case, fall through to trying to
1396 // build a built-in operation.
1397 }
1398
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001399 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1400 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001401 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001402 return ExprError();
1403 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001404 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001405}
1406
Sebastian Redl8b769972009-01-19 00:08:26 +00001407Action::OwningExprResult
1408Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1409 ExprArg Idx, SourceLocation RLoc) {
1410 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1411 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001412
Douglas Gregor80723c52008-11-19 17:17:41 +00001413 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001414 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001415 LHSExp->getType()->isEnumeralType() ||
1416 RHSExp->getType()->isRecordType() ||
1417 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001418 // Add the appropriate overloaded operators (C++ [over.match.oper])
1419 // to the candidate set.
1420 OverloadCandidateSet CandidateSet;
1421 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001422 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1423 SourceRange(LLoc, RLoc)))
1424 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001425
Douglas Gregor80723c52008-11-19 17:17:41 +00001426 // Perform overload resolution.
1427 OverloadCandidateSet::iterator Best;
1428 switch (BestViableFunction(CandidateSet, Best)) {
1429 case OR_Success: {
1430 // We found a built-in operator or an overloaded operator.
1431 FunctionDecl *FnDecl = Best->Function;
1432
1433 if (FnDecl) {
1434 // We matched an overloaded operator. Build a call to that
1435 // operator.
1436
1437 // Convert the arguments.
1438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1439 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1440 PerformCopyInitialization(RHSExp,
1441 FnDecl->getParamDecl(0)->getType(),
1442 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001443 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001444 } else {
1445 // Convert the arguments.
1446 if (PerformCopyInitialization(LHSExp,
1447 FnDecl->getParamDecl(0)->getType(),
1448 "passing") ||
1449 PerformCopyInitialization(RHSExp,
1450 FnDecl->getParamDecl(1)->getType(),
1451 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001452 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001453 }
1454
1455 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001456 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001457 = FnDecl->getType()->getAsFunctionType()->getResultType();
1458 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001459
Douglas Gregor80723c52008-11-19 17:17:41 +00001460 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001461 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1462 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001463 UsualUnaryConversions(FnExpr);
1464
Sebastian Redl8b769972009-01-19 00:08:26 +00001465 Base.release();
1466 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001467 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001468 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001469 } else {
1470 // We matched a built-in operator. Convert the arguments, then
1471 // break out so that we will build the appropriate built-in
1472 // operator node.
1473 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1474 "passing") ||
1475 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1476 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001477 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001478
1479 break;
1480 }
1481 }
1482
1483 case OR_No_Viable_Function:
1484 // No viable function; fall through to handling this as a
1485 // built-in operator, which will produce an error message for us.
1486 break;
1487
1488 case OR_Ambiguous:
1489 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1490 << "[]"
1491 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1492 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001493 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001494
1495 case OR_Deleted:
1496 Diag(LLoc, diag::err_ovl_deleted_oper)
1497 << Best->Function->isDeleted()
1498 << "[]"
1499 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1500 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1501 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001502 }
1503
1504 // Either we found no viable overloaded operator or we matched a
1505 // built-in operator. In either case, fall through to trying to
1506 // build a built-in operation.
1507 }
1508
Chris Lattner4b009652007-07-25 00:24:17 +00001509 // Perform default conversions.
1510 DefaultFunctionArrayConversion(LHSExp);
1511 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001512
Chris Lattner4b009652007-07-25 00:24:17 +00001513 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1514
1515 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001516 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001517 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001518 // and index from the expression types.
1519 Expr *BaseExpr, *IndexExpr;
1520 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001521 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1522 BaseExpr = LHSExp;
1523 IndexExpr = RHSExp;
1524 ResultType = Context.DependentTy;
1525 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001526 BaseExpr = LHSExp;
1527 IndexExpr = RHSExp;
1528 // FIXME: need to deal with const...
1529 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001530 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001531 // Handle the uncommon case of "123[Ptr]".
1532 BaseExpr = RHSExp;
1533 IndexExpr = LHSExp;
1534 // FIXME: need to deal with const...
1535 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001536 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1537 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001538 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001539
Chris Lattner4b009652007-07-25 00:24:17 +00001540 // FIXME: need to deal with const...
1541 ResultType = VTy->getElementType();
1542 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001543 return ExprError(Diag(LHSExp->getLocStart(),
1544 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1545 }
Chris Lattner4b009652007-07-25 00:24:17 +00001546 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001547 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001548 return ExprError(Diag(IndexExpr->getLocStart(),
1549 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001550
1551 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1552 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001553 // void (*)(int)) and pointers to incomplete types. Functions are not
1554 // objects in C99.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001555 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001556 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001557 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001558 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001559
Sebastian Redl8b769972009-01-19 00:08:26 +00001560 Base.release();
1561 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001562 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001563 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001564}
1565
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001566QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001567CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001568 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001569 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001570
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001571 // The vector accessor can't exceed the number of elements.
1572 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001573
Mike Stump9afab102009-02-19 03:04:26 +00001574 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001575 // special names that indicate a subset of exactly half the elements are
1576 // to be selected.
1577 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001578
Nate Begeman1486b502009-01-18 01:47:54 +00001579 // This flag determines whether or not CompName has an 's' char prefix,
1580 // indicating that it is a string of hex values to be used as vector indices.
1581 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001582
1583 // Check that we've found one of the special components, or that the component
1584 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001585 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001586 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1587 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001588 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001589 do
1590 compStr++;
1591 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001592 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001593 do
1594 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001595 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001596 }
Nate Begeman1486b502009-01-18 01:47:54 +00001597
Mike Stump9afab102009-02-19 03:04:26 +00001598 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001599 // We didn't get to the end of the string. This means the component names
1600 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001601 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1602 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001603 return QualType();
1604 }
Mike Stump9afab102009-02-19 03:04:26 +00001605
Nate Begeman1486b502009-01-18 01:47:54 +00001606 // Ensure no component accessor exceeds the width of the vector type it
1607 // operates on.
1608 if (!HalvingSwizzle) {
1609 compStr = CompName.getName();
1610
1611 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001612 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001613
1614 while (*compStr) {
1615 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1616 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1617 << baseType << SourceRange(CompLoc);
1618 return QualType();
1619 }
1620 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001621 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001622
Nate Begeman1486b502009-01-18 01:47:54 +00001623 // If this is a halving swizzle, verify that the base type has an even
1624 // number of elements.
1625 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001626 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001627 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001628 return QualType();
1629 }
Mike Stump9afab102009-02-19 03:04:26 +00001630
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001631 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001632 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001633 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001634 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001635 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001636 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1637 : CompName.getLength();
1638 if (HexSwizzle)
1639 CompSize--;
1640
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001641 if (CompSize == 1)
1642 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001643
Nate Begemanaf6ed502008-04-18 23:10:10 +00001644 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001645 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001646 // diagostics look bad. We want extended vector types to appear built-in.
1647 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1648 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1649 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001650 }
1651 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001652}
1653
Chris Lattner2cb744b2009-02-15 22:43:40 +00001654
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001655/// constructSetterName - Return the setter name for the given
1656/// identifier, i.e. "set" + Name where the initial character of Name
1657/// has been capitalized.
1658// FIXME: Merge with same routine in Parser. But where should this
1659// live?
1660static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1661 const IdentifierInfo *Name) {
1662 llvm::SmallString<100> SelectorName;
1663 SelectorName = "set";
1664 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1665 SelectorName[3] = toupper(SelectorName[3]);
1666 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1667}
1668
Sebastian Redl8b769972009-01-19 00:08:26 +00001669Action::OwningExprResult
1670Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1671 tok::TokenKind OpKind, SourceLocation MemberLoc,
1672 IdentifierInfo &Member) {
1673 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001674 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001675
1676 // Perform default conversions.
1677 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001678
Steve Naroff2cb66382007-07-26 03:11:44 +00001679 QualType BaseType = BaseExpr->getType();
1680 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001681
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001682 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1683 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001684 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001685 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001686 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001687 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001688 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1689 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001690 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001691 return ExprError(Diag(MemberLoc,
1692 diag::err_typecheck_member_reference_arrow)
1693 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001694 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001695
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001696 // Handle field access to simple records. This also handles access to fields
1697 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001698 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001699 RecordDecl *RDecl = RTy->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00001700 if (DiagnoseIncompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001701 diag::err_typecheck_incomplete_tag,
1702 BaseExpr->getSourceRange()))
1703 return ExprError();
1704
Steve Naroff2cb66382007-07-26 03:11:44 +00001705 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001706 // FIXME: Qualified name lookup for C++ is a bit more complicated
1707 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001708 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001709 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001710 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001711
Douglas Gregor09be81b2009-02-04 17:27:36 +00001712 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001713 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001714 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1715 << &Member << BaseExpr->getSourceRange());
1716 else if (Result.isAmbiguous()) {
1717 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1718 MemberLoc, BaseExpr->getSourceRange());
1719 return ExprError();
1720 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001721 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001722
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001723 // If the decl being referenced had an error, return an error for this
1724 // sub-expr without emitting another error, in order to avoid cascading
1725 // error cases.
1726 if (MemberDecl->isInvalidDecl())
1727 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001728
Douglas Gregoraa57e862009-02-18 21:56:37 +00001729 // Check the use of this field
1730 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1731 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001732
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001733 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001734 // We may have found a field within an anonymous union or struct
1735 // (C++ [class.union]).
1736 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001737 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001738 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001739
Douglas Gregor82d44772008-12-20 23:49:58 +00001740 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1741 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001742 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001743 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1744 MemberType = Ref->getPointeeType();
1745 else {
1746 unsigned combinedQualifiers =
1747 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001748 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001749 combinedQualifiers &= ~QualType::Const;
1750 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1751 }
Eli Friedman76b49832008-02-06 22:48:16 +00001752
Steve Naroff774e4152009-01-21 00:14:39 +00001753 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1754 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001755 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001756 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001757 Var, MemberLoc,
1758 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001759 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001760 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001761 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001762 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001763 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001764 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001765 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001766 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001767 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1768 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001769 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001770 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1771 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001772
Douglas Gregor82d44772008-12-20 23:49:58 +00001773 // We found a declaration kind that we didn't expect. This is a
1774 // generic error message that tells the user that she can't refer
1775 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001776 return ExprError(Diag(MemberLoc,
1777 diag::err_typecheck_member_reference_unknown)
1778 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001779 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001780
Chris Lattnere9d71612008-07-21 04:59:05 +00001781 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1782 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001783 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001784 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001785 // If the decl being referenced had an error, return an error for this
1786 // sub-expr without emitting another error, in order to avoid cascading
1787 // error cases.
1788 if (IV->isInvalidDecl())
1789 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001790
1791 // Check whether we can reference this field.
1792 if (DiagnoseUseOfDecl(IV, MemberLoc))
1793 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001794
1795 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001796 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001797 OpKind == tok::arrow);
1798 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001799 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001800 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001801 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1802 << IFTy->getDecl()->getDeclName() << &Member
1803 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001804 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001805
Chris Lattnere9d71612008-07-21 04:59:05 +00001806 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1807 // pointer to a (potentially qualified) interface type.
1808 const PointerType *PTy;
1809 const ObjCInterfaceType *IFTy;
1810 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1811 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1812 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001813
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001814 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001815 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001816 // Check whether we can reference this property.
1817 if (DiagnoseUseOfDecl(PD, MemberLoc))
1818 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001819
Steve Naroff774e4152009-01-21 00:14:39 +00001820 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001821 MemberLoc, BaseExpr));
1822 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001823
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001824 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001825 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1826 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001827 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001828 // Check whether we can reference this property.
1829 if (DiagnoseUseOfDecl(PD, MemberLoc))
1830 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001831
Steve Naroff774e4152009-01-21 00:14:39 +00001832 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001833 MemberLoc, BaseExpr));
1834 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001835
1836 // If that failed, look for an "implicit" property by seeing if the nullary
1837 // selector is implemented.
1838
1839 // FIXME: The logic for looking up nullary and unary selectors should be
1840 // shared with the code in ActOnInstanceMessage.
1841
1842 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1843 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001844
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001845 // If this reference is in an @implementation, check for 'private' methods.
1846 if (!Getter)
1847 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1848 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001849 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001850 ObjCImplementations[ClassDecl->getIdentifier()])
1851 Getter = ImpDecl->getInstanceMethod(Sel);
1852
Steve Naroff04151f32008-10-22 19:16:27 +00001853 // Look through local category implementations associated with the class.
1854 if (!Getter) {
1855 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1856 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1857 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1858 }
1859 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001860 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001861 // Check if we can reference this property.
1862 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1863 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001864
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001865 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001866 // will look for the matching setter, in case it is needed.
1867 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1868 &Member);
1869 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1870 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1871 if (!Setter) {
Mike Stump9afab102009-02-19 03:04:26 +00001872 // If this reference is in an @implementation, also check for 'private'
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001873 // methods.
1874 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1875 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001876 if (ObjCImplementationDecl *ImpDecl =
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001877 ObjCImplementations[ClassDecl->getIdentifier()])
1878 Setter = ImpDecl->getInstanceMethod(SetterSel);
1879 }
1880 // Look through local category implementations associated with the class.
1881 if (!Setter) {
1882 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1883 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1884 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1885 }
1886 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001887
Douglas Gregoraa57e862009-02-18 21:56:37 +00001888 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1889 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001890
Sebastian Redl8b769972009-01-19 00:08:26 +00001891 // FIXME: we must check that the setter has property type.
Mike Stump9afab102009-02-19 03:04:26 +00001892 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001893 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001894 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001895
1896 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1897 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001898 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001899 // Handle properties on qualified "id" protocols.
1900 const ObjCQualifiedIdType *QIdTy;
1901 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1902 // Check protocols on qualified interfaces.
1903 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001904 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001905 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001906 // Check the use of this declaration
1907 if (DiagnoseUseOfDecl(PD, MemberLoc))
1908 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001909
Steve Naroff774e4152009-01-21 00:14:39 +00001910 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001911 MemberLoc, BaseExpr));
1912 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001913 // Also must look for a getter name which uses property syntax.
1914 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1915 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001916 // Check the use of this method.
1917 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1918 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001919
1920 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001921 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001922 }
1923 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001924
1925 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1926 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001927 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001928 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001929 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001930 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1931 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001932 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001933 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00001934 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001935 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001936
1937 return ExprError(Diag(MemberLoc,
1938 diag::err_typecheck_member_reference_struct_union)
1939 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001940}
1941
Douglas Gregor3257fb52008-12-22 05:46:06 +00001942/// ConvertArgumentsForCall - Converts the arguments specified in
1943/// Args/NumArgs to the parameter types of the function FDecl with
1944/// function prototype Proto. Call is the call expression itself, and
1945/// Fn is the function expression. For a C++ member function, this
1946/// routine does not attempt to convert the object argument. Returns
1947/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00001948bool
1949Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001950 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001951 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001952 Expr **Args, unsigned NumArgs,
1953 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00001954 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00001955 // assignment, to the types of the corresponding parameter, ...
1956 unsigned NumArgsInProto = Proto->getNumArgs();
1957 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001958 bool Invalid = false;
1959
Douglas Gregor3257fb52008-12-22 05:46:06 +00001960 // If too few arguments are available (and we don't have default
1961 // arguments for the remaining parameters), don't make the call.
1962 if (NumArgs < NumArgsInProto) {
1963 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1964 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1965 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1966 // Use default arguments for missing arguments
1967 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001968 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001969 }
1970
1971 // If too many are passed and not variadic, error on the extras and drop
1972 // them.
1973 if (NumArgs > NumArgsInProto) {
1974 if (!Proto->isVariadic()) {
1975 Diag(Args[NumArgsInProto]->getLocStart(),
1976 diag::err_typecheck_call_too_many_args)
1977 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1978 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1979 Args[NumArgs-1]->getLocEnd());
1980 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001981 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001982 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001983 }
1984 NumArgsToCheck = NumArgsInProto;
1985 }
Mike Stump9afab102009-02-19 03:04:26 +00001986
Douglas Gregor3257fb52008-12-22 05:46:06 +00001987 // Continue to check argument types (even if we have too few/many args).
1988 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1989 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00001990
Douglas Gregor3257fb52008-12-22 05:46:06 +00001991 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001992 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001993 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001994
1995 // Pass the argument.
1996 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1997 return true;
Mike Stump9afab102009-02-19 03:04:26 +00001998 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001999 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002000 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002001 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002002
Douglas Gregor3257fb52008-12-22 05:46:06 +00002003 Call->setArg(i, Arg);
2004 }
Mike Stump9afab102009-02-19 03:04:26 +00002005
Douglas Gregor3257fb52008-12-22 05:46:06 +00002006 // If this is a variadic call, handle args passed through "...".
2007 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002008 VariadicCallType CallType = VariadicFunction;
2009 if (Fn->getType()->isBlockPointerType())
2010 CallType = VariadicBlock; // Block
2011 else if (isa<MemberExpr>(Fn))
2012 CallType = VariadicMethod;
2013
Douglas Gregor3257fb52008-12-22 05:46:06 +00002014 // Promote the arguments (C99 6.5.2.2p7).
2015 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2016 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002017 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002018 Call->setArg(i, Arg);
2019 }
2020 }
2021
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002022 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002023}
2024
Steve Naroff87d58b42007-09-16 03:34:24 +00002025/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002026/// This provides the location of the left/right parens and a list of comma
2027/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002028Action::OwningExprResult
2029Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2030 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002031 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002032 unsigned NumArgs = args.size();
2033 Expr *Fn = static_cast<Expr *>(fn.release());
2034 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002035 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002036 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002037 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002038
Douglas Gregor3257fb52008-12-22 05:46:06 +00002039 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002040 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002041 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002042 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2043 bool Dependent = false;
2044 if (Fn->isTypeDependent())
2045 Dependent = true;
2046 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2047 Dependent = true;
2048
2049 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002050 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002051 Context.DependentTy, RParenLoc));
2052
2053 // Determine whether this is a call to an object (C++ [over.call.object]).
2054 if (Fn->getType()->isRecordType())
2055 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2056 CommaLocs, RParenLoc));
2057
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002058 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002059 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2060 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2061 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002062 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2063 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002064 }
2065
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002066 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002067 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002068 Expr *FnExpr = Fn;
2069 bool ADL = true;
2070 while (true) {
2071 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2072 FnExpr = IcExpr->getSubExpr();
2073 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002074 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002075 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002076 ADL = false;
2077 FnExpr = PExpr->getSubExpr();
2078 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002079 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002080 == UnaryOperator::AddrOf) {
2081 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002082 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2083 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2084 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2085 break;
Mike Stump9afab102009-02-19 03:04:26 +00002086 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002087 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2088 UnqualifiedName = DepName->getName();
2089 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002090 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002091 // Any kind of name that does not refer to a declaration (or
2092 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2093 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002094 break;
2095 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002096 }
Mike Stump9afab102009-02-19 03:04:26 +00002097
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002098 OverloadedFunctionDecl *Ovl = 0;
2099 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002100 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002101 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2102 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002103
Douglas Gregorfcb19192009-02-11 23:02:49 +00002104 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002105 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002106 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002107 ADL = false;
2108
Douglas Gregorfcb19192009-02-11 23:02:49 +00002109 // We don't perform ADL in C.
2110 if (!getLangOptions().CPlusPlus)
2111 ADL = false;
2112
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002113 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002114 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2115 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002116 NumArgs, CommaLocs, RParenLoc, ADL);
2117 if (!FDecl)
2118 return ExprError();
2119
2120 // Update Fn to refer to the actual function selected.
2121 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002122 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002123 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stump9afab102009-02-19 03:04:26 +00002124 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2125 QDRExpr->getLocation(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002126 false, false,
2127 QDRExpr->getSourceRange().getBegin());
2128 else
Mike Stump9afab102009-02-19 03:04:26 +00002129 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002130 Fn->getSourceRange().getBegin());
2131 Fn->Destroy(Context);
2132 Fn = NewFn;
2133 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002134 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002135
2136 // Promote the function operand.
2137 UsualUnaryConversions(Fn);
2138
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002139 // Make the call expr early, before semantic checks. This guarantees cleanup
2140 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002141 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2142 Args, NumArgs,
2143 Context.BoolTy,
2144 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002145
Steve Naroffd6163f32008-09-05 22:11:13 +00002146 const FunctionType *FuncT;
2147 if (!Fn->getType()->isBlockPointerType()) {
2148 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2149 // have type pointer to function".
2150 const PointerType *PT = Fn->getType()->getAsPointerType();
2151 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002152 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2153 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002154 FuncT = PT->getPointeeType()->getAsFunctionType();
2155 } else { // This is a block call.
2156 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2157 getAsFunctionType();
2158 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002159 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002160 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2161 << Fn->getType() << Fn->getSourceRange());
2162
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002163 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002164 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002165
Douglas Gregor4fa58902009-02-26 23:50:07 +00002166 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002167 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002168 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002169 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002170 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002171 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002172
Steve Naroffdb65e052007-08-28 23:30:39 +00002173 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002174 for (unsigned i = 0; i != NumArgs; i++) {
2175 Expr *Arg = Args[i];
2176 DefaultArgumentPromotion(Arg);
2177 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002178 }
Chris Lattner4b009652007-07-25 00:24:17 +00002179 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002180
Douglas Gregor3257fb52008-12-22 05:46:06 +00002181 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2182 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002183 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2184 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002185
Chris Lattner2e64c072007-08-10 20:18:51 +00002186 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002187 if (FDecl)
2188 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002189
Sebastian Redl8b769972009-01-19 00:08:26 +00002190 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002191}
2192
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002193Action::OwningExprResult
2194Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2195 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002196 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002197 QualType literalType = QualType::getFromOpaquePtr(Ty);
2198 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002199 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002200 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002201
Eli Friedman8c2173d2008-05-20 05:22:08 +00002202 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002203 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002204 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2205 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002206 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2207 diag::err_typecheck_decl_incomplete_type,
2208 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002209 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002210
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002211 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002212 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002213 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002214
Chris Lattnere5cb5862008-12-04 23:50:19 +00002215 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002216 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002217 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002218 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002219 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002220 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002221 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002222 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002223}
2224
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002225Action::OwningExprResult
2226Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2227 InitListDesignations &Designators,
2228 SourceLocation RBraceLoc) {
2229 unsigned NumInit = initlist.size();
2230 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002231
Steve Naroff0acc9c92007-09-15 18:49:24 +00002232 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002233 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002234
Mike Stump9afab102009-02-19 03:04:26 +00002235 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002236 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002237 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002238 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002239}
2240
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002241/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002242bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002243 UsualUnaryConversions(castExpr);
2244
2245 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2246 // type needs to be scalar.
2247 if (castType->isVoidType()) {
2248 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002249 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2250 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002251 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002252 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2253 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2254 (castType->isStructureType() || castType->isUnionType())) {
2255 // GCC struct/union extension: allow cast to self.
2256 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2257 << castType << castExpr->getSourceRange();
2258 } else if (castType->isUnionType()) {
2259 // GCC cast to union extension
2260 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2261 RecordDecl::field_iterator Field, FieldEnd;
2262 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2263 Field != FieldEnd; ++Field) {
2264 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2265 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2266 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2267 << castExpr->getSourceRange();
2268 break;
2269 }
2270 }
2271 if (Field == FieldEnd)
2272 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2273 << castExpr->getType() << castExpr->getSourceRange();
2274 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002275 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002276 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002277 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002278 }
Mike Stump9afab102009-02-19 03:04:26 +00002279 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002280 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002281 return Diag(castExpr->getLocStart(),
2282 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002283 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002284 } else if (castExpr->getType()->isVectorType()) {
2285 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2286 return true;
2287 } else if (castType->isVectorType()) {
2288 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2289 return true;
2290 }
2291 return false;
2292}
2293
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002294bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002295 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002296
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002297 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002298 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002299 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002300 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002301 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002302 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002303 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002304 } else
2305 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002306 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002307 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002308
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002309 return false;
2310}
2311
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002312Action::OwningExprResult
2313Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2314 SourceLocation RParenLoc, ExprArg Op) {
2315 assert((Ty != 0) && (Op.get() != 0) &&
2316 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002317
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002318 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002319 QualType castType = QualType::getFromOpaquePtr(Ty);
2320
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002321 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002322 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002323 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002324 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002325}
2326
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002327/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2328/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002329/// C99 6.5.15
2330QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2331 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002332 UsualUnaryConversions(Cond);
2333 UsualUnaryConversions(LHS);
2334 UsualUnaryConversions(RHS);
2335 QualType CondTy = Cond->getType();
2336 QualType LHSTy = LHS->getType();
2337 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002338
2339 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002340 if (!Cond->isTypeDependent()) {
2341 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2342 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2343 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002344 return QualType();
2345 }
Chris Lattner4b009652007-07-25 00:24:17 +00002346 }
Mike Stump9afab102009-02-19 03:04:26 +00002347
Chris Lattner992ae932008-01-06 22:42:25 +00002348 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002349 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002350 return Context.DependentTy;
2351
Chris Lattner992ae932008-01-06 22:42:25 +00002352 // If both operands have arithmetic type, do the usual arithmetic conversions
2353 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002354 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2355 UsualArithmeticConversions(LHS, RHS);
2356 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002357 }
Mike Stump9afab102009-02-19 03:04:26 +00002358
Chris Lattner992ae932008-01-06 22:42:25 +00002359 // If both operands are the same structure or union type, the result is that
2360 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002361 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2362 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002363 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002364 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002365 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002366 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002367 }
Mike Stump9afab102009-02-19 03:04:26 +00002368
Chris Lattner992ae932008-01-06 22:42:25 +00002369 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002370 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002371 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2372 if (!LHSTy->isVoidType())
2373 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2374 << RHS->getSourceRange();
2375 if (!RHSTy->isVoidType())
2376 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2377 << LHS->getSourceRange();
2378 ImpCastExprToType(LHS, Context.VoidTy);
2379 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002380 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002381 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002382 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2383 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002384 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2385 Context.isObjCObjectPointerType(LHSTy)) &&
2386 RHS->isNullPointerConstant(Context)) {
2387 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2388 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002389 }
Chris Lattnere2897262009-02-18 04:28:32 +00002390 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2391 Context.isObjCObjectPointerType(RHSTy)) &&
2392 LHS->isNullPointerConstant(Context)) {
2393 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2394 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002395 }
Mike Stump9afab102009-02-19 03:04:26 +00002396
Chris Lattner0ac51632008-01-06 22:50:31 +00002397 // Handle the case where both operands are pointers before we handle null
2398 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002399 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2400 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002401 // get the "pointed to" types
2402 QualType lhptee = LHSPT->getPointeeType();
2403 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002404
Chris Lattner71225142007-07-31 21:27:01 +00002405 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2406 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002407 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002408 // Figure out necessary qualifiers (C99 6.5.15p6)
2409 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002410 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002411 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2412 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002413 return destType;
2414 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002415 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002416 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002417 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002418 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2419 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002420 return destType;
2421 }
Chris Lattner4b009652007-07-25 00:24:17 +00002422
Chris Lattner9c039b52009-02-18 04:38:20 +00002423 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002424 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002425 return LHSTy;
2426 }
Mike Stump9afab102009-02-19 03:04:26 +00002427
Chris Lattnere2897262009-02-18 04:28:32 +00002428 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002429
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002430 // If either type is an Objective-C object type then check
2431 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002432 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002433 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002434 // If both operands are interfaces and either operand can be
2435 // assigned to the other, use that type as the composite
2436 // type. This allows
2437 // xxx ? (A*) a : (B*) b
2438 // where B is a subclass of A.
2439 //
2440 // Additionally, as for assignment, if either type is 'id'
2441 // allow silent coercion. Finally, if the types are
2442 // incompatible then make sure to use 'id' as the composite
2443 // type so the result is acceptable for sending messages to.
2444
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002445 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002446 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002447 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2448 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2449 if (LHSIface && RHSIface &&
2450 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002451 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002452 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002453 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002454 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002455 } else if (Context.isObjCIdStructType(lhptee) ||
2456 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002457 compositeType = Context.getObjCIdType();
2458 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002459 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002460 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002461 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002462 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002463 ImpCastExprToType(LHS, incompatTy);
2464 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002465 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002466 }
Mike Stump9afab102009-02-19 03:04:26 +00002467 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002468 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002469 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2470 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002471 // In this situation, we assume void* type. No especially good
2472 // reason, but this is what gcc does, and we do have to pick
2473 // to get a consistent AST.
2474 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002475 ImpCastExprToType(LHS, incompatTy);
2476 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002477 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002478 }
2479 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002480 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2481 // differently qualified versions of compatible types, the result type is
2482 // a pointer to an appropriately qualified version of the *composite*
2483 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002484 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002485 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002486 ImpCastExprToType(LHS, compositeType);
2487 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002488 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002489 }
Chris Lattner4b009652007-07-25 00:24:17 +00002490 }
Mike Stump9afab102009-02-19 03:04:26 +00002491
Chris Lattner9c039b52009-02-18 04:38:20 +00002492 // Selection between block pointer types is ok as long as they are the same.
2493 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2494 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2495 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002496
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002497 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2498 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002499 // id with statically typed objects).
2500 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002501 // GCC allows qualified id and any Objective-C type to devolve to
2502 // id. Currently localizing to here until clear this should be
2503 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002504 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002505 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002506 Context.isObjCObjectPointerType(RHSTy)) ||
2507 (RHSTy->isObjCQualifiedIdType() &&
2508 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002509 // FIXME: This is not the correct composite type. This only
2510 // happens to work because id can more or less be used anywhere,
2511 // however this may change the type of method sends.
2512 // FIXME: gcc adds some type-checking of the arguments and emits
2513 // (confusing) incompatible comparison warnings in some
2514 // cases. Investigate.
2515 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002516 ImpCastExprToType(LHS, compositeType);
2517 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002518 return compositeType;
2519 }
2520 }
2521
Chris Lattner992ae932008-01-06 22:42:25 +00002522 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002523 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2524 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002525 return QualType();
2526}
2527
Steve Naroff87d58b42007-09-16 03:34:24 +00002528/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002529/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002530Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2531 SourceLocation ColonLoc,
2532 ExprArg Cond, ExprArg LHS,
2533 ExprArg RHS) {
2534 Expr *CondExpr = (Expr *) Cond.get();
2535 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002536
2537 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2538 // was the condition.
2539 bool isLHSNull = LHSExpr == 0;
2540 if (isLHSNull)
2541 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002542
2543 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002544 RHSExpr, QuestionLoc);
2545 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002546 return ExprError();
2547
2548 Cond.release();
2549 LHS.release();
2550 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002551 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002552 isLHSNull ? 0 : LHSExpr,
2553 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002554}
2555
Chris Lattner4b009652007-07-25 00:24:17 +00002556
2557// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002558// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002559// routine is it effectively iqnores the qualifiers on the top level pointee.
2560// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2561// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002562Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002563Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2564 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002565
Chris Lattner4b009652007-07-25 00:24:17 +00002566 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002567 lhptee = lhsType->getAsPointerType()->getPointeeType();
2568 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002569
Chris Lattner4b009652007-07-25 00:24:17 +00002570 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002571 lhptee = Context.getCanonicalType(lhptee);
2572 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002573
Chris Lattner005ed752008-01-04 18:04:52 +00002574 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002575
2576 // C99 6.5.16.1p1: This following citation is common to constraints
2577 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2578 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002579 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002580 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002581 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002582
Mike Stump9afab102009-02-19 03:04:26 +00002583 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2584 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002585 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002586 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002587 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002588 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002589
Chris Lattner4ca3d772008-01-03 22:56:36 +00002590 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002591 assert(rhptee->isFunctionType());
2592 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002593 }
Mike Stump9afab102009-02-19 03:04:26 +00002594
Chris Lattner4ca3d772008-01-03 22:56:36 +00002595 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002596 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002597 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002598
2599 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002600 assert(lhptee->isFunctionType());
2601 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002602 }
Mike Stump9afab102009-02-19 03:04:26 +00002603 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002604 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002605 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002606 rhptee.getUnqualifiedType()))
2607 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002608 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002609}
2610
Steve Naroff3454b6c2008-09-04 15:10:53 +00002611/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2612/// block pointer types are compatible or whether a block and normal pointer
2613/// are compatible. It is more restrict than comparing two function pointer
2614// types.
Mike Stump9afab102009-02-19 03:04:26 +00002615Sema::AssignConvertType
2616Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002617 QualType rhsType) {
2618 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002619
Steve Naroff3454b6c2008-09-04 15:10:53 +00002620 // get the "pointed to" type (ignoring qualifiers at the top level)
2621 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002622 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2623
Steve Naroff3454b6c2008-09-04 15:10:53 +00002624 // make sure we operate on the canonical type
2625 lhptee = Context.getCanonicalType(lhptee);
2626 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002627
Steve Naroff3454b6c2008-09-04 15:10:53 +00002628 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002629
Steve Naroff3454b6c2008-09-04 15:10:53 +00002630 // For blocks we enforce that qualifiers are identical.
2631 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2632 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002633
Steve Naroff3454b6c2008-09-04 15:10:53 +00002634 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002635 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002636 return ConvTy;
2637}
2638
Mike Stump9afab102009-02-19 03:04:26 +00002639/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2640/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002641/// pointers. Here are some objectionable examples that GCC considers warnings:
2642///
2643/// int a, *pint;
2644/// short *pshort;
2645/// struct foo *pfoo;
2646///
2647/// pint = pshort; // warning: assignment from incompatible pointer type
2648/// a = pint; // warning: assignment makes integer from pointer without a cast
2649/// pint = a; // warning: assignment makes pointer from integer without a cast
2650/// pint = pfoo; // warning: assignment from incompatible pointer type
2651///
2652/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002653/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002654///
Chris Lattner005ed752008-01-04 18:04:52 +00002655Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002656Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002657 // Get canonical types. We're not formatting these types, just comparing
2658 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002659 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2660 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002661
2662 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002663 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002664
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002665 // If the left-hand side is a reference type, then we are in a
2666 // (rare!) case where we've allowed the use of references in C,
2667 // e.g., as a parameter type in a built-in function. In this case,
2668 // just make sure that the type referenced is compatible with the
2669 // right-hand side type. The caller is responsible for adjusting
2670 // lhsType so that the resulting expression does not have reference
2671 // type.
2672 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2673 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002674 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002675 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002676 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002677
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002678 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2679 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002680 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002681 // Relax integer conversions like we do for pointers below.
2682 if (rhsType->isIntegerType())
2683 return IntToPointer;
2684 if (lhsType->isIntegerType())
2685 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002686 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002687 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002688
Nate Begemanc5f0f652008-07-14 18:02:46 +00002689 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002690 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002691 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2692 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002693 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002694
Nate Begemanc5f0f652008-07-14 18:02:46 +00002695 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002696 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002697 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002698 if (getLangOptions().LaxVectorConversions &&
2699 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002700 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002701 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002702 }
2703 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002704 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002705
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002706 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002707 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002708
Chris Lattner390564e2008-04-07 06:49:41 +00002709 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002710 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002711 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002712
Chris Lattner390564e2008-04-07 06:49:41 +00002713 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002714 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002715
Steve Naroffa982c712008-09-29 18:10:17 +00002716 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002717 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002718 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002719
2720 // Treat block pointers as objects.
2721 if (getLangOptions().ObjC1 &&
2722 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2723 return Compatible;
2724 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002725 return Incompatible;
2726 }
2727
2728 if (isa<BlockPointerType>(lhsType)) {
2729 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002730 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002731
Steve Naroffa982c712008-09-29 18:10:17 +00002732 // Treat block pointers as objects.
2733 if (getLangOptions().ObjC1 &&
2734 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2735 return Compatible;
2736
Steve Naroff3454b6c2008-09-04 15:10:53 +00002737 if (rhsType->isBlockPointerType())
2738 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002739
Steve Naroff3454b6c2008-09-04 15:10:53 +00002740 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2741 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002742 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002743 }
Chris Lattner1853da22008-01-04 23:18:45 +00002744 return Incompatible;
2745 }
2746
Chris Lattner390564e2008-04-07 06:49:41 +00002747 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002748 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002749 if (lhsType == Context.BoolTy)
2750 return Compatible;
2751
2752 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002753 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002754
Mike Stump9afab102009-02-19 03:04:26 +00002755 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002756 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002757
2758 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002759 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002760 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002761 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002762 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002763
Chris Lattner1853da22008-01-04 23:18:45 +00002764 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002765 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002766 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002767 }
2768 return Incompatible;
2769}
2770
Chris Lattner005ed752008-01-04 18:04:52 +00002771Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002772Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002773 if (getLangOptions().CPlusPlus) {
2774 if (!lhsType->isRecordType()) {
2775 // C++ 5.17p3: If the left operand is not of class type, the
2776 // expression is implicitly converted (C++ 4) to the
2777 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002778 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2779 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002780 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002781 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002782 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002783 }
2784
2785 // FIXME: Currently, we fall through and treat C++ classes like C
2786 // structures.
2787 }
2788
Steve Naroffcdee22d2007-11-27 17:58:44 +00002789 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2790 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002791 if ((lhsType->isPointerType() ||
2792 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002793 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002794 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002795 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002796 return Compatible;
2797 }
Mike Stump9afab102009-02-19 03:04:26 +00002798
Chris Lattner5f505bf2007-10-16 02:55:40 +00002799 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002800 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002801 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002802 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002803 //
Mike Stump9afab102009-02-19 03:04:26 +00002804 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002805 if (!lhsType->isReferenceType())
2806 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002807
Chris Lattner005ed752008-01-04 18:04:52 +00002808 Sema::AssignConvertType result =
2809 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002810
Steve Naroff0f32f432007-08-24 22:33:52 +00002811 // C99 6.5.16.1p2: The value of the right operand is converted to the
2812 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002813 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2814 // so that we can use references in built-in functions even in C.
2815 // The getNonReferenceType() call makes sure that the resulting expression
2816 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002817 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002818 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002819 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002820}
2821
Chris Lattner005ed752008-01-04 18:04:52 +00002822Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002823Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2824 return CheckAssignmentConstraints(lhsType, rhsType);
2825}
2826
Chris Lattner1eafdea2008-11-18 01:30:42 +00002827QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002828 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002829 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002830 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002831 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002832}
2833
Mike Stump9afab102009-02-19 03:04:26 +00002834inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002835 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002836 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002837 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002838 QualType lhsType =
2839 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2840 QualType rhsType =
2841 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002842
Nate Begemanc5f0f652008-07-14 18:02:46 +00002843 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002844 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002845 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002846
Nate Begemanc5f0f652008-07-14 18:02:46 +00002847 // Handle the case of a vector & extvector type of the same size and element
2848 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002849 if (getLangOptions().LaxVectorConversions) {
2850 // FIXME: Should we warn here?
2851 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002852 if (const VectorType *RV = rhsType->getAsVectorType())
2853 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002854 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002855 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002856 }
2857 }
2858 }
Mike Stump9afab102009-02-19 03:04:26 +00002859
Nate Begemanc5f0f652008-07-14 18:02:46 +00002860 // If the lhs is an extended vector and the rhs is a scalar of the same type
2861 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002862 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002863 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002864
2865 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002866 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2867 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002868 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002869 return lhsType;
2870 }
2871 }
2872
Nate Begemanc5f0f652008-07-14 18:02:46 +00002873 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002874 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002875 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002876 QualType eltType = V->getElementType();
2877
Mike Stump9afab102009-02-19 03:04:26 +00002878 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002879 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2880 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002881 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002882 return rhsType;
2883 }
2884 }
2885
Chris Lattner4b009652007-07-25 00:24:17 +00002886 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002887 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002888 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002889 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002890 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002891}
2892
Chris Lattner4b009652007-07-25 00:24:17 +00002893inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002894 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002895{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002896 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002897 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002898
Steve Naroff8f708362007-08-24 19:07:16 +00002899 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002900
Chris Lattner4b009652007-07-25 00:24:17 +00002901 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002902 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002903 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002904}
2905
2906inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002907 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002908{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002909 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2910 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2911 return CheckVectorOperands(Loc, lex, rex);
2912 return InvalidOperands(Loc, lex, rex);
2913 }
Chris Lattner4b009652007-07-25 00:24:17 +00002914
Steve Naroff8f708362007-08-24 19:07:16 +00002915 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002916
Chris Lattner4b009652007-07-25 00:24:17 +00002917 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002918 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002919 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002920}
2921
2922inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00002923 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002924{
2925 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002926 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002927
Steve Naroff8f708362007-08-24 19:07:16 +00002928 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002929
Chris Lattner4b009652007-07-25 00:24:17 +00002930 // handle the common case first (both operands are arithmetic).
2931 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002932 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002933
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002934 // Put any potential pointer into PExp
2935 Expr* PExp = lex, *IExp = rex;
2936 if (IExp->getType()->isPointerType())
2937 std::swap(PExp, IExp);
2938
2939 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2940 if (IExp->getType()->isIntegerType()) {
2941 // Check for arithmetic on pointers to incomplete types
2942 if (!PTy->getPointeeType()->isObjectType()) {
2943 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002944 if (getLangOptions().CPlusPlus) {
2945 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2946 << lex->getSourceRange() << rex->getSourceRange();
2947 return QualType();
2948 }
2949
2950 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002951 Diag(Loc, diag::ext_gnu_void_ptr)
2952 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002953 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002954 if (getLangOptions().CPlusPlus) {
2955 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2956 << lex->getType() << lex->getSourceRange();
2957 return QualType();
2958 }
2959
2960 // GNU extension: arithmetic on pointer to function
2961 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002962 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002963 } else {
Mike Stump9afab102009-02-19 03:04:26 +00002964 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002965 diag::err_typecheck_arithmetic_incomplete_type,
2966 lex->getSourceRange(), SourceRange(),
2967 lex->getType());
2968 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002969 }
2970 }
2971 return PExp->getType();
2972 }
2973 }
2974
Chris Lattner1eafdea2008-11-18 01:30:42 +00002975 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002976}
2977
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002978// C99 6.5.6
2979QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002980 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002981 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002982 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002983
Steve Naroff8f708362007-08-24 19:07:16 +00002984 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002985
Chris Lattnerf6da2912007-12-09 21:53:25 +00002986 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00002987
Chris Lattnerf6da2912007-12-09 21:53:25 +00002988 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002989 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002990 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00002991
Chris Lattnerf6da2912007-12-09 21:53:25 +00002992 // Either ptr - int or ptr - ptr.
2993 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002994 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002995
Chris Lattnerf6da2912007-12-09 21:53:25 +00002996 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002997 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002998 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002999 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003000 Diag(Loc, diag::ext_gnu_void_ptr)
3001 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00003002 } else if (lpointee->isFunctionType()) {
3003 if (getLangOptions().CPlusPlus) {
3004 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3005 << lex->getType() << lex->getSourceRange();
3006 return QualType();
3007 }
3008
3009 // GNU extension: arithmetic on pointer to function
3010 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3011 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003012 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003013 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003014 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003015 return QualType();
3016 }
3017 }
3018
3019 // The result type of a pointer-int computation is the pointer type.
3020 if (rex->getType()->isIntegerType())
3021 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003022
Chris Lattnerf6da2912007-12-09 21:53:25 +00003023 // Handle pointer-pointer subtractions.
3024 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003025 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003026
Chris Lattnerf6da2912007-12-09 21:53:25 +00003027 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00003028 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003029 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003030 if (rpointee->isVoidType()) {
3031 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00003032 Diag(Loc, diag::ext_gnu_void_ptr)
3033 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00003034 } else if (rpointee->isFunctionType()) {
3035 if (getLangOptions().CPlusPlus) {
3036 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3037 << rex->getType() << rex->getSourceRange();
3038 return QualType();
3039 }
Mike Stump9afab102009-02-19 03:04:26 +00003040
Douglas Gregorf93eda12009-01-23 19:03:35 +00003041 // GNU extension: arithmetic on pointer to function
3042 if (!lpointee->isFunctionType())
3043 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3044 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003045 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003046 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003047 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003048 return QualType();
3049 }
3050 }
Mike Stump9afab102009-02-19 03:04:26 +00003051
Chris Lattnerf6da2912007-12-09 21:53:25 +00003052 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003053 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003054 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003055 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003056 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003057 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003058 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003059 return QualType();
3060 }
Mike Stump9afab102009-02-19 03:04:26 +00003061
Chris Lattnerf6da2912007-12-09 21:53:25 +00003062 return Context.getPointerDiffType();
3063 }
3064 }
Mike Stump9afab102009-02-19 03:04:26 +00003065
Chris Lattner1eafdea2008-11-18 01:30:42 +00003066 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003067}
3068
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003069// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003070QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003071 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003072 // C99 6.5.7p2: Each of the operands shall have integer type.
3073 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003074 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003075
Chris Lattner2c8bff72007-12-12 05:47:28 +00003076 // Shifts don't perform usual arithmetic conversions, they just do integer
3077 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003078 if (!isCompAssign)
3079 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003080 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003081
Chris Lattner2c8bff72007-12-12 05:47:28 +00003082 // "The type of the result is that of the promoted left operand."
3083 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003084}
3085
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003086// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003087QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003088 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003089 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003090 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003091
Chris Lattner254f3bc2007-08-26 01:18:55 +00003092 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003093 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3094 UsualArithmeticConversions(lex, rex);
3095 else {
3096 UsualUnaryConversions(lex);
3097 UsualUnaryConversions(rex);
3098 }
Chris Lattner4b009652007-07-25 00:24:17 +00003099 QualType lType = lex->getType();
3100 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003101
Ted Kremenek486509e2007-10-29 17:13:39 +00003102 // For non-floating point types, check for self-comparisons of the form
3103 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3104 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003105 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003106 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3107 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003108 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003109 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003110 }
Mike Stump9afab102009-02-19 03:04:26 +00003111
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003112 // The result of comparisons is 'bool' in C++, 'int' in C.
3113 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3114
Chris Lattner254f3bc2007-08-26 01:18:55 +00003115 if (isRelational) {
3116 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003117 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003118 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003119 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003120 if (lType->isFloatingType()) {
3121 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003122 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003123 }
Mike Stump9afab102009-02-19 03:04:26 +00003124
Chris Lattner254f3bc2007-08-26 01:18:55 +00003125 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003126 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003127 }
Mike Stump9afab102009-02-19 03:04:26 +00003128
Chris Lattner22be8422007-08-26 01:10:14 +00003129 bool LHSIsNull = lex->isNullPointerConstant(Context);
3130 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003131
Chris Lattner254f3bc2007-08-26 01:18:55 +00003132 // All of the following pointer related warnings are GCC extensions, except
3133 // when handling null pointer constants. One day, we can consider making them
3134 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003135 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003136 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003137 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003138 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003139 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003140
Steve Naroff3b435622007-11-13 14:57:38 +00003141 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003142 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3143 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003144 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003145 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003146 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003147 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003148 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003149 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003150 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003151 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003152 // Handle block pointer types.
3153 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3154 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3155 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003156
Steve Naroff3454b6c2008-09-04 15:10:53 +00003157 if (!LHSIsNull && !RHSIsNull &&
3158 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003159 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003160 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003161 }
3162 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003163 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003164 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003165 // Allow block pointers to be compared with null pointer constants.
3166 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3167 (lType->isPointerType() && rType->isBlockPointerType())) {
3168 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003169 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003170 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003171 }
3172 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003173 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003174 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003175
Steve Naroff936c4362008-06-03 14:04:54 +00003176 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003177 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003178 const PointerType *LPT = lType->getAsPointerType();
3179 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003180 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003181 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003182 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003183 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003184
Steve Naroff030fcda2008-11-17 19:49:16 +00003185 if (!LPtrToVoid && !RPtrToVoid &&
3186 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003187 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003188 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003189 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003190 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003191 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003192 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003193 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003194 }
Steve Naroff936c4362008-06-03 14:04:54 +00003195 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3196 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003197 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003198 } else {
3199 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003200 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003201 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003202 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003203 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003204 }
Steve Naroff936c4362008-06-03 14:04:54 +00003205 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003206 }
Mike Stump9afab102009-02-19 03:04:26 +00003207 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003208 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003209 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003210 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003211 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003212 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003213 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003214 }
Mike Stump9afab102009-02-19 03:04:26 +00003215 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003216 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003217 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003218 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003219 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003220 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003221 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003222 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003223 // Handle block pointers.
3224 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3225 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003226 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003227 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003228 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003229 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003230 }
3231 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3232 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003233 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003234 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003235 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003236 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003237 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003238 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003239}
3240
Nate Begemanc5f0f652008-07-14 18:02:46 +00003241/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003242/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003243/// like a scalar comparison, a vector comparison produces a vector of integer
3244/// types.
3245QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003246 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003247 bool isRelational) {
3248 // Check to make sure we're operating on vectors of the same type and width,
3249 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003250 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003251 if (vType.isNull())
3252 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003253
Nate Begemanc5f0f652008-07-14 18:02:46 +00003254 QualType lType = lex->getType();
3255 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003256
Nate Begemanc5f0f652008-07-14 18:02:46 +00003257 // For non-floating point types, check for self-comparisons of the form
3258 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3259 // often indicate logic errors in the program.
3260 if (!lType->isFloatingType()) {
3261 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3262 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3263 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003264 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003265 }
Mike Stump9afab102009-02-19 03:04:26 +00003266
Nate Begemanc5f0f652008-07-14 18:02:46 +00003267 // Check for comparisons of floating point operands using != and ==.
3268 if (!isRelational && lType->isFloatingType()) {
3269 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003270 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003271 }
Mike Stump9afab102009-02-19 03:04:26 +00003272
Nate Begemanc5f0f652008-07-14 18:02:46 +00003273 // Return the type for the comparison, which is the same as vector type for
3274 // integer vectors, or an integer type of identical size and number of
3275 // elements for floating point vectors.
3276 if (lType->isIntegerType())
3277 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003278
Nate Begemanc5f0f652008-07-14 18:02:46 +00003279 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003280 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003281 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003282 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003283 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3284 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3285
Mike Stump9afab102009-02-19 03:04:26 +00003286 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003287 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003288 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3289}
3290
Chris Lattner4b009652007-07-25 00:24:17 +00003291inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003292 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003293{
3294 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003295 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003296
Steve Naroff8f708362007-08-24 19:07:16 +00003297 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003298
Chris Lattner4b009652007-07-25 00:24:17 +00003299 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003300 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003301 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003302}
3303
3304inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003305 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003306{
3307 UsualUnaryConversions(lex);
3308 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003309
Eli Friedmanbea3f842008-05-13 20:16:47 +00003310 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003311 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003312 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003313}
3314
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003315/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3316/// is a read-only property; return true if so. A readonly property expression
3317/// depends on various declarations and thus must be treated specially.
3318///
Mike Stump9afab102009-02-19 03:04:26 +00003319static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003320{
3321 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3322 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3323 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3324 QualType BaseType = PropExpr->getBase()->getType();
3325 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003326 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003327 PTy->getPointeeType()->getAsObjCInterfaceType())
3328 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3329 if (S.isPropertyReadonly(PDecl, IFace))
3330 return true;
3331 }
3332 }
3333 return false;
3334}
3335
Chris Lattner4c2642c2008-11-18 01:22:49 +00003336/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3337/// emit an error and return true. If so, return false.
3338static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003339 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3340 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3341 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003342 if (IsLV == Expr::MLV_Valid)
3343 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003344
Chris Lattner4c2642c2008-11-18 01:22:49 +00003345 unsigned Diag = 0;
3346 bool NeedType = false;
3347 switch (IsLV) { // C99 6.5.16p2
3348 default: assert(0 && "Unknown result from isModifiableLvalue!");
3349 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003350 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003351 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3352 NeedType = true;
3353 break;
Mike Stump9afab102009-02-19 03:04:26 +00003354 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003355 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3356 NeedType = true;
3357 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003358 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003359 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3360 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003361 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003362 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3363 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003364 case Expr::MLV_IncompleteType:
3365 case Expr::MLV_IncompleteVoidType:
Mike Stump9afab102009-02-19 03:04:26 +00003366 return S.DiagnoseIncompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003367 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3368 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003369 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003370 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3371 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003372 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003373 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3374 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003375 case Expr::MLV_ReadonlyProperty:
3376 Diag = diag::error_readonly_property_assignment;
3377 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003378 case Expr::MLV_NoSetterProperty:
3379 Diag = diag::error_nosetter_property_assignment;
3380 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003381 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003382
Chris Lattner4c2642c2008-11-18 01:22:49 +00003383 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003384 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003385 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003386 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003387 return true;
3388}
3389
3390
3391
3392// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003393QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3394 SourceLocation Loc,
3395 QualType CompoundType) {
3396 // Verify that LHS is a modifiable lvalue, and emit error if not.
3397 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003398 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003399
3400 QualType LHSType = LHS->getType();
3401 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003402
Chris Lattner005ed752008-01-04 18:04:52 +00003403 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003404 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003405 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003406 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003407 // Special case of NSObject attributes on c-style pointer types.
3408 if (ConvTy == IncompatiblePointer &&
3409 ((Context.isObjCNSObjectType(LHSType) &&
3410 Context.isObjCObjectPointerType(RHSType)) ||
3411 (Context.isObjCNSObjectType(RHSType) &&
3412 Context.isObjCObjectPointerType(LHSType))))
3413 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003414
Chris Lattner34c85082008-08-21 18:04:13 +00003415 // If the RHS is a unary plus or minus, check to see if they = and + are
3416 // right next to each other. If so, the user may have typo'd "x =+ 4"
3417 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003418 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003419 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3420 RHSCheck = ICE->getSubExpr();
3421 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3422 if ((UO->getOpcode() == UnaryOperator::Plus ||
3423 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003424 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003425 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003426 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003427 Diag(Loc, diag::warn_not_compound_assign)
3428 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3429 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003430 }
3431 } else {
3432 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003433 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003434 }
Chris Lattner005ed752008-01-04 18:04:52 +00003435
Chris Lattner1eafdea2008-11-18 01:30:42 +00003436 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3437 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003438 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003439
Chris Lattner4b009652007-07-25 00:24:17 +00003440 // C99 6.5.16p3: The type of an assignment expression is the type of the
3441 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003442 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003443 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3444 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003445 // C++ 5.17p1: the type of the assignment expression is that of its left
3446 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003447 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003448}
3449
Chris Lattner1eafdea2008-11-18 01:30:42 +00003450// C99 6.5.17
3451QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3452 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003453
Chris Lattner03c430f2008-07-25 20:54:07 +00003454 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003455 DefaultFunctionArrayConversion(RHS);
3456 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003457}
3458
3459/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3460/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003461QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3462 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003463 if (Op->isTypeDependent())
3464 return Context.DependentTy;
3465
Chris Lattnere65182c2008-11-21 07:05:48 +00003466 QualType ResType = Op->getType();
3467 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003468
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003469 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3470 // Decrement of bool is not allowed.
3471 if (!isInc) {
3472 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3473 return QualType();
3474 }
3475 // Increment of bool sets it to true, but is deprecated.
3476 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3477 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003478 // OK!
3479 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3480 // C99 6.5.2.4p2, 6.5.6p2
3481 if (PT->getPointeeType()->isObjectType()) {
3482 // Pointer to object is ok!
3483 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003484 if (getLangOptions().CPlusPlus) {
3485 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3486 << Op->getSourceRange();
3487 return QualType();
3488 }
3489
3490 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003491 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003492 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003493 if (getLangOptions().CPlusPlus) {
3494 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3495 << Op->getType() << Op->getSourceRange();
3496 return QualType();
3497 }
3498
3499 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003500 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003501 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003502 } else {
Mike Stump9afab102009-02-19 03:04:26 +00003503 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003504 diag::err_typecheck_arithmetic_incomplete_type,
3505 Op->getSourceRange(), SourceRange(),
3506 ResType);
3507 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003508 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003509 } else if (ResType->isComplexType()) {
3510 // C99 does not support ++/-- on complex types, we allow as an extension.
3511 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003512 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003513 } else {
3514 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003515 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003516 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003517 }
Mike Stump9afab102009-02-19 03:04:26 +00003518 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003519 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003520 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003521 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003522 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003523}
3524
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003525/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003526/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003527/// where the declaration is needed for type checking. We only need to
3528/// handle cases when the expression references a function designator
3529/// or is an lvalue. Here are some examples:
3530/// - &(x) => x
3531/// - &*****f => f for f a function designator.
3532/// - &s.xx => s
3533/// - &s.zz[1].yy -> s, if zz is an array
3534/// - *(x + 1) -> x, if x is an array
3535/// - &"123"[2] -> 0
3536/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003537static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003538 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003539 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003540 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003541 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003542 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003543 // Fields cannot be declared with a 'register' storage class.
3544 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003545 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003546 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003547 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003548 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003549 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003550
Douglas Gregord2baafd2008-10-21 16:13:35 +00003551 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003552 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003553 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003554 return 0;
3555 else
3556 return VD;
3557 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003558 case Stmt::UnaryOperatorClass: {
3559 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003560
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003561 switch(UO->getOpcode()) {
3562 case UnaryOperator::Deref: {
3563 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003564 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3565 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3566 if (!VD || VD->getType()->isPointerType())
3567 return 0;
3568 return VD;
3569 }
3570 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003571 }
3572 case UnaryOperator::Real:
3573 case UnaryOperator::Imag:
3574 case UnaryOperator::Extension:
3575 return getPrimaryDecl(UO->getSubExpr());
3576 default:
3577 return 0;
3578 }
3579 }
3580 case Stmt::BinaryOperatorClass: {
3581 BinaryOperator *BO = cast<BinaryOperator>(E);
3582
3583 // Handle cases involving pointer arithmetic. The result of an
3584 // Assign or AddAssign is not an lvalue so they can be ignored.
3585
3586 // (x + n) or (n + x) => x
3587 if (BO->getOpcode() == BinaryOperator::Add) {
3588 if (BO->getLHS()->getType()->isPointerType()) {
3589 return getPrimaryDecl(BO->getLHS());
3590 } else if (BO->getRHS()->getType()->isPointerType()) {
3591 return getPrimaryDecl(BO->getRHS());
3592 }
3593 }
3594
3595 return 0;
3596 }
Chris Lattner4b009652007-07-25 00:24:17 +00003597 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003598 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003599 case Stmt::ImplicitCastExprClass:
3600 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003601 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003602 default:
3603 return 0;
3604 }
3605}
3606
3607/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003608/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003609/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003610/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003611/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003612/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003613/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003614QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003615 if (op->isTypeDependent())
3616 return Context.DependentTy;
3617
Steve Naroff9c6c3592008-01-13 17:10:08 +00003618 if (getLangOptions().C99) {
3619 // Implement C99-only parts of addressof rules.
3620 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3621 if (uOp->getOpcode() == UnaryOperator::Deref)
3622 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3623 // (assuming the deref expression is valid).
3624 return uOp->getSubExpr()->getType();
3625 }
3626 // Technically, there should be a check for array subscript
3627 // expressions here, but the result of one is always an lvalue anyway.
3628 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003629 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003630 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003631
Chris Lattner4b009652007-07-25 00:24:17 +00003632 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003633 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3634 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003635 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3636 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003637 return QualType();
3638 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003639 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003640 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3641 if (Field->isBitField()) {
3642 Diag(OpLoc, diag::err_typecheck_address_of)
3643 << "bit-field" << op->getSourceRange();
3644 return QualType();
3645 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003646 }
3647 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003648 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3649 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003650 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003651 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003652 return QualType();
3653 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003654 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003655 // with the register storage-class specifier.
3656 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3657 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003658 Diag(OpLoc, diag::err_typecheck_address_of)
3659 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003660 return QualType();
3661 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003662 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003663 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003664 } else if (isa<FieldDecl>(dcl)) {
3665 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003666 // Could be a pointer to member, though, if there is an explicit
3667 // scope qualifier for the class.
3668 if (isa<QualifiedDeclRefExpr>(op)) {
3669 DeclContext *Ctx = dcl->getDeclContext();
3670 if (Ctx && Ctx->isRecord())
3671 return Context.getMemberPointerType(op->getType(),
3672 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3673 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003674 } else if (isa<FunctionDecl>(dcl)) {
3675 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003676 // As above.
3677 if (isa<QualifiedDeclRefExpr>(op)) {
3678 DeclContext *Ctx = dcl->getDeclContext();
3679 if (Ctx && Ctx->isRecord())
3680 return Context.getMemberPointerType(op->getType(),
3681 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3682 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003683 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003684 else
Chris Lattner4b009652007-07-25 00:24:17 +00003685 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003686 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003687
Chris Lattner4b009652007-07-25 00:24:17 +00003688 // If the operand has type "type", the result has type "pointer to type".
3689 return Context.getPointerType(op->getType());
3690}
3691
Chris Lattnerda5c0872008-11-23 09:13:29 +00003692QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003693 if (Op->isTypeDependent())
3694 return Context.DependentTy;
3695
Chris Lattnerda5c0872008-11-23 09:13:29 +00003696 UsualUnaryConversions(Op);
3697 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003698
Chris Lattnerda5c0872008-11-23 09:13:29 +00003699 // Note that per both C89 and C99, this is always legal, even if ptype is an
3700 // incomplete type or void. It would be possible to warn about dereferencing
3701 // a void pointer, but it's completely well-defined, and such a warning is
3702 // unlikely to catch any mistakes.
3703 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003704 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003705
Chris Lattner77d52da2008-11-20 06:06:08 +00003706 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003707 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003708 return QualType();
3709}
3710
3711static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3712 tok::TokenKind Kind) {
3713 BinaryOperator::Opcode Opc;
3714 switch (Kind) {
3715 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003716 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3717 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003718 case tok::star: Opc = BinaryOperator::Mul; break;
3719 case tok::slash: Opc = BinaryOperator::Div; break;
3720 case tok::percent: Opc = BinaryOperator::Rem; break;
3721 case tok::plus: Opc = BinaryOperator::Add; break;
3722 case tok::minus: Opc = BinaryOperator::Sub; break;
3723 case tok::lessless: Opc = BinaryOperator::Shl; break;
3724 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3725 case tok::lessequal: Opc = BinaryOperator::LE; break;
3726 case tok::less: Opc = BinaryOperator::LT; break;
3727 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3728 case tok::greater: Opc = BinaryOperator::GT; break;
3729 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3730 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3731 case tok::amp: Opc = BinaryOperator::And; break;
3732 case tok::caret: Opc = BinaryOperator::Xor; break;
3733 case tok::pipe: Opc = BinaryOperator::Or; break;
3734 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3735 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3736 case tok::equal: Opc = BinaryOperator::Assign; break;
3737 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3738 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3739 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3740 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3741 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3742 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3743 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3744 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3745 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3746 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3747 case tok::comma: Opc = BinaryOperator::Comma; break;
3748 }
3749 return Opc;
3750}
3751
3752static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3753 tok::TokenKind Kind) {
3754 UnaryOperator::Opcode Opc;
3755 switch (Kind) {
3756 default: assert(0 && "Unknown unary op!");
3757 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3758 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3759 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3760 case tok::star: Opc = UnaryOperator::Deref; break;
3761 case tok::plus: Opc = UnaryOperator::Plus; break;
3762 case tok::minus: Opc = UnaryOperator::Minus; break;
3763 case tok::tilde: Opc = UnaryOperator::Not; break;
3764 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003765 case tok::kw___real: Opc = UnaryOperator::Real; break;
3766 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3767 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3768 }
3769 return Opc;
3770}
3771
Douglas Gregord7f915e2008-11-06 23:29:22 +00003772/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3773/// operator @p Opc at location @c TokLoc. This routine only supports
3774/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003775Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3776 unsigned Op,
3777 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003778 QualType ResultTy; // Result type of the binary operator.
3779 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3780 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3781
3782 switch (Opc) {
3783 default:
3784 assert(0 && "Unknown binary expr!");
3785 case BinaryOperator::Assign:
3786 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3787 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003788 case BinaryOperator::PtrMemD:
3789 case BinaryOperator::PtrMemI:
3790 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3791 Opc == BinaryOperator::PtrMemI);
3792 break;
3793 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003794 case BinaryOperator::Div:
3795 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3796 break;
3797 case BinaryOperator::Rem:
3798 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3799 break;
3800 case BinaryOperator::Add:
3801 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3802 break;
3803 case BinaryOperator::Sub:
3804 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3805 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003806 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003807 case BinaryOperator::Shr:
3808 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3809 break;
3810 case BinaryOperator::LE:
3811 case BinaryOperator::LT:
3812 case BinaryOperator::GE:
3813 case BinaryOperator::GT:
3814 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3815 break;
3816 case BinaryOperator::EQ:
3817 case BinaryOperator::NE:
3818 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3819 break;
3820 case BinaryOperator::And:
3821 case BinaryOperator::Xor:
3822 case BinaryOperator::Or:
3823 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3824 break;
3825 case BinaryOperator::LAnd:
3826 case BinaryOperator::LOr:
3827 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3828 break;
3829 case BinaryOperator::MulAssign:
3830 case BinaryOperator::DivAssign:
3831 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3832 if (!CompTy.isNull())
3833 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3834 break;
3835 case BinaryOperator::RemAssign:
3836 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3837 if (!CompTy.isNull())
3838 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3839 break;
3840 case BinaryOperator::AddAssign:
3841 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3842 if (!CompTy.isNull())
3843 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3844 break;
3845 case BinaryOperator::SubAssign:
3846 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3847 if (!CompTy.isNull())
3848 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3849 break;
3850 case BinaryOperator::ShlAssign:
3851 case BinaryOperator::ShrAssign:
3852 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3853 if (!CompTy.isNull())
3854 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3855 break;
3856 case BinaryOperator::AndAssign:
3857 case BinaryOperator::XorAssign:
3858 case BinaryOperator::OrAssign:
3859 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3860 if (!CompTy.isNull())
3861 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3862 break;
3863 case BinaryOperator::Comma:
3864 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3865 break;
3866 }
3867 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003868 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003869 if (CompTy.isNull())
3870 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3871 else
3872 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00003873 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003874}
3875
Chris Lattner4b009652007-07-25 00:24:17 +00003876// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003877Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3878 tok::TokenKind Kind,
3879 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003880 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003881 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003882
Steve Naroff87d58b42007-09-16 03:34:24 +00003883 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3884 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003885
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003886 // If either expression is type-dependent, just build the AST.
3887 // FIXME: We'll need to perform some caching of the result of name
3888 // lookup for operator+.
3889 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003890 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3891 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003892 Context.DependentTy,
3893 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003894 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003895 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3896 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003897 }
3898
Sebastian Redl95216a62009-02-07 00:15:38 +00003899 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003900 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3901 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003902 // If this is one of the assignment operators, we only perform
3903 // overload resolution if the left-hand side is a class or
3904 // enumeration type (C++ [expr.ass]p3).
3905 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3906 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3907 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3908 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003909
Douglas Gregord7f915e2008-11-06 23:29:22 +00003910 // Determine which overloaded operator we're dealing with.
3911 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003912 // Overloading .* is not possible.
3913 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003914 OO_Star, OO_Slash, OO_Percent,
3915 OO_Plus, OO_Minus,
3916 OO_LessLess, OO_GreaterGreater,
3917 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3918 OO_EqualEqual, OO_ExclaimEqual,
3919 OO_Amp,
3920 OO_Caret,
3921 OO_Pipe,
3922 OO_AmpAmp,
3923 OO_PipePipe,
3924 OO_Equal, OO_StarEqual,
3925 OO_SlashEqual, OO_PercentEqual,
3926 OO_PlusEqual, OO_MinusEqual,
3927 OO_LessLessEqual, OO_GreaterGreaterEqual,
3928 OO_AmpEqual, OO_CaretEqual,
3929 OO_PipeEqual,
3930 OO_Comma
3931 };
3932 OverloadedOperatorKind OverOp = OverOps[Opc];
3933
Mike Stump9afab102009-02-19 03:04:26 +00003934 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor5ed15042008-11-18 23:14:02 +00003935 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003936 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003937 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003938 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3939 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003940
3941 // Perform overload resolution.
3942 OverloadCandidateSet::iterator Best;
3943 switch (BestViableFunction(CandidateSet, Best)) {
3944 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003945 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003946 FunctionDecl *FnDecl = Best->Function;
3947
Douglas Gregor70d26122008-11-12 17:17:38 +00003948 if (FnDecl) {
3949 // We matched an overloaded operator. Build a call to that
3950 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003951
Douglas Gregor70d26122008-11-12 17:17:38 +00003952 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003953 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3954 if (PerformObjectArgumentInitialization(lhs, Method) ||
3955 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3956 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003957 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003958 } else {
3959 // Convert the arguments.
3960 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3961 "passing") ||
3962 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3963 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003964 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003965 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003966
Douglas Gregor70d26122008-11-12 17:17:38 +00003967 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003968 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003969 = FnDecl->getType()->getAsFunctionType()->getResultType();
3970 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003971
Douglas Gregor70d26122008-11-12 17:17:38 +00003972 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003973 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3974 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003975 UsualUnaryConversions(FnExpr);
3976
Mike Stump9afab102009-02-19 03:04:26 +00003977 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003978 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003979 } else {
3980 // We matched a built-in operator. Convert the arguments, then
3981 // break out so that we will build the appropriate built-in
3982 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003983 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3984 Best->Conversions[0], "passing") ||
3985 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3986 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003987 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003988
3989 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003990 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003991 }
3992
3993 case OR_No_Viable_Function:
3994 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003995 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003996 break;
3997
3998 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003999 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
4000 << BinaryOperator::getOpcodeStr(Opc)
4001 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00004002 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004003 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004004
4005 case OR_Deleted:
4006 Diag(TokLoc, diag::err_ovl_deleted_oper)
4007 << Best->Function->isDeleted()
4008 << BinaryOperator::getOpcodeStr(Opc)
4009 << lhs->getSourceRange() << rhs->getSourceRange();
4010 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4011 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00004012 }
4013
Douglas Gregor70d26122008-11-12 17:17:38 +00004014 // Either we found no viable overloaded operator or we matched a
4015 // built-in operator. In either case, fall through to trying to
4016 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004017 }
4018
Douglas Gregord7f915e2008-11-06 23:29:22 +00004019 // Build a built-in binary operation.
4020 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004021}
4022
4023// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00004024Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4025 tok::TokenKind Op, ExprArg input) {
4026 // FIXME: Input is modified later, but smart pointer not reassigned.
4027 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004028 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004029
4030 if (getLangOptions().CPlusPlus &&
Mike Stump9afab102009-02-19 03:04:26 +00004031 (Input->getType()->isRecordType()
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004032 || Input->getType()->isEnumeralType())) {
4033 // Determine which overloaded operator we're dealing with.
4034 static const OverloadedOperatorKind OverOps[] = {
4035 OO_None, OO_None,
4036 OO_PlusPlus, OO_MinusMinus,
4037 OO_Amp, OO_Star,
4038 OO_Plus, OO_Minus,
4039 OO_Tilde, OO_Exclaim,
4040 OO_None, OO_None,
Mike Stump9afab102009-02-19 03:04:26 +00004041 OO_None,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004042 OO_None
4043 };
4044 OverloadedOperatorKind OverOp = OverOps[Opc];
4045
Mike Stump9afab102009-02-19 03:04:26 +00004046 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004047 // to the candidate set.
4048 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00004049 if (OverOp != OO_None &&
4050 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4051 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004052
4053 // Perform overload resolution.
4054 OverloadCandidateSet::iterator Best;
4055 switch (BestViableFunction(CandidateSet, Best)) {
4056 case OR_Success: {
4057 // We found a built-in operator or an overloaded operator.
4058 FunctionDecl *FnDecl = Best->Function;
4059
4060 if (FnDecl) {
4061 // We matched an overloaded operator. Build a call to that
4062 // operator.
4063
4064 // Convert the arguments.
4065 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4066 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004067 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004068 } else {
4069 // Convert the arguments.
Mike Stump9afab102009-02-19 03:04:26 +00004070 if (PerformCopyInitialization(Input,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004071 FnDecl->getParamDecl(0)->getType(),
4072 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004073 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004074 }
4075
4076 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004077 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004078 = FnDecl->getType()->getAsFunctionType()->getResultType();
4079 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004080
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004081 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00004082 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004083 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004084 UsualUnaryConversions(FnExpr);
4085
Sebastian Redl8b769972009-01-19 00:08:26 +00004086 input.release();
Mike Stump9afab102009-02-19 03:04:26 +00004087 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4088 1, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004089 } else {
4090 // We matched a built-in operator. Convert the arguments, then
4091 // break out so that we will build the appropriate built-in
4092 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004093 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4094 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004095 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004096
4097 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004098 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004099 }
4100
4101 case OR_No_Viable_Function:
4102 // No viable function; fall through to handling this as a
4103 // built-in operator, which will produce an error message for us.
4104 break;
4105
4106 case OR_Ambiguous:
4107 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4108 << UnaryOperator::getOpcodeStr(Opc)
4109 << Input->getSourceRange();
4110 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004111 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004112
4113 case OR_Deleted:
4114 Diag(OpLoc, diag::err_ovl_deleted_oper)
4115 << Best->Function->isDeleted()
4116 << UnaryOperator::getOpcodeStr(Opc)
4117 << Input->getSourceRange();
4118 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4119 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004120 }
4121
4122 // Either we found no viable overloaded operator or we matched a
4123 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004124 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004125 }
4126
Chris Lattner4b009652007-07-25 00:24:17 +00004127 QualType resultType;
4128 switch (Opc) {
4129 default:
4130 assert(0 && "Unimplemented unary expr!");
4131 case UnaryOperator::PreInc:
4132 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004133 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4134 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004135 break;
Mike Stump9afab102009-02-19 03:04:26 +00004136 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004137 resultType = CheckAddressOfOperand(Input, OpLoc);
4138 break;
Mike Stump9afab102009-02-19 03:04:26 +00004139 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004140 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004141 resultType = CheckIndirectionOperand(Input, OpLoc);
4142 break;
4143 case UnaryOperator::Plus:
4144 case UnaryOperator::Minus:
4145 UsualUnaryConversions(Input);
4146 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004147 if (resultType->isDependentType())
4148 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004149 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4150 break;
4151 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4152 resultType->isEnumeralType())
4153 break;
4154 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4155 Opc == UnaryOperator::Plus &&
4156 resultType->isPointerType())
4157 break;
4158
Sebastian Redl8b769972009-01-19 00:08:26 +00004159 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4160 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004161 case UnaryOperator::Not: // bitwise complement
4162 UsualUnaryConversions(Input);
4163 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004164 if (resultType->isDependentType())
4165 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004166 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4167 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4168 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004169 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004170 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004171 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004172 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4173 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004174 break;
4175 case UnaryOperator::LNot: // logical negation
4176 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4177 DefaultFunctionArrayConversion(Input);
4178 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004179 if (resultType->isDependentType())
4180 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004181 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004182 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4183 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004184 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004185 // In C++, it's bool. C++ 5.3.1p8
4186 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004187 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004188 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004189 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004190 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004191 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004192 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004193 resultType = Input->getType();
4194 break;
4195 }
4196 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004197 return ExprError();
4198 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004199 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004200}
4201
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004202/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stump9afab102009-02-19 03:04:26 +00004203Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004204 SourceLocation LabLoc,
4205 IdentifierInfo *LabelII) {
4206 // Look up the record for this label identifier.
Steve Naroff313c4162009-02-28 16:48:43 +00004207 llvm::DenseMap<IdentifierInfo*, Action::StmtTy*>::iterator I =
4208 ActiveScope->LabelMap.find(LabelII);
Mike Stump9afab102009-02-19 03:04:26 +00004209
Steve Naroff313c4162009-02-28 16:48:43 +00004210 LabelStmt *LabelDecl;
4211
Daniel Dunbar879788d2008-08-04 16:51:22 +00004212 // If we haven't seen this label yet, create a forward reference. It
4213 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff313c4162009-02-28 16:48:43 +00004214 if (I == ActiveScope->LabelMap.end()) {
Steve Naroff774e4152009-01-21 00:14:39 +00004215 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004216
Steve Naroff313c4162009-02-28 16:48:43 +00004217 ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl));
4218 } else
4219 LabelDecl = static_cast<LabelStmt *>(I->second);
4220
Chris Lattner4b009652007-07-25 00:24:17 +00004221 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004222 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4223 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004224}
4225
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004226Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004227 SourceLocation RPLoc) { // "({..})"
4228 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4229 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4230 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4231
Eli Friedmanbc941e12009-01-24 23:09:00 +00004232 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4233 if (isFileScope) {
4234 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4235 }
4236
Chris Lattner4b009652007-07-25 00:24:17 +00004237 // FIXME: there are a variety of strange constraints to enforce here, for
4238 // example, it is not possible to goto into a stmt expression apparently.
4239 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004240
Chris Lattner4b009652007-07-25 00:24:17 +00004241 // FIXME: the last statement in the compount stmt has its value used. We
4242 // should not warn about it being unused.
4243
4244 // If there are sub stmts in the compound stmt, take the type of the last one
4245 // as the type of the stmtexpr.
4246 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004247
Chris Lattner200964f2008-07-26 19:51:01 +00004248 if (!Compound->body_empty()) {
4249 Stmt *LastStmt = Compound->body_back();
4250 // If LastStmt is a label, skip down through into the body.
4251 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4252 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004253
Chris Lattner200964f2008-07-26 19:51:01 +00004254 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004255 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004256 }
Mike Stump9afab102009-02-19 03:04:26 +00004257
Steve Naroff774e4152009-01-21 00:14:39 +00004258 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004259}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004260
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004261Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4262 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004263 SourceLocation TypeLoc,
4264 TypeTy *argty,
4265 OffsetOfComponent *CompPtr,
4266 unsigned NumComponents,
4267 SourceLocation RPLoc) {
4268 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4269 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004270
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004271 bool Dependent = ArgTy->isDependentType();
4272
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004273 // We must have at least one component that refers to the type, and the first
4274 // one is known to be a field designator. Verify that the ArgTy represents
4275 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004276 if (!Dependent && !ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004277 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stump9afab102009-02-19 03:04:26 +00004278
Eli Friedman342d9432009-02-27 06:44:11 +00004279 // Otherwise, create a null pointer as the base, and iteratively process
4280 // the offsetof designators.
4281 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4282 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
4283 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
4284 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004285
Chris Lattnerb37522e2007-08-31 21:49:13 +00004286 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4287 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004288 // FIXME: This diagnostic isn't actually visible because the location is in
4289 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004290 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004291 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4292 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004293
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004294 if (!Dependent) {
4295 // FIXME: Dependent case loses a lot of information here. And probably
4296 // leaks like a sieve.
4297 for (unsigned i = 0; i != NumComponents; ++i) {
4298 const OffsetOfComponent &OC = CompPtr[i];
4299 if (OC.isBrackets) {
4300 // Offset of an array sub-field. TODO: Should we allow vector elements?
4301 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4302 if (!AT) {
4303 Res->Destroy(Context);
4304 return Diag(OC.LocEnd, diag::err_offsetof_array_type)
4305 << Res->getType();
4306 }
4307
4308 // FIXME: C++: Verify that operator[] isn't overloaded.
4309
Eli Friedman342d9432009-02-27 06:44:11 +00004310 // Promote the array so it looks more like a normal array subscript
4311 // expression.
4312 DefaultFunctionArrayConversion(Res);
4313
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004314 // C99 6.5.2.1p1
4315 Expr *Idx = static_cast<Expr*>(OC.U.E);
4316 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4317 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4318 << Idx->getSourceRange();
4319
4320 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4321 OC.LocEnd);
4322 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004323 }
Mike Stump9afab102009-02-19 03:04:26 +00004324
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004325 const RecordType *RC = Res->getType()->getAsRecordType();
4326 if (!RC) {
4327 Res->Destroy(Context);
4328 return Diag(OC.LocEnd, diag::err_offsetof_record_type)
4329 << Res->getType();
4330 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004331
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004332 // Get the decl corresponding to this.
4333 RecordDecl *RD = RC->getDecl();
4334 FieldDecl *MemberDecl
4335 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4336 LookupMemberName)
4337 .getAsDecl());
4338 if (!MemberDecl)
4339 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4340 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004341
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004342 // FIXME: C++: Verify that MemberDecl isn't a static field.
4343 // FIXME: Verify that MemberDecl isn't a bitfield.
4344 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4345 // matter here.
4346 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004347 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004348 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004349 }
Mike Stump9afab102009-02-19 03:04:26 +00004350
4351 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff774e4152009-01-21 00:14:39 +00004352 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004353}
4354
4355
Mike Stump9afab102009-02-19 03:04:26 +00004356Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004357 TypeTy *arg1, TypeTy *arg2,
4358 SourceLocation RPLoc) {
4359 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4360 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004361
Steve Naroff63bad2d2007-08-01 22:05:33 +00004362 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004363
4364 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff774e4152009-01-21 00:14:39 +00004365 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004366}
4367
Mike Stump9afab102009-02-19 03:04:26 +00004368Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004369 ExprTy *expr1, ExprTy *expr2,
4370 SourceLocation RPLoc) {
4371 Expr *CondExpr = static_cast<Expr*>(cond);
4372 Expr *LHSExpr = static_cast<Expr*>(expr1);
4373 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stump9afab102009-02-19 03:04:26 +00004374
Steve Naroff93c53012007-08-03 21:21:27 +00004375 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4376
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004377 QualType resType;
4378 if (CondExpr->isValueDependent()) {
4379 resType = Context.DependentTy;
4380 } else {
4381 // The conditional expression is required to be a constant expression.
4382 llvm::APSInt condEval(32);
4383 SourceLocation ExpLoc;
4384 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4385 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4386 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004387
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004388 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4389 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4390 }
4391
Mike Stump9afab102009-02-19 03:04:26 +00004392 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00004393 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004394}
4395
Steve Naroff52a81c02008-09-03 18:15:37 +00004396//===----------------------------------------------------------------------===//
4397// Clang Extensions.
4398//===----------------------------------------------------------------------===//
4399
4400/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004401void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004402 // Analyze block parameters.
4403 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004404
Steve Naroff52a81c02008-09-03 18:15:37 +00004405 // Add BSI to CurBlock.
4406 BSI->PrevBlockInfo = CurBlock;
4407 CurBlock = BSI;
Steve Naroff313c4162009-02-28 16:48:43 +00004408 ActiveScope = BlockScope;
Mike Stump9afab102009-02-19 03:04:26 +00004409
Steve Naroff52a81c02008-09-03 18:15:37 +00004410 BSI->ReturnType = 0;
4411 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004412 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004413
Steve Naroff52059382008-10-10 01:28:17 +00004414 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004415 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004416}
4417
Mike Stumpc1fddff2009-02-04 22:31:32 +00004418void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4419 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4420
4421 if (ParamInfo.getNumTypeObjects() == 0
4422 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4423 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4424
4425 // The type is entirely optional as well, if none, use DependentTy.
4426 if (T.isNull())
4427 T = Context.DependentTy;
4428
4429 // The parameter list is optional, if there was none, assume ().
4430 if (!T->isFunctionType())
4431 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4432
4433 CurBlock->hasPrototype = true;
4434 CurBlock->isVariadic = false;
4435 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4436 .getTypePtr();
4437
4438 if (!RetTy->isDependentType())
4439 CurBlock->ReturnType = RetTy;
4440 return;
4441 }
4442
Steve Naroff52a81c02008-09-03 18:15:37 +00004443 // Analyze arguments to block.
4444 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4445 "Not a function declarator!");
4446 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004447
Steve Naroff52059382008-10-10 01:28:17 +00004448 CurBlock->hasPrototype = FTI.hasPrototype;
4449 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004450
Steve Naroff52a81c02008-09-03 18:15:37 +00004451 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4452 // no arguments, not a function that takes a single void argument.
4453 if (FTI.hasPrototype &&
4454 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4455 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4456 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4457 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004458 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004459 } else if (FTI.hasPrototype) {
4460 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004461 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4462 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004463 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4464
4465 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4466 .getTypePtr();
4467
4468 if (!RetTy->isDependentType())
4469 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004470 }
Steve Naroff52059382008-10-10 01:28:17 +00004471 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004472
Steve Naroff52059382008-10-10 01:28:17 +00004473 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4474 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4475 // If this has an identifier, add it to the scope stack.
4476 if ((*AI)->getIdentifier())
4477 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004478}
4479
4480/// ActOnBlockError - If there is an error parsing a block, this callback
4481/// is invoked to pop the information about the block from the action impl.
4482void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4483 // Ensure that CurBlock is deleted.
4484 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004485
Steve Naroff52a81c02008-09-03 18:15:37 +00004486 // Pop off CurBlock, handle nested blocks.
4487 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004488
Steve Naroff52a81c02008-09-03 18:15:37 +00004489 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stump9afab102009-02-19 03:04:26 +00004490
Steve Naroff52a81c02008-09-03 18:15:37 +00004491}
4492
4493/// ActOnBlockStmtExpr - This is called when the body of a block statement
4494/// literal was successfully completed. ^(int x){...}
4495Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4496 Scope *CurScope) {
4497 // Ensure that CurBlock is deleted.
4498 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004499 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004500
Steve Naroff52059382008-10-10 01:28:17 +00004501 PopDeclContext();
4502
Steve Naroff5cd38432009-02-28 21:01:15 +00004503 // Before poping CurBlock, set ActiveScope to this scopes parent.
4504 ActiveScope = CurBlock->TheScope->getParent();
4505
Steve Naroff52a81c02008-09-03 18:15:37 +00004506 // Pop off CurBlock, handle nested blocks.
4507 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004508
Steve Naroff52a81c02008-09-03 18:15:37 +00004509 QualType RetTy = Context.VoidTy;
4510 if (BSI->ReturnType)
4511 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004512
Steve Naroff52a81c02008-09-03 18:15:37 +00004513 llvm::SmallVector<QualType, 8> ArgTypes;
4514 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4515 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004516
Steve Naroff52a81c02008-09-03 18:15:37 +00004517 QualType BlockTy;
4518 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004519 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004520 else
4521 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004522 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004523
Steve Naroff52a81c02008-09-03 18:15:37 +00004524 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004525
Steve Naroff95029d92008-10-08 18:44:00 +00004526 BSI->TheDecl->setBody(Body.take());
Mike Stumpae93d652009-02-19 22:01:56 +00004527 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff52a81c02008-09-03 18:15:37 +00004528}
4529
Anders Carlsson36760332007-10-15 20:28:48 +00004530Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4531 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004532 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004533 Expr *E = static_cast<Expr*>(expr);
4534 QualType T = QualType::getFromOpaquePtr(type);
4535
4536 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004537
4538 // Get the va_list type
4539 QualType VaListType = Context.getBuiltinVaListType();
4540 // Deal with implicit array decay; for example, on x86-64,
4541 // va_list is an array, but it's supposed to decay to
4542 // a pointer for va_arg.
4543 if (VaListType->isArrayType())
4544 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004545 // Make sure the input expression also decays appropriately.
4546 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004547
4548 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004549 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004550 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004551 << E->getType() << E->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004552
Anders Carlsson36760332007-10-15 20:28:48 +00004553 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004554
Steve Naroff774e4152009-01-21 00:14:39 +00004555 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004556}
4557
Douglas Gregorad4b3792008-11-29 04:51:27 +00004558Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4559 // The type of __null will be int or long, depending on the size of
4560 // pointers on the target.
4561 QualType Ty;
4562 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4563 Ty = Context.IntTy;
4564 else
4565 Ty = Context.LongTy;
4566
Steve Naroff774e4152009-01-21 00:14:39 +00004567 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004568}
4569
Chris Lattner005ed752008-01-04 18:04:52 +00004570bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4571 SourceLocation Loc,
4572 QualType DstType, QualType SrcType,
4573 Expr *SrcExpr, const char *Flavor) {
4574 // Decode the result (notice that AST's are still created for extensions).
4575 bool isInvalid = false;
4576 unsigned DiagKind;
4577 switch (ConvTy) {
4578 default: assert(0 && "Unknown conversion type");
4579 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004580 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004581 DiagKind = diag::ext_typecheck_convert_pointer_int;
4582 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004583 case IntToPointer:
4584 DiagKind = diag::ext_typecheck_convert_int_pointer;
4585 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004586 case IncompatiblePointer:
4587 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4588 break;
4589 case FunctionVoidPointer:
4590 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4591 break;
4592 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004593 // If the qualifiers lost were because we were applying the
4594 // (deprecated) C++ conversion from a string literal to a char*
4595 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4596 // Ideally, this check would be performed in
4597 // CheckPointerTypesForAssignment. However, that would require a
4598 // bit of refactoring (so that the second argument is an
4599 // expression, rather than a type), which should be done as part
4600 // of a larger effort to fix CheckPointerTypesForAssignment for
4601 // C++ semantics.
4602 if (getLangOptions().CPlusPlus &&
4603 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4604 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004605 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4606 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004607 case IntToBlockPointer:
4608 DiagKind = diag::err_int_to_block_pointer;
4609 break;
4610 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004611 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004612 break;
Steve Naroff19608432008-10-14 22:18:38 +00004613 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004614 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004615 // it can give a more specific diagnostic.
4616 DiagKind = diag::warn_incompatible_qualified_id;
4617 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004618 case IncompatibleVectors:
4619 DiagKind = diag::warn_incompatible_vectors;
4620 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004621 case Incompatible:
4622 DiagKind = diag::err_typecheck_convert_incompatible;
4623 isInvalid = true;
4624 break;
4625 }
Mike Stump9afab102009-02-19 03:04:26 +00004626
Chris Lattner271d4c22008-11-24 05:29:24 +00004627 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4628 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004629 return isInvalid;
4630}
Anders Carlssond5201b92008-11-30 19:50:32 +00004631
4632bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4633{
4634 Expr::EvalResult EvalResult;
4635
Mike Stump9afab102009-02-19 03:04:26 +00004636 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004637 EvalResult.HasSideEffects) {
4638 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4639
4640 if (EvalResult.Diag) {
4641 // We only show the note if it's not the usual "invalid subexpression"
4642 // or if it's actually in a subexpression.
4643 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4644 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4645 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4646 }
Mike Stump9afab102009-02-19 03:04:26 +00004647
Anders Carlssond5201b92008-11-30 19:50:32 +00004648 return true;
4649 }
4650
4651 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004652 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004653 E->getSourceRange();
4654
4655 // Print the reason it's not a constant.
4656 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4657 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4658 }
Mike Stump9afab102009-02-19 03:04:26 +00004659
Anders Carlssond5201b92008-11-30 19:50:32 +00004660 if (Result)
4661 *Result = EvalResult.Val.getInt();
4662 return false;
4663}