blob: 1f8cb80cd3dcdffc3de19d70f85b574759ed3628 [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
Chris Lattner299b8842008-07-25 21:10:04 +0000113//===----------------------------------------------------------------------===//
114// Standard Promotions and Conversions
115//===----------------------------------------------------------------------===//
116
Chris Lattner299b8842008-07-25 21:10:04 +0000117/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
118void Sema::DefaultFunctionArrayConversion(Expr *&E) {
119 QualType Ty = E->getType();
120 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
121
Chris Lattner299b8842008-07-25 21:10:04 +0000122 if (Ty->isFunctionType())
123 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000124 else if (Ty->isArrayType()) {
125 // In C90 mode, arrays only promote to pointers if the array expression is
126 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
127 // type 'array of type' is converted to an expression that has type 'pointer
128 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
129 // that has type 'array of type' ...". The relevant change is "an lvalue"
130 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000131 //
132 // C++ 4.2p1:
133 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
134 // T" can be converted to an rvalue of type "pointer to T".
135 //
136 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
137 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000138 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
139 }
Chris Lattner299b8842008-07-25 21:10:04 +0000140}
141
142/// UsualUnaryConversions - Performs various conversions that are common to most
143/// operators (C99 6.3). The conversions of array and function types are
144/// sometimes surpressed. For example, the array->pointer conversion doesn't
145/// apply if the array is an argument to the sizeof or address (&) operators.
146/// In these instances, this routine should *not* be called.
147Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
148 QualType Ty = Expr->getType();
149 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
150
Chris Lattner299b8842008-07-25 21:10:04 +0000151 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
152 ImpCastExprToType(Expr, Context.IntTy);
153 else
154 DefaultFunctionArrayConversion(Expr);
155
156 return Expr;
157}
158
Chris Lattner9305c3d2008-07-25 22:25:12 +0000159/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
160/// do not have a prototype. Arguments that have type float are promoted to
161/// double. All other argument types are converted by UsualUnaryConversions().
162void Sema::DefaultArgumentPromotion(Expr *&Expr) {
163 QualType Ty = Expr->getType();
164 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
165
166 // If this is a 'float' (CVR qualified or typedef) promote to double.
167 if (const BuiltinType *BT = Ty->getAsBuiltinType())
168 if (BT->getKind() == BuiltinType::Float)
169 return ImpCastExprToType(Expr, Context.DoubleTy);
170
171 UsualUnaryConversions(Expr);
172}
173
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000174// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
175// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000176void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000177 DefaultArgumentPromotion(Expr);
178
179 if (!Expr->getType()->isPODType()) {
180 Diag(Expr->getLocStart(),
181 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
182 Expr->getType() << CT;
183 }
184}
185
186
Chris Lattner299b8842008-07-25 21:10:04 +0000187/// UsualArithmeticConversions - Performs various conversions that are common to
188/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
189/// routine returns the first non-arithmetic type found. The client is
190/// responsible for emitting appropriate error diagnostics.
191/// FIXME: verify the conversion rules for "complex int" are consistent with
192/// GCC.
193QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
194 bool isCompAssign) {
195 if (!isCompAssign) {
196 UsualUnaryConversions(lhsExpr);
197 UsualUnaryConversions(rhsExpr);
198 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000199
Chris Lattner299b8842008-07-25 21:10:04 +0000200 // For conversion purposes, we ignore any qualifiers.
201 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000202 QualType lhs =
203 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
204 QualType rhs =
205 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000206
207 // If both types are identical, no conversion is needed.
208 if (lhs == rhs)
209 return lhs;
210
211 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
212 // The caller can deal with this (e.g. pointer + int).
213 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
214 return lhs;
215
216 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
217 if (!isCompAssign) {
218 ImpCastExprToType(lhsExpr, destType);
219 ImpCastExprToType(rhsExpr, destType);
220 }
221 return destType;
222}
223
224QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
225 // Perform the usual unary conversions. We do this early so that
226 // integral promotions to "int" can allow us to exit early, in the
227 // lhs == rhs check. Also, for conversion purposes, we ignore any
228 // qualifiers. For example, "const float" and "float" are
229 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000230 if (lhs->isPromotableIntegerType())
231 lhs = Context.IntTy;
232 else
233 lhs = lhs.getUnqualifiedType();
234 if (rhs->isPromotableIntegerType())
235 rhs = Context.IntTy;
236 else
237 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000238
Chris Lattner299b8842008-07-25 21:10:04 +0000239 // If both types are identical, no conversion is needed.
240 if (lhs == rhs)
241 return lhs;
242
243 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
244 // The caller can deal with this (e.g. pointer + int).
245 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
246 return lhs;
247
248 // At this point, we have two different arithmetic types.
249
250 // Handle complex types first (C99 6.3.1.8p1).
251 if (lhs->isComplexType() || rhs->isComplexType()) {
252 // if we have an integer operand, the result is the complex type.
253 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
254 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000255 return lhs;
256 }
257 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
258 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000259 return rhs;
260 }
261 // This handles complex/complex, complex/float, or float/complex.
262 // When both operands are complex, the shorter operand is converted to the
263 // type of the longer, and that is the type of the result. This corresponds
264 // to what is done when combining two real floating-point operands.
265 // The fun begins when size promotion occur across type domains.
266 // From H&S 6.3.4: When one operand is complex and the other is a real
267 // floating-point type, the less precise type is converted, within it's
268 // real or complex domain, to the precision of the other type. For example,
269 // when combining a "long double" with a "double _Complex", the
270 // "double _Complex" is promoted to "long double _Complex".
271 int result = Context.getFloatingTypeOrder(lhs, rhs);
272
273 if (result > 0) { // The left side is bigger, convert rhs.
274 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000275 } else if (result < 0) { // The right side is bigger, convert lhs.
276 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000277 }
278 // At this point, lhs and rhs have the same rank/size. Now, make sure the
279 // domains match. This is a requirement for our implementation, C99
280 // does not require this promotion.
281 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
282 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000283 return rhs;
284 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000285 return lhs;
286 }
287 }
288 return lhs; // The domain/size match exactly.
289 }
290 // Now handle "real" floating types (i.e. float, double, long double).
291 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
292 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000293 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000294 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000295 return lhs;
296 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000297 if (rhs->isComplexIntegerType()) {
298 // convert rhs to the complex floating point type.
299 return Context.getComplexType(lhs);
300 }
301 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000302 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000303 return rhs;
304 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000305 if (lhs->isComplexIntegerType()) {
306 // convert lhs to the complex floating point type.
307 return Context.getComplexType(rhs);
308 }
Chris Lattner299b8842008-07-25 21:10:04 +0000309 // We have two real floating types, float/complex combos were handled above.
310 // Convert the smaller operand to the bigger result.
311 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000312 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000313 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000314 assert(result < 0 && "illegal float comparison");
315 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000316 }
317 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
318 // Handle GCC complex int extension.
319 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
320 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
321
322 if (lhsComplexInt && rhsComplexInt) {
323 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000324 rhsComplexInt->getElementType()) >= 0)
325 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000326 return rhs;
327 } else if (lhsComplexInt && rhs->isIntegerType()) {
328 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000329 return lhs;
330 } else if (rhsComplexInt && lhs->isIntegerType()) {
331 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000332 return rhs;
333 }
334 }
335 // Finally, we have two differing integer types.
336 // The rules for this case are in C99 6.3.1.8
337 int compare = Context.getIntegerTypeOrder(lhs, rhs);
338 bool lhsSigned = lhs->isSignedIntegerType(),
339 rhsSigned = rhs->isSignedIntegerType();
340 QualType destType;
341 if (lhsSigned == rhsSigned) {
342 // Same signedness; use the higher-ranked type
343 destType = compare >= 0 ? lhs : rhs;
344 } else if (compare != (lhsSigned ? 1 : -1)) {
345 // The unsigned type has greater than or equal rank to the
346 // signed type, so use the unsigned type
347 destType = lhsSigned ? rhs : lhs;
348 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
349 // The two types are different widths; if we are here, that
350 // means the signed type is larger than the unsigned type, so
351 // use the signed type.
352 destType = lhsSigned ? lhs : rhs;
353 } else {
354 // The signed type is higher-ranked than the unsigned type,
355 // but isn't actually any bigger (like unsigned int and long
356 // on most 32-bit systems). Use the unsigned type corresponding
357 // to the signed type.
358 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
359 }
Chris Lattner299b8842008-07-25 21:10:04 +0000360 return destType;
361}
362
363//===----------------------------------------------------------------------===//
364// Semantic Analysis for various Expression Types
365//===----------------------------------------------------------------------===//
366
367
Steve Naroff87d58b42007-09-16 03:34:24 +0000368/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000369/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
370/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
371/// multiple tokens. However, the common case is that StringToks points to one
372/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000373///
374Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000375Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000376 assert(NumStringToks && "Must have at least one string!");
377
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000378 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000379 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000380 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000381
382 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
383 for (unsigned i = 0; i != NumStringToks; ++i)
384 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000385
Chris Lattnera6dcce32008-02-11 00:02:17 +0000386 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000387 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000388 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000389
390 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
391 if (getLangOptions().CPlusPlus)
392 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000393
Chris Lattnera6dcce32008-02-11 00:02:17 +0000394 // Get an array type for the string, according to C99 6.4.5. This includes
395 // the nul terminator character as well as the string length for pascal
396 // strings.
397 StrTy = Context.getConstantArrayType(StrTy,
398 llvm::APInt(32, Literal.GetStringLength()+1),
399 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000400
Chris Lattner4b009652007-07-25 00:24:17 +0000401 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000402 return Owned(StringLiteral::Create(Context, Literal.GetString(),
403 Literal.GetStringLength(),
404 Literal.AnyWide, StrTy,
405 &StringTokLocs[0],
406 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000407}
408
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000409/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
410/// CurBlock to VD should cause it to be snapshotted (as we do for auto
411/// variables defined outside the block) or false if this is not needed (e.g.
412/// for values inside the block or for globals).
413///
414/// FIXME: This will create BlockDeclRefExprs for global variables,
415/// function references, etc which is suboptimal :) and breaks
416/// things like "integer constant expression" tests.
417static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
418 ValueDecl *VD) {
419 // If the value is defined inside the block, we couldn't snapshot it even if
420 // we wanted to.
421 if (CurBlock->TheDecl == VD->getDeclContext())
422 return false;
423
424 // If this is an enum constant or function, it is constant, don't snapshot.
425 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
426 return false;
427
428 // If this is a reference to an extern, static, or global variable, no need to
429 // snapshot it.
430 // FIXME: What about 'const' variables in C++?
431 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
432 return Var->hasLocalStorage();
433
434 return true;
435}
436
437
438
Steve Naroff0acc9c92007-09-15 18:49:24 +0000439/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000440/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000441/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000442/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000443/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000444Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
445 IdentifierInfo &II,
446 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000447 const CXXScopeSpec *SS,
448 bool isAddressOfOperand) {
449 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000450 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000451}
452
Douglas Gregor566782a2009-01-06 05:10:23 +0000453/// BuildDeclRefExpr - Build either a DeclRefExpr or a
454/// QualifiedDeclRefExpr based on whether or not SS is a
455/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000456DeclRefExpr *
457Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
458 bool TypeDependent, bool ValueDependent,
459 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000460 if (SS && !SS->isEmpty())
461 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Mike Stump9afab102009-02-19 03:04:26 +0000462 ValueDependent,
463 SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000464 else
465 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000466}
467
Douglas Gregor723d3332009-01-07 00:43:41 +0000468/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
469/// variable corresponding to the anonymous union or struct whose type
470/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000471static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000472 assert(Record->isAnonymousStructOrUnion() &&
473 "Record must be an anonymous struct or union!");
474
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000475 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000476 // be an O(1) operation rather than a slow walk through DeclContext's
477 // vector (which itself will be eliminated). DeclGroups might make
478 // this even better.
479 DeclContext *Ctx = Record->getDeclContext();
480 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
481 DEnd = Ctx->decls_end();
482 D != DEnd; ++D) {
483 if (*D == Record) {
484 // The object for the anonymous struct/union directly
485 // follows its type in the list of declarations.
486 ++D;
487 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000488 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000489 return *D;
490 }
491 }
492
493 assert(false && "Missing object for anonymous record");
494 return 0;
495}
496
Sebastian Redlcd883f72009-01-18 18:53:16 +0000497Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000498Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
499 FieldDecl *Field,
500 Expr *BaseObjectExpr,
501 SourceLocation OpLoc) {
502 assert(Field->getDeclContext()->isRecord() &&
503 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
504 && "Field must be stored inside an anonymous struct or union");
505
506 // Construct the sequence of field member references
507 // we'll have to perform to get to the field in the anonymous
508 // union/struct. The list of members is built from the field
509 // outward, so traverse it backwards to go from an object in
510 // the current context to the field we found.
511 llvm::SmallVector<FieldDecl *, 4> AnonFields;
512 AnonFields.push_back(Field);
513 VarDecl *BaseObject = 0;
514 DeclContext *Ctx = Field->getDeclContext();
515 do {
516 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000517 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000518 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
519 AnonFields.push_back(AnonField);
520 else {
521 BaseObject = cast<VarDecl>(AnonObject);
522 break;
523 }
524 Ctx = Ctx->getParent();
525 } while (Ctx->isRecord() &&
526 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
527
528 // Build the expression that refers to the base object, from
529 // which we will build a sequence of member references to each
530 // of the anonymous union objects and, eventually, the field we
531 // found via name lookup.
532 bool BaseObjectIsPointer = false;
533 unsigned ExtraQuals = 0;
534 if (BaseObject) {
535 // BaseObject is an anonymous struct/union variable (and is,
536 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000537 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000538 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000539 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000540 ExtraQuals
541 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
542 } else if (BaseObjectExpr) {
543 // The caller provided the base object expression. Determine
544 // whether its a pointer and whether it adds any qualifiers to the
545 // anonymous struct/union fields we're looking into.
546 QualType ObjectType = BaseObjectExpr->getType();
547 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
548 BaseObjectIsPointer = true;
549 ObjectType = ObjectPtr->getPointeeType();
550 }
551 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
552 } else {
553 // We've found a member of an anonymous struct/union that is
554 // inside a non-anonymous struct/union, so in a well-formed
555 // program our base object expression is "this".
556 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
557 if (!MD->isStatic()) {
558 QualType AnonFieldType
559 = Context.getTagDeclType(
560 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
561 QualType ThisType = Context.getTagDeclType(MD->getParent());
562 if ((Context.getCanonicalType(AnonFieldType)
563 == Context.getCanonicalType(ThisType)) ||
564 IsDerivedFrom(ThisType, AnonFieldType)) {
565 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000566 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000567 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000568 BaseObjectIsPointer = true;
569 }
570 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000571 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
572 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000573 }
574 ExtraQuals = MD->getTypeQualifiers();
575 }
576
577 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000578 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
579 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000580 }
581
582 // Build the implicit member references to the field of the
583 // anonymous struct/union.
584 Expr *Result = BaseObjectExpr;
585 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
586 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
587 FI != FIEnd; ++FI) {
588 QualType MemberType = (*FI)->getType();
589 if (!(*FI)->isMutable()) {
590 unsigned combinedQualifiers
591 = MemberType.getCVRQualifiers() | ExtraQuals;
592 MemberType = MemberType.getQualifiedType(combinedQualifiers);
593 }
Steve Naroff774e4152009-01-21 00:14:39 +0000594 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
595 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000596 BaseObjectIsPointer = false;
597 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
598 OpLoc = SourceLocation();
599 }
600
Sebastian Redlcd883f72009-01-18 18:53:16 +0000601 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000602}
603
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000604/// ActOnDeclarationNameExpr - The parser has read some kind of name
605/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
606/// performs lookup on that name and returns an expression that refers
607/// to that name. This routine isn't directly called from the parser,
608/// because the parser doesn't know about DeclarationName. Rather,
609/// this routine is called by ActOnIdentifierExpr,
610/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
611/// which form the DeclarationName from the corresponding syntactic
612/// forms.
613///
614/// HasTrailingLParen indicates whether this identifier is used in a
615/// function call context. LookupCtx is only used for a C++
616/// qualified-id (foo::bar) to indicate the class or namespace that
617/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000618///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000619/// isAddressOfOperand means that this expression is the direct operand
620/// of an address-of operator. This matters because this is the only
621/// situation where a qualified name referencing a non-static member may
622/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000623Sema::OwningExprResult
624Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
625 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000626 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000627 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000628 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000629 if (SS && SS->isInvalid())
630 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000631 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
632 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000633
Douglas Gregor09be81b2009-02-04 17:27:36 +0000634 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000635 if (Lookup.isAmbiguous()) {
636 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
637 SS && SS->isSet() ? SS->getRange()
638 : SourceRange());
639 return ExprError();
640 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000641 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000642
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000643 // If this reference is in an Objective-C method, then ivar lookup happens as
644 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000645 IdentifierInfo *II = Name.getAsIdentifierInfo();
646 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000647 // There are two cases to handle here. 1) scoped lookup could have failed,
648 // in which case we should look for an ivar. 2) scoped lookup could have
649 // found a decl, but that decl is outside the current method (i.e. a global
650 // variable). In these two cases, we do a lookup for an ivar with this
651 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000652 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000653 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000654 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000655 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000656 if (DiagnoseUseOfDecl(IV, Loc))
657 return ExprError();
Chris Lattner2a3bef92009-02-16 17:19:12 +0000658
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000659 // FIXME: This should use a new expr for a direct reference, don't turn
660 // this into Self->ivar, just return a BareIVarExpr or something.
661 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000662 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Mike Stump9afab102009-02-19 03:04:26 +0000663 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +0000664 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000665 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000666 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000667 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000668 }
669 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000670 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000671 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000672 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000673 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000674 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000675 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000676 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000677
Douglas Gregoraa57e862009-02-18 21:56:37 +0000678 // Determine whether this name might be a candidate for
679 // argument-dependent lookup.
680 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
681 HasTrailingLParen;
682
683 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000684 // We've seen something of the form
685 //
686 // identifier(
687 //
688 // and we did not find any entity by the name
689 // "identifier". However, this identifier is still subject to
690 // argument-dependent lookup, so keep track of the name.
691 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
692 Context.OverloadTy,
693 Loc));
694 }
695
Chris Lattner4b009652007-07-25 00:24:17 +0000696 if (D == 0) {
697 // Otherwise, this could be an implicitly declared function reference (legal
698 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000699 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000700 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000701 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000702 else {
703 // If this name wasn't predeclared and if this is not a function call,
704 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000705 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000706 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
707 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000708 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
709 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000710 return ExprError(Diag(Loc, diag::err_undeclared_use)
711 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000712 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000713 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000714 }
715 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000716
Sebastian Redl0c9da212009-02-03 20:19:35 +0000717 // If this is an expression of the form &Class::member, don't build an
718 // implicit member ref, because we want a pointer to the member in general,
719 // not any specific instance's member.
720 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000721 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000722 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000723 QualType DType;
724 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
725 DType = FD->getType().getNonReferenceType();
726 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
727 DType = Method->getType();
728 } else if (isa<OverloadedFunctionDecl>(D)) {
729 DType = Context.OverloadTy;
730 }
731 // Could be an inner type. That's diagnosed below, so ignore it here.
732 if (!DType.isNull()) {
733 // The pointer is type- and value-dependent if it points into something
734 // dependent.
735 bool Dependent = false;
736 for (; DC; DC = DC->getParent()) {
737 // FIXME: could stop early at namespace scope.
738 if (DC->isRecord()) {
739 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
740 if (Context.getTypeDeclType(Record)->isDependentType()) {
741 Dependent = true;
742 break;
743 }
744 }
745 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000746 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000747 }
748 }
749 }
750
Douglas Gregor723d3332009-01-07 00:43:41 +0000751 // We may have found a field within an anonymous union or struct
752 // (C++ [class.union]).
753 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
754 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
755 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000756
Douglas Gregor3257fb52008-12-22 05:46:06 +0000757 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
758 if (!MD->isStatic()) {
759 // C++ [class.mfct.nonstatic]p2:
760 // [...] if name lookup (3.4.1) resolves the name in the
761 // id-expression to a nonstatic nontype member of class X or of
762 // a base class of X, the id-expression is transformed into a
763 // class member access expression (5.2.5) using (*this) (9.3.2)
764 // as the postfix-expression to the left of the '.' operator.
765 DeclContext *Ctx = 0;
766 QualType MemberType;
767 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
768 Ctx = FD->getDeclContext();
769 MemberType = FD->getType();
770
771 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
772 MemberType = RefType->getPointeeType();
773 else if (!FD->isMutable()) {
774 unsigned combinedQualifiers
775 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
776 MemberType = MemberType.getQualifiedType(combinedQualifiers);
777 }
778 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
779 if (!Method->isStatic()) {
780 Ctx = Method->getParent();
781 MemberType = Method->getType();
782 }
783 } else if (OverloadedFunctionDecl *Ovl
784 = dyn_cast<OverloadedFunctionDecl>(D)) {
785 for (OverloadedFunctionDecl::function_iterator
786 Func = Ovl->function_begin(),
787 FuncEnd = Ovl->function_end();
788 Func != FuncEnd; ++Func) {
789 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
790 if (!DMethod->isStatic()) {
791 Ctx = Ovl->getDeclContext();
792 MemberType = Context.OverloadTy;
793 break;
794 }
795 }
796 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000797
798 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000799 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
800 QualType ThisType = Context.getTagDeclType(MD->getParent());
801 if ((Context.getCanonicalType(CtxType)
802 == Context.getCanonicalType(ThisType)) ||
803 IsDerivedFrom(ThisType, CtxType)) {
804 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000805 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000806 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000807 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000808 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000809 }
810 }
811 }
812 }
813
Douglas Gregor8acb7272008-12-11 16:49:14 +0000814 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000815 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
816 if (MD->isStatic())
817 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000818 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
819 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000820 }
821
Douglas Gregor3257fb52008-12-22 05:46:06 +0000822 // Any other ways we could have found the field in a well-formed
823 // program would have been turned into implicit member expressions
824 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000825 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
826 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000827 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000828
Chris Lattner4b009652007-07-25 00:24:17 +0000829 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000830 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000831 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000832 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000833 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000834 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000835
Steve Naroffd6163f32008-09-05 22:11:13 +0000836 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000837 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000838 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
839 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000840 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
841 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
842 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000843 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000844
Douglas Gregoraa57e862009-02-18 21:56:37 +0000845 // Check whether this declaration can be used. Note that we suppress
846 // this check when we're going to perform argument-dependent lookup
847 // on this function name, because this might not be the function
848 // that overload resolution actually selects.
849 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
850 return ExprError();
851
Douglas Gregor48840c72008-12-10 23:01:14 +0000852 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000853 // Warn about constructs like:
854 // if (void *X = foo()) { ... } else { X }.
855 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000856 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
857 Scope *CheckS = S;
858 while (CheckS) {
859 if (CheckS->isWithinElse() &&
860 CheckS->getControlParent()->isDeclScope(Var)) {
861 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000862 ExprError(Diag(Loc, diag::warn_value_always_false)
863 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000864 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000865 ExprError(Diag(Loc, diag::warn_value_always_zero)
866 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000867 break;
868 }
869
870 // Move up one more control parent to check again.
871 CheckS = CheckS->getControlParent();
872 if (CheckS)
873 CheckS = CheckS->getParent();
874 }
875 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000876 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
877 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
878 // C99 DR 316 says that, if a function type comes from a
879 // function definition (without a prototype), that type is only
880 // used for checking compatibility. Therefore, when referencing
881 // the function, we pretend that we don't have the full function
882 // type.
883 QualType T = Func->getType();
884 QualType NoProtoType = T;
885 if (const FunctionTypeProto *Proto = T->getAsFunctionTypeProto())
886 NoProtoType = Context.getFunctionTypeNoProto(Proto->getResultType());
887 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
888 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000889 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000890
891 // Only create DeclRefExpr's for valid Decl's.
892 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000893 return ExprError();
894
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000895 // If the identifier reference is inside a block, and it refers to a value
896 // that is outside the block, create a BlockDeclRefExpr instead of a
897 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
898 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000899 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000900 // We do not do this for things like enum constants, global variables, etc,
901 // as they do not get snapshotted.
902 //
903 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000904 // Blocks that have these can't be constant.
905 CurBlock->hasBlockDeclRefExprs = true;
906
Steve Naroff52059382008-10-10 01:28:17 +0000907 // The BlocksAttr indicates the variable is bound by-reference.
908 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000909 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000910 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000911
Steve Naroff52059382008-10-10 01:28:17 +0000912 // Variable will be bound by-copy, make it const within the closure.
913 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000914 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000915 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000916 }
917 // If this reference is not in a block or if the referenced variable is
918 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000919
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000920 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000921 bool ValueDependent = false;
922 if (getLangOptions().CPlusPlus) {
923 // C++ [temp.dep.expr]p3:
924 // An id-expression is type-dependent if it contains:
925 // - an identifier that was declared with a dependent type,
926 if (VD->getType()->isDependentType())
927 TypeDependent = true;
928 // - FIXME: a template-id that is dependent,
929 // - a conversion-function-id that specifies a dependent type,
930 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
931 Name.getCXXNameType()->isDependentType())
932 TypeDependent = true;
933 // - a nested-name-specifier that contains a class-name that
934 // names a dependent type.
935 else if (SS && !SS->isEmpty()) {
936 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
937 DC; DC = DC->getParent()) {
938 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000939 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000940 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
941 if (Context.getTypeDeclType(Record)->isDependentType()) {
942 TypeDependent = true;
943 break;
944 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000945 }
946 }
947 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000948
Douglas Gregora5d84612008-12-10 20:57:37 +0000949 // C++ [temp.dep.constexpr]p2:
950 //
951 // An identifier is value-dependent if it is:
952 // - a name declared with a dependent type,
953 if (TypeDependent)
954 ValueDependent = true;
955 // - the name of a non-type template parameter,
956 else if (isa<NonTypeTemplateParmDecl>(VD))
957 ValueDependent = true;
958 // - a constant with integral or enumeration type and is
959 // initialized with an expression that is value-dependent
960 // (FIXME!).
961 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000962
Sebastian Redlcd883f72009-01-18 18:53:16 +0000963 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
964 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000965}
966
Sebastian Redlcd883f72009-01-18 18:53:16 +0000967Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
968 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000969 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000970
Chris Lattner4b009652007-07-25 00:24:17 +0000971 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000972 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000973 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
974 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
975 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000976 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000977
Chris Lattner7e637512008-01-12 08:14:25 +0000978 // Pre-defined identifiers are of type char[x], where x is the length of the
979 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000980 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000981 if (FunctionDecl *FD = getCurFunctionDecl())
982 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000983 else if (ObjCMethodDecl *MD = getCurMethodDecl())
984 Length = MD->getSynthesizedMethodSize();
985 else {
986 Diag(Loc, diag::ext_predef_outside_function);
987 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
988 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
989 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990
991
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000992 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000993 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000994 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000995 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000996}
997
Sebastian Redlcd883f72009-01-18 18:53:16 +0000998Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000999 llvm::SmallString<16> CharBuffer;
1000 CharBuffer.resize(Tok.getLength());
1001 const char *ThisTokBegin = &CharBuffer[0];
1002 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001003
Chris Lattner4b009652007-07-25 00:24:17 +00001004 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1005 Tok.getLocation(), PP);
1006 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001007 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001008
1009 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1010
Sebastian Redl75324932009-01-20 22:23:13 +00001011 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1012 Literal.isWide(),
1013 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001014}
1015
Sebastian Redlcd883f72009-01-18 18:53:16 +00001016Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1017 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1019 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001020 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001021 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001022 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001023 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001024 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001025
Chris Lattner4b009652007-07-25 00:24:17 +00001026 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001027 // Add padding so that NumericLiteralParser can overread by one character.
1028 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001029 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001030
Chris Lattner4b009652007-07-25 00:24:17 +00001031 // Get the spelling of the token, which eliminates trigraphs, etc.
1032 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033
Chris Lattner4b009652007-07-25 00:24:17 +00001034 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1035 Tok.getLocation(), PP);
1036 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001037 return ExprError();
1038
Chris Lattner1de66eb2007-08-26 03:42:43 +00001039 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001040
Chris Lattner1de66eb2007-08-26 03:42:43 +00001041 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001042 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001043 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001044 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001045 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001046 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001047 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001048 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001049
1050 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1051
Ted Kremenekddedbe22007-11-29 00:56:49 +00001052 // isExact will be set by GetFloatValue().
1053 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001054 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1055 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001056
Chris Lattner1de66eb2007-08-26 03:42:43 +00001057 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001058 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001059 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001060 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001061
Neil Booth7421e9c2007-08-29 22:00:19 +00001062 // long long is a C99 feature.
1063 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001064 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001065 Diag(Tok.getLocation(), diag::ext_longlong);
1066
Chris Lattner4b009652007-07-25 00:24:17 +00001067 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001068 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001069
Chris Lattner4b009652007-07-25 00:24:17 +00001070 if (Literal.GetIntegerValue(ResultVal)) {
1071 // If this value didn't fit into uintmax_t, warn and force to ull.
1072 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001073 Ty = Context.UnsignedLongLongTy;
1074 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001075 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001076 } else {
1077 // If this value fits into a ULL, try to figure out what else it fits into
1078 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001079
Chris Lattner4b009652007-07-25 00:24:17 +00001080 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1081 // be an unsigned int.
1082 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1083
1084 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001085 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001086 if (!Literal.isLong && !Literal.isLongLong) {
1087 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001088 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001089
Chris Lattner4b009652007-07-25 00:24:17 +00001090 // Does it fit in a unsigned int?
1091 if (ResultVal.isIntN(IntSize)) {
1092 // Does it fit in a signed int?
1093 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001094 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001095 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001096 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001097 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001098 }
Chris Lattner4b009652007-07-25 00:24:17 +00001099 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001100
Chris Lattner4b009652007-07-25 00:24:17 +00001101 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001102 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001103 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001104
Chris Lattner4b009652007-07-25 00:24:17 +00001105 // Does it fit in a unsigned long?
1106 if (ResultVal.isIntN(LongSize)) {
1107 // Does it fit in a signed long?
1108 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001109 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001110 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001111 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001112 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001113 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001114 }
1115
Chris Lattner4b009652007-07-25 00:24:17 +00001116 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001117 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001118 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001119
Chris Lattner4b009652007-07-25 00:24:17 +00001120 // Does it fit in a unsigned long long?
1121 if (ResultVal.isIntN(LongLongSize)) {
1122 // Does it fit in a signed long long?
1123 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001124 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001125 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001126 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001127 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001128 }
1129 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001130
Chris Lattner4b009652007-07-25 00:24:17 +00001131 // If we still couldn't decide a type, we probably have something that
1132 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001133 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001134 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001135 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001136 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001137 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001138
Chris Lattnere4068872008-05-09 05:59:00 +00001139 if (ResultVal.getBitWidth() != Width)
1140 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001141 }
Sebastian Redl75324932009-01-20 22:23:13 +00001142 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001143 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001144
Chris Lattner1de66eb2007-08-26 03:42:43 +00001145 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1146 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001147 Res = new (Context) ImaginaryLiteral(Res,
1148 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001149
1150 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001151}
1152
Sebastian Redlcd883f72009-01-18 18:53:16 +00001153Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1154 SourceLocation R, ExprArg Val) {
1155 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001156 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001157 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001158}
1159
1160/// The UsualUnaryConversions() function is *not* called by this routine.
1161/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001162bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001163 SourceLocation OpLoc,
1164 const SourceRange &ExprRange,
1165 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001166 if (exprType->isDependentType())
1167 return false;
1168
Chris Lattner4b009652007-07-25 00:24:17 +00001169 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001170 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001171 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001172 if (isSizeof)
1173 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1174 return false;
1175 }
1176
1177 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001178 Diag(OpLoc, diag::ext_sizeof_void_type)
1179 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001180 return false;
1181 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001182
Chris Lattner159fe082009-01-24 19:46:37 +00001183 return DiagnoseIncompleteType(OpLoc, exprType,
1184 isSizeof ? diag::err_sizeof_incomplete_type :
1185 diag::err_alignof_incomplete_type,
1186 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001187}
1188
Chris Lattner8d9f7962009-01-24 20:17:12 +00001189bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1190 const SourceRange &ExprRange) {
1191 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001192
Chris Lattner8d9f7962009-01-24 20:17:12 +00001193 // alignof decl is always ok.
1194 if (isa<DeclRefExpr>(E))
1195 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001196
1197 // Cannot know anything else if the expression is dependent.
1198 if (E->isTypeDependent())
1199 return false;
1200
Chris Lattner8d9f7962009-01-24 20:17:12 +00001201 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1202 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1203 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001204 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001205 return true;
1206 }
1207 // Other fields are ok.
1208 return false;
1209 }
1210 }
1211 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1212}
1213
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001214/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1215/// the same for @c alignof and @c __alignof
1216/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001217Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001218Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1219 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001220 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001221 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001222
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001223 QualType ArgTy;
1224 SourceRange Range;
1225 if (isType) {
1226 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1227 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001228
1229 // Verify that the operand is valid.
1230 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1231 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001232 } else {
1233 // Get the end location.
1234 Expr *ArgEx = (Expr *)TyOrEx;
1235 Range = ArgEx->getSourceRange();
1236 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001237
1238 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001239 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001240 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001241 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001242 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1243 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1244 isInvalid = true;
1245 } else {
1246 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1247 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001248
1249 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001250 DeleteExpr(ArgEx);
1251 return ExprError();
1252 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001253 }
1254
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001255 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001256 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001257 Context.getSizeType(), OpLoc,
1258 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001259}
1260
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001261QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001262 if (V->isTypeDependent())
1263 return Context.DependentTy;
1264
Chris Lattner03931a72007-08-24 21:16:53 +00001265 DefaultFunctionArrayConversion(V);
1266
Chris Lattnera16e42d2007-08-26 05:39:26 +00001267 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001268 if (const ComplexType *CT = V->getType()->getAsComplexType())
1269 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001270
1271 // Otherwise they pass through real integer and floating point types here.
1272 if (V->getType()->isArithmeticType())
1273 return V->getType();
1274
1275 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001276 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1277 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001278 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001279}
1280
1281
Chris Lattner4b009652007-07-25 00:24:17 +00001282
Sebastian Redl8b769972009-01-19 00:08:26 +00001283Action::OwningExprResult
1284Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1285 tok::TokenKind Kind, ExprArg Input) {
1286 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001287
Chris Lattner4b009652007-07-25 00:24:17 +00001288 UnaryOperator::Opcode Opc;
1289 switch (Kind) {
1290 default: assert(0 && "Unknown unary op!");
1291 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1292 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1293 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001294
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001295 if (getLangOptions().CPlusPlus &&
1296 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1297 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001298 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001299 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1300
1301 // C++ [over.inc]p1:
1302 //
1303 // [...] If the function is a member function with one
1304 // parameter (which shall be of type int) or a non-member
1305 // function with two parameters (the second of which shall be
1306 // of type int), it defines the postfix increment operator ++
1307 // for objects of that type. When the postfix increment is
1308 // called as a result of using the ++ operator, the int
1309 // argument will have value zero.
1310 Expr *Args[2] = {
1311 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001312 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1313 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001314 };
1315
1316 // Build the candidate set for overloading
1317 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001318 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1319 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001320
1321 // Perform overload resolution.
1322 OverloadCandidateSet::iterator Best;
1323 switch (BestViableFunction(CandidateSet, Best)) {
1324 case OR_Success: {
1325 // We found a built-in operator or an overloaded operator.
1326 FunctionDecl *FnDecl = Best->Function;
1327
1328 if (FnDecl) {
1329 // We matched an overloaded operator. Build a call to that
1330 // operator.
1331
1332 // Convert the arguments.
1333 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1334 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001335 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001336 } else {
1337 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001338 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001339 FnDecl->getParamDecl(0)->getType(),
1340 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001341 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001342 }
1343
1344 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001345 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001346 = FnDecl->getType()->getAsFunctionType()->getResultType();
1347 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001348
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001349 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001350 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001351 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001352 UsualUnaryConversions(FnExpr);
1353
Sebastian Redl8b769972009-01-19 00:08:26 +00001354 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001355 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1356 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001357 } else {
1358 // We matched a built-in operator. Convert the arguments, then
1359 // break out so that we will build the appropriate built-in
1360 // operator node.
1361 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1362 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001363 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001364
1365 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001366 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001367 }
1368
1369 case OR_No_Viable_Function:
1370 // No viable function; fall through to handling this as a
1371 // built-in operator, which will produce an error message for us.
1372 break;
1373
1374 case OR_Ambiguous:
1375 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1376 << UnaryOperator::getOpcodeStr(Opc)
1377 << Arg->getSourceRange();
1378 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001379 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001380
1381 case OR_Deleted:
1382 Diag(OpLoc, diag::err_ovl_deleted_oper)
1383 << Best->Function->isDeleted()
1384 << UnaryOperator::getOpcodeStr(Opc)
1385 << Arg->getSourceRange();
1386 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1387 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001388 }
1389
1390 // Either we found no viable overloaded operator or we matched a
1391 // built-in operator. In either case, fall through to trying to
1392 // build a built-in operation.
1393 }
1394
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001395 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1396 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001397 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001398 return ExprError();
1399 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001400 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001401}
1402
Sebastian Redl8b769972009-01-19 00:08:26 +00001403Action::OwningExprResult
1404Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1405 ExprArg Idx, SourceLocation RLoc) {
1406 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1407 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001408
Douglas Gregor80723c52008-11-19 17:17:41 +00001409 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001410 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001411 LHSExp->getType()->isEnumeralType() ||
1412 RHSExp->getType()->isRecordType() ||
1413 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001414 // Add the appropriate overloaded operators (C++ [over.match.oper])
1415 // to the candidate set.
1416 OverloadCandidateSet CandidateSet;
1417 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001418 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1419 SourceRange(LLoc, RLoc)))
1420 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001421
Douglas Gregor80723c52008-11-19 17:17:41 +00001422 // Perform overload resolution.
1423 OverloadCandidateSet::iterator Best;
1424 switch (BestViableFunction(CandidateSet, Best)) {
1425 case OR_Success: {
1426 // We found a built-in operator or an overloaded operator.
1427 FunctionDecl *FnDecl = Best->Function;
1428
1429 if (FnDecl) {
1430 // We matched an overloaded operator. Build a call to that
1431 // operator.
1432
1433 // Convert the arguments.
1434 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1435 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1436 PerformCopyInitialization(RHSExp,
1437 FnDecl->getParamDecl(0)->getType(),
1438 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001439 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001440 } else {
1441 // Convert the arguments.
1442 if (PerformCopyInitialization(LHSExp,
1443 FnDecl->getParamDecl(0)->getType(),
1444 "passing") ||
1445 PerformCopyInitialization(RHSExp,
1446 FnDecl->getParamDecl(1)->getType(),
1447 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001448 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001449 }
1450
1451 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001452 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001453 = FnDecl->getType()->getAsFunctionType()->getResultType();
1454 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001455
Douglas Gregor80723c52008-11-19 17:17:41 +00001456 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001457 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1458 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001459 UsualUnaryConversions(FnExpr);
1460
Sebastian Redl8b769972009-01-19 00:08:26 +00001461 Base.release();
1462 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001463 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001464 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001465 } else {
1466 // We matched a built-in operator. Convert the arguments, then
1467 // break out so that we will build the appropriate built-in
1468 // operator node.
1469 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1470 "passing") ||
1471 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1472 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001473 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001474
1475 break;
1476 }
1477 }
1478
1479 case OR_No_Viable_Function:
1480 // No viable function; fall through to handling this as a
1481 // built-in operator, which will produce an error message for us.
1482 break;
1483
1484 case OR_Ambiguous:
1485 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1486 << "[]"
1487 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1488 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001489 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001490
1491 case OR_Deleted:
1492 Diag(LLoc, diag::err_ovl_deleted_oper)
1493 << Best->Function->isDeleted()
1494 << "[]"
1495 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1496 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1497 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001498 }
1499
1500 // Either we found no viable overloaded operator or we matched a
1501 // built-in operator. In either case, fall through to trying to
1502 // build a built-in operation.
1503 }
1504
Chris Lattner4b009652007-07-25 00:24:17 +00001505 // Perform default conversions.
1506 DefaultFunctionArrayConversion(LHSExp);
1507 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001508
Chris Lattner4b009652007-07-25 00:24:17 +00001509 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1510
1511 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001512 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001513 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001514 // and index from the expression types.
1515 Expr *BaseExpr, *IndexExpr;
1516 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001517 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1518 BaseExpr = LHSExp;
1519 IndexExpr = RHSExp;
1520 ResultType = Context.DependentTy;
1521 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001522 BaseExpr = LHSExp;
1523 IndexExpr = RHSExp;
1524 // FIXME: need to deal with const...
1525 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001526 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001527 // Handle the uncommon case of "123[Ptr]".
1528 BaseExpr = RHSExp;
1529 IndexExpr = LHSExp;
1530 // FIXME: need to deal with const...
1531 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001532 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1533 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001534 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001535
Chris Lattner4b009652007-07-25 00:24:17 +00001536 // FIXME: need to deal with const...
1537 ResultType = VTy->getElementType();
1538 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001539 return ExprError(Diag(LHSExp->getLocStart(),
1540 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1541 }
Chris Lattner4b009652007-07-25 00:24:17 +00001542 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001543 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001544 return ExprError(Diag(IndexExpr->getLocStart(),
1545 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001546
1547 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1548 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001549 // void (*)(int)) and pointers to incomplete types. Functions are not
1550 // objects in C99.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001551 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001552 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001553 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001554 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001555
Sebastian Redl8b769972009-01-19 00:08:26 +00001556 Base.release();
1557 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001558 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001559 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001560}
1561
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001562QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001563CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001564 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001565 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001566
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001567 // The vector accessor can't exceed the number of elements.
1568 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001569
Mike Stump9afab102009-02-19 03:04:26 +00001570 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001571 // special names that indicate a subset of exactly half the elements are
1572 // to be selected.
1573 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001574
Nate Begeman1486b502009-01-18 01:47:54 +00001575 // This flag determines whether or not CompName has an 's' char prefix,
1576 // indicating that it is a string of hex values to be used as vector indices.
1577 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001578
1579 // Check that we've found one of the special components, or that the component
1580 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001581 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001582 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1583 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001584 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001585 do
1586 compStr++;
1587 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001588 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001589 do
1590 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001591 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001592 }
Nate Begeman1486b502009-01-18 01:47:54 +00001593
Mike Stump9afab102009-02-19 03:04:26 +00001594 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001595 // We didn't get to the end of the string. This means the component names
1596 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001597 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1598 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001599 return QualType();
1600 }
Mike Stump9afab102009-02-19 03:04:26 +00001601
Nate Begeman1486b502009-01-18 01:47:54 +00001602 // Ensure no component accessor exceeds the width of the vector type it
1603 // operates on.
1604 if (!HalvingSwizzle) {
1605 compStr = CompName.getName();
1606
1607 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001608 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001609
1610 while (*compStr) {
1611 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1612 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1613 << baseType << SourceRange(CompLoc);
1614 return QualType();
1615 }
1616 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001617 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001618
Nate Begeman1486b502009-01-18 01:47:54 +00001619 // If this is a halving swizzle, verify that the base type has an even
1620 // number of elements.
1621 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001622 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001623 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001624 return QualType();
1625 }
Mike Stump9afab102009-02-19 03:04:26 +00001626
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001627 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001628 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001629 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001630 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001631 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001632 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1633 : CompName.getLength();
1634 if (HexSwizzle)
1635 CompSize--;
1636
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001637 if (CompSize == 1)
1638 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001639
Nate Begemanaf6ed502008-04-18 23:10:10 +00001640 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001641 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001642 // diagostics look bad. We want extended vector types to appear built-in.
1643 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1644 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1645 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001646 }
1647 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001648}
1649
Chris Lattner2cb744b2009-02-15 22:43:40 +00001650
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001651/// constructSetterName - Return the setter name for the given
1652/// identifier, i.e. "set" + Name where the initial character of Name
1653/// has been capitalized.
1654// FIXME: Merge with same routine in Parser. But where should this
1655// live?
1656static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1657 const IdentifierInfo *Name) {
1658 llvm::SmallString<100> SelectorName;
1659 SelectorName = "set";
1660 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1661 SelectorName[3] = toupper(SelectorName[3]);
1662 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1663}
1664
Sebastian Redl8b769972009-01-19 00:08:26 +00001665Action::OwningExprResult
1666Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1667 tok::TokenKind OpKind, SourceLocation MemberLoc,
1668 IdentifierInfo &Member) {
1669 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001670 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001671
1672 // Perform default conversions.
1673 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001674
Steve Naroff2cb66382007-07-26 03:11:44 +00001675 QualType BaseType = BaseExpr->getType();
1676 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001677
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001678 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1679 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001680 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001681 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001682 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001683 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001684 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1685 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001686 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001687 return ExprError(Diag(MemberLoc,
1688 diag::err_typecheck_member_reference_arrow)
1689 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001690 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001691
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001692 // Handle field access to simple records. This also handles access to fields
1693 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001694 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001695 RecordDecl *RDecl = RTy->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00001696 if (DiagnoseIncompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001697 diag::err_typecheck_incomplete_tag,
1698 BaseExpr->getSourceRange()))
1699 return ExprError();
1700
Steve Naroff2cb66382007-07-26 03:11:44 +00001701 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001702 // FIXME: Qualified name lookup for C++ is a bit more complicated
1703 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001704 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001705 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001706 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001707
Douglas Gregor09be81b2009-02-04 17:27:36 +00001708 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001709 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001710 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1711 << &Member << BaseExpr->getSourceRange());
1712 else if (Result.isAmbiguous()) {
1713 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1714 MemberLoc, BaseExpr->getSourceRange());
1715 return ExprError();
1716 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001717 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001718
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001719 // If the decl being referenced had an error, return an error for this
1720 // sub-expr without emitting another error, in order to avoid cascading
1721 // error cases.
1722 if (MemberDecl->isInvalidDecl())
1723 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001724
Douglas Gregoraa57e862009-02-18 21:56:37 +00001725 // Check the use of this field
1726 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1727 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001728
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001729 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001730 // We may have found a field within an anonymous union or struct
1731 // (C++ [class.union]).
1732 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001733 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001734 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001735
Douglas Gregor82d44772008-12-20 23:49:58 +00001736 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1737 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001738 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001739 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1740 MemberType = Ref->getPointeeType();
1741 else {
1742 unsigned combinedQualifiers =
1743 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001744 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001745 combinedQualifiers &= ~QualType::Const;
1746 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1747 }
Eli Friedman76b49832008-02-06 22:48:16 +00001748
Steve Naroff774e4152009-01-21 00:14:39 +00001749 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1750 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001751 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001752 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001753 Var, MemberLoc,
1754 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001755 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001756 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001757 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001758 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001759 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001760 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001761 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001762 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001763 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1764 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001765 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001766 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1767 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001768
Douglas Gregor82d44772008-12-20 23:49:58 +00001769 // We found a declaration kind that we didn't expect. This is a
1770 // generic error message that tells the user that she can't refer
1771 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001772 return ExprError(Diag(MemberLoc,
1773 diag::err_typecheck_member_reference_unknown)
1774 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001775 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001776
Chris Lattnere9d71612008-07-21 04:59:05 +00001777 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1778 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001779 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001780 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001781 // If the decl being referenced had an error, return an error for this
1782 // sub-expr without emitting another error, in order to avoid cascading
1783 // error cases.
1784 if (IV->isInvalidDecl())
1785 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001786
1787 // Check whether we can reference this field.
1788 if (DiagnoseUseOfDecl(IV, MemberLoc))
1789 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001790
1791 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001792 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001793 OpKind == tok::arrow);
1794 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001795 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001796 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001797 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1798 << IFTy->getDecl()->getDeclName() << &Member
1799 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001800 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001801
Chris Lattnere9d71612008-07-21 04:59:05 +00001802 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1803 // pointer to a (potentially qualified) interface type.
1804 const PointerType *PTy;
1805 const ObjCInterfaceType *IFTy;
1806 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1807 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1808 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001809
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001810 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001811 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001812 // Check whether we can reference this property.
1813 if (DiagnoseUseOfDecl(PD, MemberLoc))
1814 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001815
Steve Naroff774e4152009-01-21 00:14:39 +00001816 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001817 MemberLoc, BaseExpr));
1818 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001819
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001820 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001821 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1822 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001823 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001824 // Check whether we can reference this property.
1825 if (DiagnoseUseOfDecl(PD, MemberLoc))
1826 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001827
Steve Naroff774e4152009-01-21 00:14:39 +00001828 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001829 MemberLoc, BaseExpr));
1830 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001831
1832 // If that failed, look for an "implicit" property by seeing if the nullary
1833 // selector is implemented.
1834
1835 // FIXME: The logic for looking up nullary and unary selectors should be
1836 // shared with the code in ActOnInstanceMessage.
1837
1838 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1839 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001840
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001841 // If this reference is in an @implementation, check for 'private' methods.
1842 if (!Getter)
1843 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1844 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001845 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001846 ObjCImplementations[ClassDecl->getIdentifier()])
1847 Getter = ImpDecl->getInstanceMethod(Sel);
1848
Steve Naroff04151f32008-10-22 19:16:27 +00001849 // Look through local category implementations associated with the class.
1850 if (!Getter) {
1851 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1852 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1853 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1854 }
1855 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001856 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001857 // Check if we can reference this property.
1858 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1859 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001860
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001861 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001862 // will look for the matching setter, in case it is needed.
1863 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1864 &Member);
1865 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1866 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1867 if (!Setter) {
Mike Stump9afab102009-02-19 03:04:26 +00001868 // If this reference is in an @implementation, also check for 'private'
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001869 // methods.
1870 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1871 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001872 if (ObjCImplementationDecl *ImpDecl =
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001873 ObjCImplementations[ClassDecl->getIdentifier()])
1874 Setter = ImpDecl->getInstanceMethod(SetterSel);
1875 }
1876 // Look through local category implementations associated with the class.
1877 if (!Setter) {
1878 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1879 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1880 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1881 }
1882 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001883
Douglas Gregoraa57e862009-02-18 21:56:37 +00001884 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1885 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001886
Sebastian Redl8b769972009-01-19 00:08:26 +00001887 // FIXME: we must check that the setter has property type.
Mike Stump9afab102009-02-19 03:04:26 +00001888 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001889 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001890 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001891
1892 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1893 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001894 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001895 // Handle properties on qualified "id" protocols.
1896 const ObjCQualifiedIdType *QIdTy;
1897 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1898 // Check protocols on qualified interfaces.
1899 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001900 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001901 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001902 // Check the use of this declaration
1903 if (DiagnoseUseOfDecl(PD, MemberLoc))
1904 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001905
Steve Naroff774e4152009-01-21 00:14:39 +00001906 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001907 MemberLoc, BaseExpr));
1908 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001909 // Also must look for a getter name which uses property syntax.
1910 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1911 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001912 // Check the use of this method.
1913 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1914 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001915
1916 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001917 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001918 }
1919 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001920
1921 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1922 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001923 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001924 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001925 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001926 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1927 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001928 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001929 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00001930 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001931 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001932
1933 return ExprError(Diag(MemberLoc,
1934 diag::err_typecheck_member_reference_struct_union)
1935 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001936}
1937
Douglas Gregor3257fb52008-12-22 05:46:06 +00001938/// ConvertArgumentsForCall - Converts the arguments specified in
1939/// Args/NumArgs to the parameter types of the function FDecl with
1940/// function prototype Proto. Call is the call expression itself, and
1941/// Fn is the function expression. For a C++ member function, this
1942/// routine does not attempt to convert the object argument. Returns
1943/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00001944bool
1945Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001946 FunctionDecl *FDecl,
1947 const FunctionTypeProto *Proto,
1948 Expr **Args, unsigned NumArgs,
1949 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00001950 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00001951 // assignment, to the types of the corresponding parameter, ...
1952 unsigned NumArgsInProto = Proto->getNumArgs();
1953 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001954 bool Invalid = false;
1955
Douglas Gregor3257fb52008-12-22 05:46:06 +00001956 // If too few arguments are available (and we don't have default
1957 // arguments for the remaining parameters), don't make the call.
1958 if (NumArgs < NumArgsInProto) {
1959 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1960 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1961 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1962 // Use default arguments for missing arguments
1963 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001964 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001965 }
1966
1967 // If too many are passed and not variadic, error on the extras and drop
1968 // them.
1969 if (NumArgs > NumArgsInProto) {
1970 if (!Proto->isVariadic()) {
1971 Diag(Args[NumArgsInProto]->getLocStart(),
1972 diag::err_typecheck_call_too_many_args)
1973 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1974 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1975 Args[NumArgs-1]->getLocEnd());
1976 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001977 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001978 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001979 }
1980 NumArgsToCheck = NumArgsInProto;
1981 }
Mike Stump9afab102009-02-19 03:04:26 +00001982
Douglas Gregor3257fb52008-12-22 05:46:06 +00001983 // Continue to check argument types (even if we have too few/many args).
1984 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1985 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00001986
Douglas Gregor3257fb52008-12-22 05:46:06 +00001987 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001988 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001989 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001990
1991 // Pass the argument.
1992 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1993 return true;
Mike Stump9afab102009-02-19 03:04:26 +00001994 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001995 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001996 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001997 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00001998
Douglas Gregor3257fb52008-12-22 05:46:06 +00001999 Call->setArg(i, Arg);
2000 }
Mike Stump9afab102009-02-19 03:04:26 +00002001
Douglas Gregor3257fb52008-12-22 05:46:06 +00002002 // If this is a variadic call, handle args passed through "...".
2003 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002004 VariadicCallType CallType = VariadicFunction;
2005 if (Fn->getType()->isBlockPointerType())
2006 CallType = VariadicBlock; // Block
2007 else if (isa<MemberExpr>(Fn))
2008 CallType = VariadicMethod;
2009
Douglas Gregor3257fb52008-12-22 05:46:06 +00002010 // Promote the arguments (C99 6.5.2.2p7).
2011 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2012 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002013 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002014 Call->setArg(i, Arg);
2015 }
2016 }
2017
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002018 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002019}
2020
Steve Naroff87d58b42007-09-16 03:34:24 +00002021/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002022/// This provides the location of the left/right parens and a list of comma
2023/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002024Action::OwningExprResult
2025Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2026 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002027 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002028 unsigned NumArgs = args.size();
2029 Expr *Fn = static_cast<Expr *>(fn.release());
2030 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002031 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002032 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002033 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002034
Douglas Gregor3257fb52008-12-22 05:46:06 +00002035 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002036 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002037 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002038 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2039 bool Dependent = false;
2040 if (Fn->isTypeDependent())
2041 Dependent = true;
2042 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2043 Dependent = true;
2044
2045 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002046 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002047 Context.DependentTy, RParenLoc));
2048
2049 // Determine whether this is a call to an object (C++ [over.call.object]).
2050 if (Fn->getType()->isRecordType())
2051 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2052 CommaLocs, RParenLoc));
2053
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002054 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002055 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2056 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2057 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002058 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2059 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002060 }
2061
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002062 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002063 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002064 Expr *FnExpr = Fn;
2065 bool ADL = true;
2066 while (true) {
2067 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2068 FnExpr = IcExpr->getSubExpr();
2069 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002070 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002071 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002072 ADL = false;
2073 FnExpr = PExpr->getSubExpr();
2074 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002075 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002076 == UnaryOperator::AddrOf) {
2077 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002078 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2079 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2080 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2081 break;
Mike Stump9afab102009-02-19 03:04:26 +00002082 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002083 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2084 UnqualifiedName = DepName->getName();
2085 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002086 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002087 // Any kind of name that does not refer to a declaration (or
2088 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2089 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002090 break;
2091 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002092 }
Mike Stump9afab102009-02-19 03:04:26 +00002093
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002094 OverloadedFunctionDecl *Ovl = 0;
2095 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002096 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002097 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2098 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002099
Douglas Gregorfcb19192009-02-11 23:02:49 +00002100 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002101 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002102 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002103 ADL = false;
2104
Douglas Gregorfcb19192009-02-11 23:02:49 +00002105 // We don't perform ADL in C.
2106 if (!getLangOptions().CPlusPlus)
2107 ADL = false;
2108
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002109 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002110 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2111 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002112 NumArgs, CommaLocs, RParenLoc, ADL);
2113 if (!FDecl)
2114 return ExprError();
2115
2116 // Update Fn to refer to the actual function selected.
2117 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002118 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002119 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stump9afab102009-02-19 03:04:26 +00002120 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2121 QDRExpr->getLocation(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002122 false, false,
2123 QDRExpr->getSourceRange().getBegin());
2124 else
Mike Stump9afab102009-02-19 03:04:26 +00002125 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002126 Fn->getSourceRange().getBegin());
2127 Fn->Destroy(Context);
2128 Fn = NewFn;
2129 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002130 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002131
2132 // Promote the function operand.
2133 UsualUnaryConversions(Fn);
2134
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002135 // Make the call expr early, before semantic checks. This guarantees cleanup
2136 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002137 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2138 Args, NumArgs,
2139 Context.BoolTy,
2140 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002141
Steve Naroffd6163f32008-09-05 22:11:13 +00002142 const FunctionType *FuncT;
2143 if (!Fn->getType()->isBlockPointerType()) {
2144 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2145 // have type pointer to function".
2146 const PointerType *PT = Fn->getType()->getAsPointerType();
2147 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002148 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2149 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002150 FuncT = PT->getPointeeType()->getAsFunctionType();
2151 } else { // This is a block call.
2152 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2153 getAsFunctionType();
2154 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002155 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002156 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2157 << Fn->getType() << Fn->getSourceRange());
2158
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002159 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002160 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002161
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002162 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002163 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002164 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002165 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002166 } else {
2167 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002168
Steve Naroffdb65e052007-08-28 23:30:39 +00002169 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002170 for (unsigned i = 0; i != NumArgs; i++) {
2171 Expr *Arg = Args[i];
2172 DefaultArgumentPromotion(Arg);
2173 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002174 }
Chris Lattner4b009652007-07-25 00:24:17 +00002175 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002176
Douglas Gregor3257fb52008-12-22 05:46:06 +00002177 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2178 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002179 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2180 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002181
Chris Lattner2e64c072007-08-10 20:18:51 +00002182 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002183 if (FDecl)
2184 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002185
Sebastian Redl8b769972009-01-19 00:08:26 +00002186 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002187}
2188
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002189Action::OwningExprResult
2190Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2191 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002192 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002193 QualType literalType = QualType::getFromOpaquePtr(Ty);
2194 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002195 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002196 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002197
Eli Friedman8c2173d2008-05-20 05:22:08 +00002198 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002199 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002200 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2201 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002202 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2203 diag::err_typecheck_decl_incomplete_type,
2204 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002205 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002206
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002207 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002208 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002209 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002210
Chris Lattnere5cb5862008-12-04 23:50:19 +00002211 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002212 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002213 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002214 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002215 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002216 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002217 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002218 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002219}
2220
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002221Action::OwningExprResult
2222Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2223 InitListDesignations &Designators,
2224 SourceLocation RBraceLoc) {
2225 unsigned NumInit = initlist.size();
2226 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002227
Steve Naroff0acc9c92007-09-15 18:49:24 +00002228 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002229 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002230
Mike Stump9afab102009-02-19 03:04:26 +00002231 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002232 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002233 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002234 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002235}
2236
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002237/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002238bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002239 UsualUnaryConversions(castExpr);
2240
2241 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2242 // type needs to be scalar.
2243 if (castType->isVoidType()) {
2244 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002245 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2246 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002247 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002248 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2249 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2250 (castType->isStructureType() || castType->isUnionType())) {
2251 // GCC struct/union extension: allow cast to self.
2252 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2253 << castType << castExpr->getSourceRange();
2254 } else if (castType->isUnionType()) {
2255 // GCC cast to union extension
2256 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2257 RecordDecl::field_iterator Field, FieldEnd;
2258 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2259 Field != FieldEnd; ++Field) {
2260 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2261 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2262 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2263 << castExpr->getSourceRange();
2264 break;
2265 }
2266 }
2267 if (Field == FieldEnd)
2268 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2269 << castExpr->getType() << castExpr->getSourceRange();
2270 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002271 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002272 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002273 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002274 }
Mike Stump9afab102009-02-19 03:04:26 +00002275 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002276 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002277 return Diag(castExpr->getLocStart(),
2278 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002279 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002280 } else if (castExpr->getType()->isVectorType()) {
2281 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2282 return true;
2283 } else if (castType->isVectorType()) {
2284 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2285 return true;
2286 }
2287 return false;
2288}
2289
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002290bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002291 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002292
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002293 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002294 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002295 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002296 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002297 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002298 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002299 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002300 } else
2301 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002302 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002303 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002304
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002305 return false;
2306}
2307
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002308Action::OwningExprResult
2309Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2310 SourceLocation RParenLoc, ExprArg Op) {
2311 assert((Ty != 0) && (Op.get() != 0) &&
2312 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002313
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002314 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002315 QualType castType = QualType::getFromOpaquePtr(Ty);
2316
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002317 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002318 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002319 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002320 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002321}
2322
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002323/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2324/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002325/// C99 6.5.15
2326QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2327 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002328 UsualUnaryConversions(Cond);
2329 UsualUnaryConversions(LHS);
2330 UsualUnaryConversions(RHS);
2331 QualType CondTy = Cond->getType();
2332 QualType LHSTy = LHS->getType();
2333 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002334
2335 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002336 if (!Cond->isTypeDependent()) {
2337 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2338 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2339 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002340 return QualType();
2341 }
Chris Lattner4b009652007-07-25 00:24:17 +00002342 }
Mike Stump9afab102009-02-19 03:04:26 +00002343
Chris Lattner992ae932008-01-06 22:42:25 +00002344 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002345 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002346 return Context.DependentTy;
2347
Chris Lattner992ae932008-01-06 22:42:25 +00002348 // If both operands have arithmetic type, do the usual arithmetic conversions
2349 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002350 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2351 UsualArithmeticConversions(LHS, RHS);
2352 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002353 }
Mike Stump9afab102009-02-19 03:04:26 +00002354
Chris Lattner992ae932008-01-06 22:42:25 +00002355 // If both operands are the same structure or union type, the result is that
2356 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002357 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2358 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002359 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002360 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002361 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002362 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002363 }
Mike Stump9afab102009-02-19 03:04:26 +00002364
Chris Lattner992ae932008-01-06 22:42:25 +00002365 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002366 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002367 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2368 if (!LHSTy->isVoidType())
2369 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2370 << RHS->getSourceRange();
2371 if (!RHSTy->isVoidType())
2372 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2373 << LHS->getSourceRange();
2374 ImpCastExprToType(LHS, Context.VoidTy);
2375 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002376 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002377 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002378 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2379 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002380 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2381 Context.isObjCObjectPointerType(LHSTy)) &&
2382 RHS->isNullPointerConstant(Context)) {
2383 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2384 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002385 }
Chris Lattnere2897262009-02-18 04:28:32 +00002386 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2387 Context.isObjCObjectPointerType(RHSTy)) &&
2388 LHS->isNullPointerConstant(Context)) {
2389 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2390 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002391 }
Mike Stump9afab102009-02-19 03:04:26 +00002392
Chris Lattner0ac51632008-01-06 22:50:31 +00002393 // Handle the case where both operands are pointers before we handle null
2394 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002395 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2396 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002397 // get the "pointed to" types
2398 QualType lhptee = LHSPT->getPointeeType();
2399 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002400
Chris Lattner71225142007-07-31 21:27:01 +00002401 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2402 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002403 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002404 // Figure out necessary qualifiers (C99 6.5.15p6)
2405 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002406 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002407 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2408 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002409 return destType;
2410 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002411 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002412 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002413 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002414 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2415 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002416 return destType;
2417 }
Chris Lattner4b009652007-07-25 00:24:17 +00002418
Chris Lattner9c039b52009-02-18 04:38:20 +00002419 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002420 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002421 return LHSTy;
2422 }
Mike Stump9afab102009-02-19 03:04:26 +00002423
Chris Lattnere2897262009-02-18 04:28:32 +00002424 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002425
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002426 // If either type is an Objective-C object type then check
2427 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002428 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002429 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002430 // If both operands are interfaces and either operand can be
2431 // assigned to the other, use that type as the composite
2432 // type. This allows
2433 // xxx ? (A*) a : (B*) b
2434 // where B is a subclass of A.
2435 //
2436 // Additionally, as for assignment, if either type is 'id'
2437 // allow silent coercion. Finally, if the types are
2438 // incompatible then make sure to use 'id' as the composite
2439 // type so the result is acceptable for sending messages to.
2440
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002441 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002442 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002443 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2444 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2445 if (LHSIface && RHSIface &&
2446 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002447 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002448 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002449 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002450 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002451 } else if (Context.isObjCIdStructType(lhptee) ||
2452 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002453 compositeType = Context.getObjCIdType();
2454 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002455 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002456 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002457 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002458 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002459 ImpCastExprToType(LHS, incompatTy);
2460 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002461 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002462 }
Mike Stump9afab102009-02-19 03:04:26 +00002463 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002464 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002465 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2466 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002467 // In this situation, we assume void* type. No especially good
2468 // reason, but this is what gcc does, and we do have to pick
2469 // to get a consistent AST.
2470 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002471 ImpCastExprToType(LHS, incompatTy);
2472 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002473 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002474 }
2475 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002476 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2477 // differently qualified versions of compatible types, the result type is
2478 // a pointer to an appropriately qualified version of the *composite*
2479 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002480 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002481 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002482 ImpCastExprToType(LHS, compositeType);
2483 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002484 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002485 }
Chris Lattner4b009652007-07-25 00:24:17 +00002486 }
Mike Stump9afab102009-02-19 03:04:26 +00002487
Chris Lattner9c039b52009-02-18 04:38:20 +00002488 // Selection between block pointer types is ok as long as they are the same.
2489 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2490 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2491 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002492
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002493 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2494 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002495 // id with statically typed objects).
2496 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002497 // GCC allows qualified id and any Objective-C type to devolve to
2498 // id. Currently localizing to here until clear this should be
2499 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002500 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002501 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002502 Context.isObjCObjectPointerType(RHSTy)) ||
2503 (RHSTy->isObjCQualifiedIdType() &&
2504 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002505 // FIXME: This is not the correct composite type. This only
2506 // happens to work because id can more or less be used anywhere,
2507 // however this may change the type of method sends.
2508 // FIXME: gcc adds some type-checking of the arguments and emits
2509 // (confusing) incompatible comparison warnings in some
2510 // cases. Investigate.
2511 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002512 ImpCastExprToType(LHS, compositeType);
2513 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002514 return compositeType;
2515 }
2516 }
2517
Chris Lattner992ae932008-01-06 22:42:25 +00002518 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002519 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2520 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002521 return QualType();
2522}
2523
Steve Naroff87d58b42007-09-16 03:34:24 +00002524/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002525/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002526Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2527 SourceLocation ColonLoc,
2528 ExprArg Cond, ExprArg LHS,
2529 ExprArg RHS) {
2530 Expr *CondExpr = (Expr *) Cond.get();
2531 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002532
2533 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2534 // was the condition.
2535 bool isLHSNull = LHSExpr == 0;
2536 if (isLHSNull)
2537 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002538
2539 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002540 RHSExpr, QuestionLoc);
2541 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002542 return ExprError();
2543
2544 Cond.release();
2545 LHS.release();
2546 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002547 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002548 isLHSNull ? 0 : LHSExpr,
2549 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002550}
2551
Chris Lattner4b009652007-07-25 00:24:17 +00002552
2553// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002554// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002555// routine is it effectively iqnores the qualifiers on the top level pointee.
2556// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2557// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002558Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002559Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2560 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002561
Chris Lattner4b009652007-07-25 00:24:17 +00002562 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002563 lhptee = lhsType->getAsPointerType()->getPointeeType();
2564 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002565
Chris Lattner4b009652007-07-25 00:24:17 +00002566 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002567 lhptee = Context.getCanonicalType(lhptee);
2568 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002569
Chris Lattner005ed752008-01-04 18:04:52 +00002570 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002571
2572 // C99 6.5.16.1p1: This following citation is common to constraints
2573 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2574 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002575 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002576 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002577 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002578
Mike Stump9afab102009-02-19 03:04:26 +00002579 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2580 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002581 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002582 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002583 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002584 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002585
Chris Lattner4ca3d772008-01-03 22:56:36 +00002586 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002587 assert(rhptee->isFunctionType());
2588 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002589 }
Mike Stump9afab102009-02-19 03:04:26 +00002590
Chris Lattner4ca3d772008-01-03 22:56:36 +00002591 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002592 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002593 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002594
2595 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002596 assert(lhptee->isFunctionType());
2597 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002598 }
Mike Stump9afab102009-02-19 03:04:26 +00002599 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002600 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002601 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002602 rhptee.getUnqualifiedType()))
2603 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002604 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002605}
2606
Steve Naroff3454b6c2008-09-04 15:10:53 +00002607/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2608/// block pointer types are compatible or whether a block and normal pointer
2609/// are compatible. It is more restrict than comparing two function pointer
2610// types.
Mike Stump9afab102009-02-19 03:04:26 +00002611Sema::AssignConvertType
2612Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002613 QualType rhsType) {
2614 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002615
Steve Naroff3454b6c2008-09-04 15:10:53 +00002616 // get the "pointed to" type (ignoring qualifiers at the top level)
2617 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002618 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2619
Steve Naroff3454b6c2008-09-04 15:10:53 +00002620 // make sure we operate on the canonical type
2621 lhptee = Context.getCanonicalType(lhptee);
2622 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002623
Steve Naroff3454b6c2008-09-04 15:10:53 +00002624 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002625
Steve Naroff3454b6c2008-09-04 15:10:53 +00002626 // For blocks we enforce that qualifiers are identical.
2627 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2628 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002629
Steve Naroff3454b6c2008-09-04 15:10:53 +00002630 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002631 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002632 return ConvTy;
2633}
2634
Mike Stump9afab102009-02-19 03:04:26 +00002635/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2636/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002637/// pointers. Here are some objectionable examples that GCC considers warnings:
2638///
2639/// int a, *pint;
2640/// short *pshort;
2641/// struct foo *pfoo;
2642///
2643/// pint = pshort; // warning: assignment from incompatible pointer type
2644/// a = pint; // warning: assignment makes integer from pointer without a cast
2645/// pint = a; // warning: assignment makes pointer from integer without a cast
2646/// pint = pfoo; // warning: assignment from incompatible pointer type
2647///
2648/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002649/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002650///
Chris Lattner005ed752008-01-04 18:04:52 +00002651Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002652Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002653 // Get canonical types. We're not formatting these types, just comparing
2654 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002655 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2656 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002657
2658 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002659 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002660
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002661 // If the left-hand side is a reference type, then we are in a
2662 // (rare!) case where we've allowed the use of references in C,
2663 // e.g., as a parameter type in a built-in function. In this case,
2664 // just make sure that the type referenced is compatible with the
2665 // right-hand side type. The caller is responsible for adjusting
2666 // lhsType so that the resulting expression does not have reference
2667 // type.
2668 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2669 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002670 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002671 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002672 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002673
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002674 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2675 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002676 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002677 // Relax integer conversions like we do for pointers below.
2678 if (rhsType->isIntegerType())
2679 return IntToPointer;
2680 if (lhsType->isIntegerType())
2681 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002682 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002683 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002684
Nate Begemanc5f0f652008-07-14 18:02:46 +00002685 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002686 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002687 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2688 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002689 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002690
Nate Begemanc5f0f652008-07-14 18:02:46 +00002691 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002692 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002693 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002694 if (getLangOptions().LaxVectorConversions &&
2695 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002696 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002697 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002698 }
2699 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002700 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002701
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002702 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002703 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002704
Chris Lattner390564e2008-04-07 06:49:41 +00002705 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002706 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002707 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002708
Chris Lattner390564e2008-04-07 06:49:41 +00002709 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002710 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002711
Steve Naroffa982c712008-09-29 18:10:17 +00002712 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002713 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002714 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002715
2716 // Treat block pointers as objects.
2717 if (getLangOptions().ObjC1 &&
2718 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2719 return Compatible;
2720 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002721 return Incompatible;
2722 }
2723
2724 if (isa<BlockPointerType>(lhsType)) {
2725 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002726 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002727
Steve Naroffa982c712008-09-29 18:10:17 +00002728 // Treat block pointers as objects.
2729 if (getLangOptions().ObjC1 &&
2730 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2731 return Compatible;
2732
Steve Naroff3454b6c2008-09-04 15:10:53 +00002733 if (rhsType->isBlockPointerType())
2734 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002735
Steve Naroff3454b6c2008-09-04 15:10:53 +00002736 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2737 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002738 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002739 }
Chris Lattner1853da22008-01-04 23:18:45 +00002740 return Incompatible;
2741 }
2742
Chris Lattner390564e2008-04-07 06:49:41 +00002743 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002744 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002745 if (lhsType == Context.BoolTy)
2746 return Compatible;
2747
2748 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002749 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002750
Mike Stump9afab102009-02-19 03:04:26 +00002751 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002752 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002753
2754 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002755 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002756 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002757 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002758 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002759
Chris Lattner1853da22008-01-04 23:18:45 +00002760 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002761 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002762 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002763 }
2764 return Incompatible;
2765}
2766
Chris Lattner005ed752008-01-04 18:04:52 +00002767Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002768Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002769 if (getLangOptions().CPlusPlus) {
2770 if (!lhsType->isRecordType()) {
2771 // C++ 5.17p3: If the left operand is not of class type, the
2772 // expression is implicitly converted (C++ 4) to the
2773 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002774 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2775 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002776 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002777 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002778 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002779 }
2780
2781 // FIXME: Currently, we fall through and treat C++ classes like C
2782 // structures.
2783 }
2784
Steve Naroffcdee22d2007-11-27 17:58:44 +00002785 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2786 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002787 if ((lhsType->isPointerType() ||
2788 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002789 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002790 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002791 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002792 return Compatible;
2793 }
Mike Stump9afab102009-02-19 03:04:26 +00002794
Chris Lattner5f505bf2007-10-16 02:55:40 +00002795 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002796 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002797 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002798 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002799 //
Mike Stump9afab102009-02-19 03:04:26 +00002800 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002801 if (!lhsType->isReferenceType())
2802 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002803
Chris Lattner005ed752008-01-04 18:04:52 +00002804 Sema::AssignConvertType result =
2805 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002806
Steve Naroff0f32f432007-08-24 22:33:52 +00002807 // C99 6.5.16.1p2: The value of the right operand is converted to the
2808 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002809 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2810 // so that we can use references in built-in functions even in C.
2811 // The getNonReferenceType() call makes sure that the resulting expression
2812 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002813 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002814 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002815 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002816}
2817
Chris Lattner005ed752008-01-04 18:04:52 +00002818Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002819Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2820 return CheckAssignmentConstraints(lhsType, rhsType);
2821}
2822
Chris Lattner1eafdea2008-11-18 01:30:42 +00002823QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002824 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002825 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002826 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002827 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002828}
2829
Mike Stump9afab102009-02-19 03:04:26 +00002830inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002831 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002832 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002833 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002834 QualType lhsType =
2835 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2836 QualType rhsType =
2837 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002838
Nate Begemanc5f0f652008-07-14 18:02:46 +00002839 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002840 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002841 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002842
Nate Begemanc5f0f652008-07-14 18:02:46 +00002843 // Handle the case of a vector & extvector type of the same size and element
2844 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002845 if (getLangOptions().LaxVectorConversions) {
2846 // FIXME: Should we warn here?
2847 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002848 if (const VectorType *RV = rhsType->getAsVectorType())
2849 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002850 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002851 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002852 }
2853 }
2854 }
Mike Stump9afab102009-02-19 03:04:26 +00002855
Nate Begemanc5f0f652008-07-14 18:02:46 +00002856 // If the lhs is an extended vector and the rhs is a scalar of the same type
2857 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002858 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002859 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002860
2861 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002862 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2863 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002864 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002865 return lhsType;
2866 }
2867 }
2868
Nate Begemanc5f0f652008-07-14 18:02:46 +00002869 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002870 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002871 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002872 QualType eltType = V->getElementType();
2873
Mike Stump9afab102009-02-19 03:04:26 +00002874 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002875 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2876 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002877 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002878 return rhsType;
2879 }
2880 }
2881
Chris Lattner4b009652007-07-25 00:24:17 +00002882 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002883 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002884 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002885 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002886 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002887}
2888
Chris Lattner4b009652007-07-25 00:24:17 +00002889inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002890 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002891{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002892 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002893 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002894
Steve Naroff8f708362007-08-24 19:07:16 +00002895 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002896
Chris Lattner4b009652007-07-25 00:24:17 +00002897 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002898 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002899 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002900}
2901
2902inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002903 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002904{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002905 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2906 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2907 return CheckVectorOperands(Loc, lex, rex);
2908 return InvalidOperands(Loc, lex, rex);
2909 }
Chris Lattner4b009652007-07-25 00:24:17 +00002910
Steve Naroff8f708362007-08-24 19:07:16 +00002911 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002912
Chris Lattner4b009652007-07-25 00:24:17 +00002913 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002914 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002915 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002916}
2917
2918inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00002919 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002920{
2921 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002922 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002923
Steve Naroff8f708362007-08-24 19:07:16 +00002924 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002925
Chris Lattner4b009652007-07-25 00:24:17 +00002926 // handle the common case first (both operands are arithmetic).
2927 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002928 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002929
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002930 // Put any potential pointer into PExp
2931 Expr* PExp = lex, *IExp = rex;
2932 if (IExp->getType()->isPointerType())
2933 std::swap(PExp, IExp);
2934
2935 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2936 if (IExp->getType()->isIntegerType()) {
2937 // Check for arithmetic on pointers to incomplete types
2938 if (!PTy->getPointeeType()->isObjectType()) {
2939 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002940 if (getLangOptions().CPlusPlus) {
2941 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2942 << lex->getSourceRange() << rex->getSourceRange();
2943 return QualType();
2944 }
2945
2946 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002947 Diag(Loc, diag::ext_gnu_void_ptr)
2948 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002949 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002950 if (getLangOptions().CPlusPlus) {
2951 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2952 << lex->getType() << lex->getSourceRange();
2953 return QualType();
2954 }
2955
2956 // GNU extension: arithmetic on pointer to function
2957 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002958 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002959 } else {
Mike Stump9afab102009-02-19 03:04:26 +00002960 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002961 diag::err_typecheck_arithmetic_incomplete_type,
2962 lex->getSourceRange(), SourceRange(),
2963 lex->getType());
2964 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002965 }
2966 }
2967 return PExp->getType();
2968 }
2969 }
2970
Chris Lattner1eafdea2008-11-18 01:30:42 +00002971 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002972}
2973
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002974// C99 6.5.6
2975QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002976 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002977 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002978 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002979
Steve Naroff8f708362007-08-24 19:07:16 +00002980 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002981
Chris Lattnerf6da2912007-12-09 21:53:25 +00002982 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00002983
Chris Lattnerf6da2912007-12-09 21:53:25 +00002984 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002985 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002986 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00002987
Chris Lattnerf6da2912007-12-09 21:53:25 +00002988 // Either ptr - int or ptr - ptr.
2989 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002990 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002991
Chris Lattnerf6da2912007-12-09 21:53:25 +00002992 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002993 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002994 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002995 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002996 Diag(Loc, diag::ext_gnu_void_ptr)
2997 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002998 } else if (lpointee->isFunctionType()) {
2999 if (getLangOptions().CPlusPlus) {
3000 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3001 << lex->getType() << lex->getSourceRange();
3002 return QualType();
3003 }
3004
3005 // GNU extension: arithmetic on pointer to function
3006 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3007 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003008 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003009 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003010 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003011 return QualType();
3012 }
3013 }
3014
3015 // The result type of a pointer-int computation is the pointer type.
3016 if (rex->getType()->isIntegerType())
3017 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003018
Chris Lattnerf6da2912007-12-09 21:53:25 +00003019 // Handle pointer-pointer subtractions.
3020 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003021 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003022
Chris Lattnerf6da2912007-12-09 21:53:25 +00003023 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00003024 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003025 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003026 if (rpointee->isVoidType()) {
3027 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00003028 Diag(Loc, diag::ext_gnu_void_ptr)
3029 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00003030 } else if (rpointee->isFunctionType()) {
3031 if (getLangOptions().CPlusPlus) {
3032 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3033 << rex->getType() << rex->getSourceRange();
3034 return QualType();
3035 }
Mike Stump9afab102009-02-19 03:04:26 +00003036
Douglas Gregorf93eda12009-01-23 19:03:35 +00003037 // GNU extension: arithmetic on pointer to function
3038 if (!lpointee->isFunctionType())
3039 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3040 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003041 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003042 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003043 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003044 return QualType();
3045 }
3046 }
Mike Stump9afab102009-02-19 03:04:26 +00003047
Chris Lattnerf6da2912007-12-09 21:53:25 +00003048 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003049 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003050 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003051 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003052 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003053 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003054 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003055 return QualType();
3056 }
Mike Stump9afab102009-02-19 03:04:26 +00003057
Chris Lattnerf6da2912007-12-09 21:53:25 +00003058 return Context.getPointerDiffType();
3059 }
3060 }
Mike Stump9afab102009-02-19 03:04:26 +00003061
Chris Lattner1eafdea2008-11-18 01:30:42 +00003062 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003063}
3064
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003065// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003066QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003067 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003068 // C99 6.5.7p2: Each of the operands shall have integer type.
3069 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003070 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003071
Chris Lattner2c8bff72007-12-12 05:47:28 +00003072 // Shifts don't perform usual arithmetic conversions, they just do integer
3073 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003074 if (!isCompAssign)
3075 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003076 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003077
Chris Lattner2c8bff72007-12-12 05:47:28 +00003078 // "The type of the result is that of the promoted left operand."
3079 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003080}
3081
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003082// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003083QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003084 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003085 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003086 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003087
Chris Lattner254f3bc2007-08-26 01:18:55 +00003088 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003089 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3090 UsualArithmeticConversions(lex, rex);
3091 else {
3092 UsualUnaryConversions(lex);
3093 UsualUnaryConversions(rex);
3094 }
Chris Lattner4b009652007-07-25 00:24:17 +00003095 QualType lType = lex->getType();
3096 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003097
Ted Kremenek486509e2007-10-29 17:13:39 +00003098 // For non-floating point types, check for self-comparisons of the form
3099 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3100 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003101 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003102 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3103 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003104 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003105 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003106 }
Mike Stump9afab102009-02-19 03:04:26 +00003107
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003108 // The result of comparisons is 'bool' in C++, 'int' in C.
3109 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3110
Chris Lattner254f3bc2007-08-26 01:18:55 +00003111 if (isRelational) {
3112 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003113 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003114 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003115 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003116 if (lType->isFloatingType()) {
3117 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003118 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003119 }
Mike Stump9afab102009-02-19 03:04:26 +00003120
Chris Lattner254f3bc2007-08-26 01:18:55 +00003121 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003122 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003123 }
Mike Stump9afab102009-02-19 03:04:26 +00003124
Chris Lattner22be8422007-08-26 01:10:14 +00003125 bool LHSIsNull = lex->isNullPointerConstant(Context);
3126 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003127
Chris Lattner254f3bc2007-08-26 01:18:55 +00003128 // All of the following pointer related warnings are GCC extensions, except
3129 // when handling null pointer constants. One day, we can consider making them
3130 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003131 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003132 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003133 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003134 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003135 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003136
Steve Naroff3b435622007-11-13 14:57:38 +00003137 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003138 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3139 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003140 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003141 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003142 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003143 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003144 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003145 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003146 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003147 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003148 // Handle block pointer types.
3149 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3150 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3151 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003152
Steve Naroff3454b6c2008-09-04 15:10:53 +00003153 if (!LHSIsNull && !RHSIsNull &&
3154 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003155 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003156 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003157 }
3158 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003159 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003160 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003161 // Allow block pointers to be compared with null pointer constants.
3162 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3163 (lType->isPointerType() && rType->isBlockPointerType())) {
3164 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003165 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003166 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003167 }
3168 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003169 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003170 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003171
Steve Naroff936c4362008-06-03 14:04:54 +00003172 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003173 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003174 const PointerType *LPT = lType->getAsPointerType();
3175 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003176 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003177 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003178 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003179 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003180
Steve Naroff030fcda2008-11-17 19:49:16 +00003181 if (!LPtrToVoid && !RPtrToVoid &&
3182 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003183 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003184 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003185 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003186 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003187 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003188 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003189 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003190 }
Steve Naroff936c4362008-06-03 14:04:54 +00003191 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3192 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003193 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003194 } else {
3195 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003196 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003197 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003198 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003199 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003200 }
Steve Naroff936c4362008-06-03 14:04:54 +00003201 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003202 }
Mike Stump9afab102009-02-19 03:04:26 +00003203 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003204 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003205 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003206 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003207 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003208 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003209 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003210 }
Mike Stump9afab102009-02-19 03:04:26 +00003211 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003212 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003213 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003214 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003215 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003216 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003217 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003218 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003219 // Handle block pointers.
3220 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3221 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003222 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003223 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003224 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003225 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003226 }
3227 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3228 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003229 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003230 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003231 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003232 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003233 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003234 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003235}
3236
Nate Begemanc5f0f652008-07-14 18:02:46 +00003237/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003238/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003239/// like a scalar comparison, a vector comparison produces a vector of integer
3240/// types.
3241QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003242 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003243 bool isRelational) {
3244 // Check to make sure we're operating on vectors of the same type and width,
3245 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003246 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003247 if (vType.isNull())
3248 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003249
Nate Begemanc5f0f652008-07-14 18:02:46 +00003250 QualType lType = lex->getType();
3251 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003252
Nate Begemanc5f0f652008-07-14 18:02:46 +00003253 // For non-floating point types, check for self-comparisons of the form
3254 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3255 // often indicate logic errors in the program.
3256 if (!lType->isFloatingType()) {
3257 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3258 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3259 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003260 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003261 }
Mike Stump9afab102009-02-19 03:04:26 +00003262
Nate Begemanc5f0f652008-07-14 18:02:46 +00003263 // Check for comparisons of floating point operands using != and ==.
3264 if (!isRelational && lType->isFloatingType()) {
3265 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003266 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003267 }
Mike Stump9afab102009-02-19 03:04:26 +00003268
Nate Begemanc5f0f652008-07-14 18:02:46 +00003269 // Return the type for the comparison, which is the same as vector type for
3270 // integer vectors, or an integer type of identical size and number of
3271 // elements for floating point vectors.
3272 if (lType->isIntegerType())
3273 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003274
Nate Begemanc5f0f652008-07-14 18:02:46 +00003275 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003276 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003277 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003278 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003279 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3280 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3281
Mike Stump9afab102009-02-19 03:04:26 +00003282 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003283 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003284 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3285}
3286
Chris Lattner4b009652007-07-25 00:24:17 +00003287inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003288 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003289{
3290 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003291 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003292
Steve Naroff8f708362007-08-24 19:07:16 +00003293 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003294
Chris Lattner4b009652007-07-25 00:24:17 +00003295 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003296 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003297 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003298}
3299
3300inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003301 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003302{
3303 UsualUnaryConversions(lex);
3304 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003305
Eli Friedmanbea3f842008-05-13 20:16:47 +00003306 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003307 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003308 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003309}
3310
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003311/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3312/// is a read-only property; return true if so. A readonly property expression
3313/// depends on various declarations and thus must be treated specially.
3314///
Mike Stump9afab102009-02-19 03:04:26 +00003315static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003316{
3317 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3318 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3319 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3320 QualType BaseType = PropExpr->getBase()->getType();
3321 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003322 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003323 PTy->getPointeeType()->getAsObjCInterfaceType())
3324 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3325 if (S.isPropertyReadonly(PDecl, IFace))
3326 return true;
3327 }
3328 }
3329 return false;
3330}
3331
Chris Lattner4c2642c2008-11-18 01:22:49 +00003332/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3333/// emit an error and return true. If so, return false.
3334static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003335 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3336 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3337 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003338 if (IsLV == Expr::MLV_Valid)
3339 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003340
Chris Lattner4c2642c2008-11-18 01:22:49 +00003341 unsigned Diag = 0;
3342 bool NeedType = false;
3343 switch (IsLV) { // C99 6.5.16p2
3344 default: assert(0 && "Unknown result from isModifiableLvalue!");
3345 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003346 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003347 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3348 NeedType = true;
3349 break;
Mike Stump9afab102009-02-19 03:04:26 +00003350 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003351 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3352 NeedType = true;
3353 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003354 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003355 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3356 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003357 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003358 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3359 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003360 case Expr::MLV_IncompleteType:
3361 case Expr::MLV_IncompleteVoidType:
Mike Stump9afab102009-02-19 03:04:26 +00003362 return S.DiagnoseIncompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003363 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3364 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003365 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003366 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3367 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003368 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003369 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3370 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003371 case Expr::MLV_ReadonlyProperty:
3372 Diag = diag::error_readonly_property_assignment;
3373 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003374 case Expr::MLV_NoSetterProperty:
3375 Diag = diag::error_nosetter_property_assignment;
3376 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003377 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003378
Chris Lattner4c2642c2008-11-18 01:22:49 +00003379 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003380 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003381 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003382 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003383 return true;
3384}
3385
3386
3387
3388// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003389QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3390 SourceLocation Loc,
3391 QualType CompoundType) {
3392 // Verify that LHS is a modifiable lvalue, and emit error if not.
3393 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003394 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003395
3396 QualType LHSType = LHS->getType();
3397 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003398
Chris Lattner005ed752008-01-04 18:04:52 +00003399 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003400 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003401 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003402 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003403 // Special case of NSObject attributes on c-style pointer types.
3404 if (ConvTy == IncompatiblePointer &&
3405 ((Context.isObjCNSObjectType(LHSType) &&
3406 Context.isObjCObjectPointerType(RHSType)) ||
3407 (Context.isObjCNSObjectType(RHSType) &&
3408 Context.isObjCObjectPointerType(LHSType))))
3409 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003410
Chris Lattner34c85082008-08-21 18:04:13 +00003411 // If the RHS is a unary plus or minus, check to see if they = and + are
3412 // right next to each other. If so, the user may have typo'd "x =+ 4"
3413 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003414 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003415 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3416 RHSCheck = ICE->getSubExpr();
3417 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3418 if ((UO->getOpcode() == UnaryOperator::Plus ||
3419 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003420 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003421 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003422 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003423 Diag(Loc, diag::warn_not_compound_assign)
3424 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3425 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003426 }
3427 } else {
3428 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003429 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003430 }
Chris Lattner005ed752008-01-04 18:04:52 +00003431
Chris Lattner1eafdea2008-11-18 01:30:42 +00003432 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3433 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003434 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003435
Chris Lattner4b009652007-07-25 00:24:17 +00003436 // C99 6.5.16p3: The type of an assignment expression is the type of the
3437 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003438 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003439 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3440 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003441 // C++ 5.17p1: the type of the assignment expression is that of its left
3442 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003443 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003444}
3445
Chris Lattner1eafdea2008-11-18 01:30:42 +00003446// C99 6.5.17
3447QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3448 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003449
Chris Lattner03c430f2008-07-25 20:54:07 +00003450 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003451 DefaultFunctionArrayConversion(RHS);
3452 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003453}
3454
3455/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3456/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003457QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3458 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003459 if (Op->isTypeDependent())
3460 return Context.DependentTy;
3461
Chris Lattnere65182c2008-11-21 07:05:48 +00003462 QualType ResType = Op->getType();
3463 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003464
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003465 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3466 // Decrement of bool is not allowed.
3467 if (!isInc) {
3468 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3469 return QualType();
3470 }
3471 // Increment of bool sets it to true, but is deprecated.
3472 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3473 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003474 // OK!
3475 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3476 // C99 6.5.2.4p2, 6.5.6p2
3477 if (PT->getPointeeType()->isObjectType()) {
3478 // Pointer to object is ok!
3479 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003480 if (getLangOptions().CPlusPlus) {
3481 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3482 << Op->getSourceRange();
3483 return QualType();
3484 }
3485
3486 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003487 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003488 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003489 if (getLangOptions().CPlusPlus) {
3490 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3491 << Op->getType() << Op->getSourceRange();
3492 return QualType();
3493 }
3494
3495 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003496 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003497 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003498 } else {
Mike Stump9afab102009-02-19 03:04:26 +00003499 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003500 diag::err_typecheck_arithmetic_incomplete_type,
3501 Op->getSourceRange(), SourceRange(),
3502 ResType);
3503 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003504 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003505 } else if (ResType->isComplexType()) {
3506 // C99 does not support ++/-- on complex types, we allow as an extension.
3507 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003508 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003509 } else {
3510 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003511 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003512 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003513 }
Mike Stump9afab102009-02-19 03:04:26 +00003514 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003515 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003516 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003517 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003518 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003519}
3520
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003521/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003522/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003523/// where the declaration is needed for type checking. We only need to
3524/// handle cases when the expression references a function designator
3525/// or is an lvalue. Here are some examples:
3526/// - &(x) => x
3527/// - &*****f => f for f a function designator.
3528/// - &s.xx => s
3529/// - &s.zz[1].yy -> s, if zz is an array
3530/// - *(x + 1) -> x, if x is an array
3531/// - &"123"[2] -> 0
3532/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003533static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003534 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003535 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003536 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003537 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003538 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003539 // Fields cannot be declared with a 'register' storage class.
3540 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003541 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003542 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003543 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003544 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003545 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003546
Douglas Gregord2baafd2008-10-21 16:13:35 +00003547 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003548 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003549 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003550 return 0;
3551 else
3552 return VD;
3553 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003554 case Stmt::UnaryOperatorClass: {
3555 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003556
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003557 switch(UO->getOpcode()) {
3558 case UnaryOperator::Deref: {
3559 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003560 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3561 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3562 if (!VD || VD->getType()->isPointerType())
3563 return 0;
3564 return VD;
3565 }
3566 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003567 }
3568 case UnaryOperator::Real:
3569 case UnaryOperator::Imag:
3570 case UnaryOperator::Extension:
3571 return getPrimaryDecl(UO->getSubExpr());
3572 default:
3573 return 0;
3574 }
3575 }
3576 case Stmt::BinaryOperatorClass: {
3577 BinaryOperator *BO = cast<BinaryOperator>(E);
3578
3579 // Handle cases involving pointer arithmetic. The result of an
3580 // Assign or AddAssign is not an lvalue so they can be ignored.
3581
3582 // (x + n) or (n + x) => x
3583 if (BO->getOpcode() == BinaryOperator::Add) {
3584 if (BO->getLHS()->getType()->isPointerType()) {
3585 return getPrimaryDecl(BO->getLHS());
3586 } else if (BO->getRHS()->getType()->isPointerType()) {
3587 return getPrimaryDecl(BO->getRHS());
3588 }
3589 }
3590
3591 return 0;
3592 }
Chris Lattner4b009652007-07-25 00:24:17 +00003593 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003594 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003595 case Stmt::ImplicitCastExprClass:
3596 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003597 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003598 default:
3599 return 0;
3600 }
3601}
3602
3603/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003604/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003605/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003606/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003607/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003608/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003609/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003610QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003611 if (op->isTypeDependent())
3612 return Context.DependentTy;
3613
Steve Naroff9c6c3592008-01-13 17:10:08 +00003614 if (getLangOptions().C99) {
3615 // Implement C99-only parts of addressof rules.
3616 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3617 if (uOp->getOpcode() == UnaryOperator::Deref)
3618 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3619 // (assuming the deref expression is valid).
3620 return uOp->getSubExpr()->getType();
3621 }
3622 // Technically, there should be a check for array subscript
3623 // expressions here, but the result of one is always an lvalue anyway.
3624 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003625 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003626 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003627
Chris Lattner4b009652007-07-25 00:24:17 +00003628 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003629 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3630 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003631 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3632 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003633 return QualType();
3634 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003635 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003636 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3637 if (Field->isBitField()) {
3638 Diag(OpLoc, diag::err_typecheck_address_of)
3639 << "bit-field" << op->getSourceRange();
3640 return QualType();
3641 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003642 }
3643 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003644 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3645 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003646 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003647 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003648 return QualType();
3649 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003650 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003651 // with the register storage-class specifier.
3652 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3653 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003654 Diag(OpLoc, diag::err_typecheck_address_of)
3655 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003656 return QualType();
3657 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003658 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003659 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003660 } else if (isa<FieldDecl>(dcl)) {
3661 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003662 // Could be a pointer to member, though, if there is an explicit
3663 // scope qualifier for the class.
3664 if (isa<QualifiedDeclRefExpr>(op)) {
3665 DeclContext *Ctx = dcl->getDeclContext();
3666 if (Ctx && Ctx->isRecord())
3667 return Context.getMemberPointerType(op->getType(),
3668 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3669 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003670 } else if (isa<FunctionDecl>(dcl)) {
3671 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003672 // As above.
3673 if (isa<QualifiedDeclRefExpr>(op)) {
3674 DeclContext *Ctx = dcl->getDeclContext();
3675 if (Ctx && Ctx->isRecord())
3676 return Context.getMemberPointerType(op->getType(),
3677 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3678 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003679 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003680 else
Chris Lattner4b009652007-07-25 00:24:17 +00003681 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003682 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003683
Chris Lattner4b009652007-07-25 00:24:17 +00003684 // If the operand has type "type", the result has type "pointer to type".
3685 return Context.getPointerType(op->getType());
3686}
3687
Chris Lattnerda5c0872008-11-23 09:13:29 +00003688QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003689 if (Op->isTypeDependent())
3690 return Context.DependentTy;
3691
Chris Lattnerda5c0872008-11-23 09:13:29 +00003692 UsualUnaryConversions(Op);
3693 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003694
Chris Lattnerda5c0872008-11-23 09:13:29 +00003695 // Note that per both C89 and C99, this is always legal, even if ptype is an
3696 // incomplete type or void. It would be possible to warn about dereferencing
3697 // a void pointer, but it's completely well-defined, and such a warning is
3698 // unlikely to catch any mistakes.
3699 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003700 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003701
Chris Lattner77d52da2008-11-20 06:06:08 +00003702 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003703 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003704 return QualType();
3705}
3706
3707static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3708 tok::TokenKind Kind) {
3709 BinaryOperator::Opcode Opc;
3710 switch (Kind) {
3711 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003712 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3713 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003714 case tok::star: Opc = BinaryOperator::Mul; break;
3715 case tok::slash: Opc = BinaryOperator::Div; break;
3716 case tok::percent: Opc = BinaryOperator::Rem; break;
3717 case tok::plus: Opc = BinaryOperator::Add; break;
3718 case tok::minus: Opc = BinaryOperator::Sub; break;
3719 case tok::lessless: Opc = BinaryOperator::Shl; break;
3720 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3721 case tok::lessequal: Opc = BinaryOperator::LE; break;
3722 case tok::less: Opc = BinaryOperator::LT; break;
3723 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3724 case tok::greater: Opc = BinaryOperator::GT; break;
3725 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3726 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3727 case tok::amp: Opc = BinaryOperator::And; break;
3728 case tok::caret: Opc = BinaryOperator::Xor; break;
3729 case tok::pipe: Opc = BinaryOperator::Or; break;
3730 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3731 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3732 case tok::equal: Opc = BinaryOperator::Assign; break;
3733 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3734 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3735 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3736 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3737 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3738 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3739 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3740 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3741 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3742 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3743 case tok::comma: Opc = BinaryOperator::Comma; break;
3744 }
3745 return Opc;
3746}
3747
3748static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3749 tok::TokenKind Kind) {
3750 UnaryOperator::Opcode Opc;
3751 switch (Kind) {
3752 default: assert(0 && "Unknown unary op!");
3753 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3754 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3755 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3756 case tok::star: Opc = UnaryOperator::Deref; break;
3757 case tok::plus: Opc = UnaryOperator::Plus; break;
3758 case tok::minus: Opc = UnaryOperator::Minus; break;
3759 case tok::tilde: Opc = UnaryOperator::Not; break;
3760 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003761 case tok::kw___real: Opc = UnaryOperator::Real; break;
3762 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3763 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3764 }
3765 return Opc;
3766}
3767
Douglas Gregord7f915e2008-11-06 23:29:22 +00003768/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3769/// operator @p Opc at location @c TokLoc. This routine only supports
3770/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003771Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3772 unsigned Op,
3773 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003774 QualType ResultTy; // Result type of the binary operator.
3775 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3776 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3777
3778 switch (Opc) {
3779 default:
3780 assert(0 && "Unknown binary expr!");
3781 case BinaryOperator::Assign:
3782 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3783 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003784 case BinaryOperator::PtrMemD:
3785 case BinaryOperator::PtrMemI:
3786 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3787 Opc == BinaryOperator::PtrMemI);
3788 break;
3789 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003790 case BinaryOperator::Div:
3791 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3792 break;
3793 case BinaryOperator::Rem:
3794 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3795 break;
3796 case BinaryOperator::Add:
3797 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3798 break;
3799 case BinaryOperator::Sub:
3800 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3801 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003802 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003803 case BinaryOperator::Shr:
3804 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3805 break;
3806 case BinaryOperator::LE:
3807 case BinaryOperator::LT:
3808 case BinaryOperator::GE:
3809 case BinaryOperator::GT:
3810 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3811 break;
3812 case BinaryOperator::EQ:
3813 case BinaryOperator::NE:
3814 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3815 break;
3816 case BinaryOperator::And:
3817 case BinaryOperator::Xor:
3818 case BinaryOperator::Or:
3819 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3820 break;
3821 case BinaryOperator::LAnd:
3822 case BinaryOperator::LOr:
3823 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3824 break;
3825 case BinaryOperator::MulAssign:
3826 case BinaryOperator::DivAssign:
3827 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3828 if (!CompTy.isNull())
3829 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3830 break;
3831 case BinaryOperator::RemAssign:
3832 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3833 if (!CompTy.isNull())
3834 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3835 break;
3836 case BinaryOperator::AddAssign:
3837 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3838 if (!CompTy.isNull())
3839 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3840 break;
3841 case BinaryOperator::SubAssign:
3842 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3843 if (!CompTy.isNull())
3844 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3845 break;
3846 case BinaryOperator::ShlAssign:
3847 case BinaryOperator::ShrAssign:
3848 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3849 if (!CompTy.isNull())
3850 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3851 break;
3852 case BinaryOperator::AndAssign:
3853 case BinaryOperator::XorAssign:
3854 case BinaryOperator::OrAssign:
3855 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3856 if (!CompTy.isNull())
3857 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3858 break;
3859 case BinaryOperator::Comma:
3860 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3861 break;
3862 }
3863 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003864 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003865 if (CompTy.isNull())
3866 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3867 else
3868 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00003869 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003870}
3871
Chris Lattner4b009652007-07-25 00:24:17 +00003872// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003873Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3874 tok::TokenKind Kind,
3875 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003876 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003877 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003878
Steve Naroff87d58b42007-09-16 03:34:24 +00003879 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3880 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003881
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003882 // If either expression is type-dependent, just build the AST.
3883 // FIXME: We'll need to perform some caching of the result of name
3884 // lookup for operator+.
3885 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003886 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3887 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003888 Context.DependentTy,
3889 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003890 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003891 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3892 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003893 }
3894
Sebastian Redl95216a62009-02-07 00:15:38 +00003895 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003896 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3897 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003898 // If this is one of the assignment operators, we only perform
3899 // overload resolution if the left-hand side is a class or
3900 // enumeration type (C++ [expr.ass]p3).
3901 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3902 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3903 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3904 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003905
Douglas Gregord7f915e2008-11-06 23:29:22 +00003906 // Determine which overloaded operator we're dealing with.
3907 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003908 // Overloading .* is not possible.
3909 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003910 OO_Star, OO_Slash, OO_Percent,
3911 OO_Plus, OO_Minus,
3912 OO_LessLess, OO_GreaterGreater,
3913 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3914 OO_EqualEqual, OO_ExclaimEqual,
3915 OO_Amp,
3916 OO_Caret,
3917 OO_Pipe,
3918 OO_AmpAmp,
3919 OO_PipePipe,
3920 OO_Equal, OO_StarEqual,
3921 OO_SlashEqual, OO_PercentEqual,
3922 OO_PlusEqual, OO_MinusEqual,
3923 OO_LessLessEqual, OO_GreaterGreaterEqual,
3924 OO_AmpEqual, OO_CaretEqual,
3925 OO_PipeEqual,
3926 OO_Comma
3927 };
3928 OverloadedOperatorKind OverOp = OverOps[Opc];
3929
Mike Stump9afab102009-02-19 03:04:26 +00003930 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor5ed15042008-11-18 23:14:02 +00003931 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003932 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003933 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003934 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3935 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003936
3937 // Perform overload resolution.
3938 OverloadCandidateSet::iterator Best;
3939 switch (BestViableFunction(CandidateSet, Best)) {
3940 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003941 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003942 FunctionDecl *FnDecl = Best->Function;
3943
Douglas Gregor70d26122008-11-12 17:17:38 +00003944 if (FnDecl) {
3945 // We matched an overloaded operator. Build a call to that
3946 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003947
Douglas Gregor70d26122008-11-12 17:17:38 +00003948 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003949 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3950 if (PerformObjectArgumentInitialization(lhs, Method) ||
3951 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3952 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003953 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003954 } else {
3955 // Convert the arguments.
3956 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3957 "passing") ||
3958 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3959 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003960 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003961 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003962
Douglas Gregor70d26122008-11-12 17:17:38 +00003963 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003964 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003965 = FnDecl->getType()->getAsFunctionType()->getResultType();
3966 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003967
Douglas Gregor70d26122008-11-12 17:17:38 +00003968 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003969 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3970 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003971 UsualUnaryConversions(FnExpr);
3972
Mike Stump9afab102009-02-19 03:04:26 +00003973 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003974 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003975 } else {
3976 // We matched a built-in operator. Convert the arguments, then
3977 // break out so that we will build the appropriate built-in
3978 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003979 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3980 Best->Conversions[0], "passing") ||
3981 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3982 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003983 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003984
3985 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003986 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003987 }
3988
3989 case OR_No_Viable_Function:
3990 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003991 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003992 break;
3993
3994 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003995 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3996 << BinaryOperator::getOpcodeStr(Opc)
3997 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003998 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003999 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004000
4001 case OR_Deleted:
4002 Diag(TokLoc, diag::err_ovl_deleted_oper)
4003 << Best->Function->isDeleted()
4004 << BinaryOperator::getOpcodeStr(Opc)
4005 << lhs->getSourceRange() << rhs->getSourceRange();
4006 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4007 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00004008 }
4009
Douglas Gregor70d26122008-11-12 17:17:38 +00004010 // Either we found no viable overloaded operator or we matched a
4011 // built-in operator. In either case, fall through to trying to
4012 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004013 }
4014
Douglas Gregord7f915e2008-11-06 23:29:22 +00004015 // Build a built-in binary operation.
4016 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004017}
4018
4019// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00004020Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4021 tok::TokenKind Op, ExprArg input) {
4022 // FIXME: Input is modified later, but smart pointer not reassigned.
4023 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004024 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004025
4026 if (getLangOptions().CPlusPlus &&
Mike Stump9afab102009-02-19 03:04:26 +00004027 (Input->getType()->isRecordType()
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004028 || Input->getType()->isEnumeralType())) {
4029 // Determine which overloaded operator we're dealing with.
4030 static const OverloadedOperatorKind OverOps[] = {
4031 OO_None, OO_None,
4032 OO_PlusPlus, OO_MinusMinus,
4033 OO_Amp, OO_Star,
4034 OO_Plus, OO_Minus,
4035 OO_Tilde, OO_Exclaim,
4036 OO_None, OO_None,
Mike Stump9afab102009-02-19 03:04:26 +00004037 OO_None,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004038 OO_None
4039 };
4040 OverloadedOperatorKind OverOp = OverOps[Opc];
4041
Mike Stump9afab102009-02-19 03:04:26 +00004042 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004043 // to the candidate set.
4044 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00004045 if (OverOp != OO_None &&
4046 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4047 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004048
4049 // Perform overload resolution.
4050 OverloadCandidateSet::iterator Best;
4051 switch (BestViableFunction(CandidateSet, Best)) {
4052 case OR_Success: {
4053 // We found a built-in operator or an overloaded operator.
4054 FunctionDecl *FnDecl = Best->Function;
4055
4056 if (FnDecl) {
4057 // We matched an overloaded operator. Build a call to that
4058 // operator.
4059
4060 // Convert the arguments.
4061 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4062 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004063 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004064 } else {
4065 // Convert the arguments.
Mike Stump9afab102009-02-19 03:04:26 +00004066 if (PerformCopyInitialization(Input,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004067 FnDecl->getParamDecl(0)->getType(),
4068 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004069 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004070 }
4071
4072 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004073 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004074 = FnDecl->getType()->getAsFunctionType()->getResultType();
4075 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004076
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004077 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00004078 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004079 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004080 UsualUnaryConversions(FnExpr);
4081
Sebastian Redl8b769972009-01-19 00:08:26 +00004082 input.release();
Mike Stump9afab102009-02-19 03:04:26 +00004083 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4084 1, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004085 } else {
4086 // We matched a built-in operator. Convert the arguments, then
4087 // break out so that we will build the appropriate built-in
4088 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004089 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4090 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004091 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004092
4093 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004094 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004095 }
4096
4097 case OR_No_Viable_Function:
4098 // No viable function; fall through to handling this as a
4099 // built-in operator, which will produce an error message for us.
4100 break;
4101
4102 case OR_Ambiguous:
4103 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4104 << UnaryOperator::getOpcodeStr(Opc)
4105 << Input->getSourceRange();
4106 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004107 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004108
4109 case OR_Deleted:
4110 Diag(OpLoc, diag::err_ovl_deleted_oper)
4111 << Best->Function->isDeleted()
4112 << UnaryOperator::getOpcodeStr(Opc)
4113 << Input->getSourceRange();
4114 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4115 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004116 }
4117
4118 // Either we found no viable overloaded operator or we matched a
4119 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004120 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004121 }
4122
Chris Lattner4b009652007-07-25 00:24:17 +00004123 QualType resultType;
4124 switch (Opc) {
4125 default:
4126 assert(0 && "Unimplemented unary expr!");
4127 case UnaryOperator::PreInc:
4128 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004129 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4130 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004131 break;
Mike Stump9afab102009-02-19 03:04:26 +00004132 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004133 resultType = CheckAddressOfOperand(Input, OpLoc);
4134 break;
Mike Stump9afab102009-02-19 03:04:26 +00004135 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004136 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004137 resultType = CheckIndirectionOperand(Input, OpLoc);
4138 break;
4139 case UnaryOperator::Plus:
4140 case UnaryOperator::Minus:
4141 UsualUnaryConversions(Input);
4142 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004143 if (resultType->isDependentType())
4144 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004145 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4146 break;
4147 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4148 resultType->isEnumeralType())
4149 break;
4150 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4151 Opc == UnaryOperator::Plus &&
4152 resultType->isPointerType())
4153 break;
4154
Sebastian Redl8b769972009-01-19 00:08:26 +00004155 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4156 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004157 case UnaryOperator::Not: // bitwise complement
4158 UsualUnaryConversions(Input);
4159 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004160 if (resultType->isDependentType())
4161 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004162 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4163 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4164 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004165 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004166 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004167 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004168 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4169 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004170 break;
4171 case UnaryOperator::LNot: // logical negation
4172 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4173 DefaultFunctionArrayConversion(Input);
4174 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004175 if (resultType->isDependentType())
4176 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004177 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004178 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4179 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004180 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004181 // In C++, it's bool. C++ 5.3.1p8
4182 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004183 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004184 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004185 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004186 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004187 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004188 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004189 resultType = Input->getType();
4190 break;
4191 }
4192 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004193 return ExprError();
4194 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004195 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004196}
4197
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004198/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stump9afab102009-02-19 03:04:26 +00004199Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004200 SourceLocation LabLoc,
4201 IdentifierInfo *LabelII) {
4202 // Look up the record for this label identifier.
4203 LabelStmt *&LabelDecl = LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004204
Daniel Dunbar879788d2008-08-04 16:51:22 +00004205 // If we haven't seen this label yet, create a forward reference. It
4206 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004207 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004208 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004209
Chris Lattner4b009652007-07-25 00:24:17 +00004210 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004211 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4212 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004213}
4214
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004215Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004216 SourceLocation RPLoc) { // "({..})"
4217 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4218 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4219 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4220
Eli Friedmanbc941e12009-01-24 23:09:00 +00004221 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4222 if (isFileScope) {
4223 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4224 }
4225
Chris Lattner4b009652007-07-25 00:24:17 +00004226 // FIXME: there are a variety of strange constraints to enforce here, for
4227 // example, it is not possible to goto into a stmt expression apparently.
4228 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004229
Chris Lattner4b009652007-07-25 00:24:17 +00004230 // FIXME: the last statement in the compount stmt has its value used. We
4231 // should not warn about it being unused.
4232
4233 // If there are sub stmts in the compound stmt, take the type of the last one
4234 // as the type of the stmtexpr.
4235 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004236
Chris Lattner200964f2008-07-26 19:51:01 +00004237 if (!Compound->body_empty()) {
4238 Stmt *LastStmt = Compound->body_back();
4239 // If LastStmt is a label, skip down through into the body.
4240 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4241 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004242
Chris Lattner200964f2008-07-26 19:51:01 +00004243 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004244 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004245 }
Mike Stump9afab102009-02-19 03:04:26 +00004246
Steve Naroff774e4152009-01-21 00:14:39 +00004247 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004248}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004249
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004250Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4251 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004252 SourceLocation TypeLoc,
4253 TypeTy *argty,
4254 OffsetOfComponent *CompPtr,
4255 unsigned NumComponents,
4256 SourceLocation RPLoc) {
4257 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4258 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004259
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004260 bool Dependent = ArgTy->isDependentType();
4261
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004262 // We must have at least one component that refers to the type, and the first
4263 // one is known to be a field designator. Verify that the ArgTy represents
4264 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004265 if (!Dependent && !ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004266 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stump9afab102009-02-19 03:04:26 +00004267
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004268 // Otherwise, create a compound literal expression as the base, and
4269 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004270 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004271 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004272 IList->setType(ArgTy);
4273 Expr *Res =
4274 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4275
Chris Lattnerb37522e2007-08-31 21:49:13 +00004276 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4277 // GCC extension, diagnose them.
4278 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004279 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4280 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004281
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004282 if (!Dependent) {
4283 // FIXME: Dependent case loses a lot of information here. And probably
4284 // leaks like a sieve.
4285 for (unsigned i = 0; i != NumComponents; ++i) {
4286 const OffsetOfComponent &OC = CompPtr[i];
4287 if (OC.isBrackets) {
4288 // Offset of an array sub-field. TODO: Should we allow vector elements?
4289 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4290 if (!AT) {
4291 Res->Destroy(Context);
4292 return Diag(OC.LocEnd, diag::err_offsetof_array_type)
4293 << Res->getType();
4294 }
4295
4296 // FIXME: C++: Verify that operator[] isn't overloaded.
4297
4298 // C99 6.5.2.1p1
4299 Expr *Idx = static_cast<Expr*>(OC.U.E);
4300 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4301 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4302 << Idx->getSourceRange();
4303
4304 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4305 OC.LocEnd);
4306 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004307 }
Mike Stump9afab102009-02-19 03:04:26 +00004308
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004309 const RecordType *RC = Res->getType()->getAsRecordType();
4310 if (!RC) {
4311 Res->Destroy(Context);
4312 return Diag(OC.LocEnd, diag::err_offsetof_record_type)
4313 << Res->getType();
4314 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004315
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004316 // Get the decl corresponding to this.
4317 RecordDecl *RD = RC->getDecl();
4318 FieldDecl *MemberDecl
4319 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4320 LookupMemberName)
4321 .getAsDecl());
4322 if (!MemberDecl)
4323 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4324 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004325
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004326 // FIXME: C++: Verify that MemberDecl isn't a static field.
4327 // FIXME: Verify that MemberDecl isn't a bitfield.
4328 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4329 // matter here.
4330 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004331 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004332 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004333 }
Mike Stump9afab102009-02-19 03:04:26 +00004334
4335 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff774e4152009-01-21 00:14:39 +00004336 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004337}
4338
4339
Mike Stump9afab102009-02-19 03:04:26 +00004340Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004341 TypeTy *arg1, TypeTy *arg2,
4342 SourceLocation RPLoc) {
4343 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4344 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004345
Steve Naroff63bad2d2007-08-01 22:05:33 +00004346 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004347
4348 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff774e4152009-01-21 00:14:39 +00004349 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004350}
4351
Mike Stump9afab102009-02-19 03:04:26 +00004352Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004353 ExprTy *expr1, ExprTy *expr2,
4354 SourceLocation RPLoc) {
4355 Expr *CondExpr = static_cast<Expr*>(cond);
4356 Expr *LHSExpr = static_cast<Expr*>(expr1);
4357 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stump9afab102009-02-19 03:04:26 +00004358
Steve Naroff93c53012007-08-03 21:21:27 +00004359 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4360
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004361 QualType resType;
4362 if (CondExpr->isValueDependent()) {
4363 resType = Context.DependentTy;
4364 } else {
4365 // The conditional expression is required to be a constant expression.
4366 llvm::APSInt condEval(32);
4367 SourceLocation ExpLoc;
4368 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4369 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4370 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004371
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004372 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4373 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4374 }
4375
Mike Stump9afab102009-02-19 03:04:26 +00004376 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00004377 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004378}
4379
Steve Naroff52a81c02008-09-03 18:15:37 +00004380//===----------------------------------------------------------------------===//
4381// Clang Extensions.
4382//===----------------------------------------------------------------------===//
4383
4384/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004385void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004386 // Analyze block parameters.
4387 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004388
Steve Naroff52a81c02008-09-03 18:15:37 +00004389 // Add BSI to CurBlock.
4390 BSI->PrevBlockInfo = CurBlock;
4391 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004392
Steve Naroff52a81c02008-09-03 18:15:37 +00004393 BSI->ReturnType = 0;
4394 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004395 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004396
Steve Naroff52059382008-10-10 01:28:17 +00004397 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004398 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004399}
4400
Mike Stumpc1fddff2009-02-04 22:31:32 +00004401void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4402 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4403
4404 if (ParamInfo.getNumTypeObjects() == 0
4405 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4406 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4407
4408 // The type is entirely optional as well, if none, use DependentTy.
4409 if (T.isNull())
4410 T = Context.DependentTy;
4411
4412 // The parameter list is optional, if there was none, assume ().
4413 if (!T->isFunctionType())
4414 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4415
4416 CurBlock->hasPrototype = true;
4417 CurBlock->isVariadic = false;
4418 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4419 .getTypePtr();
4420
4421 if (!RetTy->isDependentType())
4422 CurBlock->ReturnType = RetTy;
4423 return;
4424 }
4425
Steve Naroff52a81c02008-09-03 18:15:37 +00004426 // Analyze arguments to block.
4427 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4428 "Not a function declarator!");
4429 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004430
Steve Naroff52059382008-10-10 01:28:17 +00004431 CurBlock->hasPrototype = FTI.hasPrototype;
4432 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004433
Steve Naroff52a81c02008-09-03 18:15:37 +00004434 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4435 // no arguments, not a function that takes a single void argument.
4436 if (FTI.hasPrototype &&
4437 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4438 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4439 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4440 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004441 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004442 } else if (FTI.hasPrototype) {
4443 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004444 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4445 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004446 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4447
4448 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4449 .getTypePtr();
4450
4451 if (!RetTy->isDependentType())
4452 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004453 }
Steve Naroff52059382008-10-10 01:28:17 +00004454 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004455
Steve Naroff52059382008-10-10 01:28:17 +00004456 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4457 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4458 // If this has an identifier, add it to the scope stack.
4459 if ((*AI)->getIdentifier())
4460 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004461}
4462
4463/// ActOnBlockError - If there is an error parsing a block, this callback
4464/// is invoked to pop the information about the block from the action impl.
4465void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4466 // Ensure that CurBlock is deleted.
4467 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004468
Steve Naroff52a81c02008-09-03 18:15:37 +00004469 // Pop off CurBlock, handle nested blocks.
4470 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004471
Steve Naroff52a81c02008-09-03 18:15:37 +00004472 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stump9afab102009-02-19 03:04:26 +00004473
Steve Naroff52a81c02008-09-03 18:15:37 +00004474}
4475
4476/// ActOnBlockStmtExpr - This is called when the body of a block statement
4477/// literal was successfully completed. ^(int x){...}
4478Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4479 Scope *CurScope) {
4480 // Ensure that CurBlock is deleted.
4481 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004482 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004483
Steve Naroff52059382008-10-10 01:28:17 +00004484 PopDeclContext();
4485
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 QualType RetTy = Context.VoidTy;
4490 if (BSI->ReturnType)
4491 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004492
Steve Naroff52a81c02008-09-03 18:15:37 +00004493 llvm::SmallVector<QualType, 8> ArgTypes;
4494 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4495 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004496
Steve Naroff52a81c02008-09-03 18:15:37 +00004497 QualType BlockTy;
4498 if (!BSI->hasPrototype)
4499 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4500 else
4501 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004502 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004503
Steve Naroff52a81c02008-09-03 18:15:37 +00004504 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004505
Steve Naroff95029d92008-10-08 18:44:00 +00004506 BSI->TheDecl->setBody(Body.take());
Mike Stumpae93d652009-02-19 22:01:56 +00004507 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff52a81c02008-09-03 18:15:37 +00004508}
4509
Anders Carlsson36760332007-10-15 20:28:48 +00004510Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4511 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004512 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004513 Expr *E = static_cast<Expr*>(expr);
4514 QualType T = QualType::getFromOpaquePtr(type);
4515
4516 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004517
4518 // Get the va_list type
4519 QualType VaListType = Context.getBuiltinVaListType();
4520 // Deal with implicit array decay; for example, on x86-64,
4521 // va_list is an array, but it's supposed to decay to
4522 // a pointer for va_arg.
4523 if (VaListType->isArrayType())
4524 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004525 // Make sure the input expression also decays appropriately.
4526 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004527
4528 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004529 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004530 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004531 << E->getType() << E->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004532
Anders Carlsson36760332007-10-15 20:28:48 +00004533 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004534
Steve Naroff774e4152009-01-21 00:14:39 +00004535 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004536}
4537
Douglas Gregorad4b3792008-11-29 04:51:27 +00004538Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4539 // The type of __null will be int or long, depending on the size of
4540 // pointers on the target.
4541 QualType Ty;
4542 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4543 Ty = Context.IntTy;
4544 else
4545 Ty = Context.LongTy;
4546
Steve Naroff774e4152009-01-21 00:14:39 +00004547 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004548}
4549
Chris Lattner005ed752008-01-04 18:04:52 +00004550bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4551 SourceLocation Loc,
4552 QualType DstType, QualType SrcType,
4553 Expr *SrcExpr, const char *Flavor) {
4554 // Decode the result (notice that AST's are still created for extensions).
4555 bool isInvalid = false;
4556 unsigned DiagKind;
4557 switch (ConvTy) {
4558 default: assert(0 && "Unknown conversion type");
4559 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004560 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004561 DiagKind = diag::ext_typecheck_convert_pointer_int;
4562 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004563 case IntToPointer:
4564 DiagKind = diag::ext_typecheck_convert_int_pointer;
4565 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004566 case IncompatiblePointer:
4567 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4568 break;
4569 case FunctionVoidPointer:
4570 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4571 break;
4572 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004573 // If the qualifiers lost were because we were applying the
4574 // (deprecated) C++ conversion from a string literal to a char*
4575 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4576 // Ideally, this check would be performed in
4577 // CheckPointerTypesForAssignment. However, that would require a
4578 // bit of refactoring (so that the second argument is an
4579 // expression, rather than a type), which should be done as part
4580 // of a larger effort to fix CheckPointerTypesForAssignment for
4581 // C++ semantics.
4582 if (getLangOptions().CPlusPlus &&
4583 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4584 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004585 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4586 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004587 case IntToBlockPointer:
4588 DiagKind = diag::err_int_to_block_pointer;
4589 break;
4590 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004591 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004592 break;
Steve Naroff19608432008-10-14 22:18:38 +00004593 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004594 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004595 // it can give a more specific diagnostic.
4596 DiagKind = diag::warn_incompatible_qualified_id;
4597 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004598 case IncompatibleVectors:
4599 DiagKind = diag::warn_incompatible_vectors;
4600 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004601 case Incompatible:
4602 DiagKind = diag::err_typecheck_convert_incompatible;
4603 isInvalid = true;
4604 break;
4605 }
Mike Stump9afab102009-02-19 03:04:26 +00004606
Chris Lattner271d4c22008-11-24 05:29:24 +00004607 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4608 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004609 return isInvalid;
4610}
Anders Carlssond5201b92008-11-30 19:50:32 +00004611
4612bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4613{
4614 Expr::EvalResult EvalResult;
4615
Mike Stump9afab102009-02-19 03:04:26 +00004616 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004617 EvalResult.HasSideEffects) {
4618 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4619
4620 if (EvalResult.Diag) {
4621 // We only show the note if it's not the usual "invalid subexpression"
4622 // or if it's actually in a subexpression.
4623 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4624 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4625 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4626 }
Mike Stump9afab102009-02-19 03:04:26 +00004627
Anders Carlssond5201b92008-11-30 19:50:32 +00004628 return true;
4629 }
4630
4631 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004632 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004633 E->getSourceRange();
4634
4635 // Print the reason it's not a constant.
4636 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4637 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4638 }
Mike Stump9afab102009-02-19 03:04:26 +00004639
Anders Carlssond5201b92008-11-30 19:50:32 +00004640 if (Result)
4641 *Result = EvalResult.Val.getInt();
4642 return false;
4643}