blob: dda8654b49bde2e5648d3e2ca74c63218db277a2 [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
Douglas Gregorc55b0b02009-04-09 21:40:53 +000061 MD = Impl->getClassInterface()->getMethod(Context,
62 MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
64 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
65 }
66 }
67 }
68
69 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000070 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71 }
72
Douglas Gregoraa57e862009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000075 if (FD->isDeleted()) {
76 Diag(Loc, diag::err_deleted_function_use);
77 Diag(D->getLocation(), diag::note_unavailable_here) << true;
78 return true;
79 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000080 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000081
82 // See if the decl is unavailable
83 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000084 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000085 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86 }
87
Douglas Gregoraa57e862009-02-18 21:56:37 +000088 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000089}
90
Douglas Gregor3bb30002009-02-26 21:00:50 +000091SourceRange Sema::getExprRange(ExprTy *E) const {
92 Expr *Ex = (Expr *)E;
93 return Ex? Ex->getSourceRange() : SourceRange();
94}
95
Chris Lattner299b8842008-07-25 21:10:04 +000096//===----------------------------------------------------------------------===//
97// Standard Promotions and Conversions
98//===----------------------------------------------------------------------===//
99
Chris Lattner299b8842008-07-25 21:10:04 +0000100/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
101void Sema::DefaultFunctionArrayConversion(Expr *&E) {
102 QualType Ty = E->getType();
103 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
104
Chris Lattner299b8842008-07-25 21:10:04 +0000105 if (Ty->isFunctionType())
106 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000107 else if (Ty->isArrayType()) {
108 // In C90 mode, arrays only promote to pointers if the array expression is
109 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
110 // type 'array of type' is converted to an expression that has type 'pointer
111 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
112 // that has type 'array of type' ...". The relevant change is "an lvalue"
113 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000114 //
115 // C++ 4.2p1:
116 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
117 // T" can be converted to an rvalue of type "pointer to T".
118 //
119 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
120 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000121 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
122 }
Chris Lattner299b8842008-07-25 21:10:04 +0000123}
124
125/// UsualUnaryConversions - Performs various conversions that are common to most
126/// operators (C99 6.3). The conversions of array and function types are
127/// sometimes surpressed. For example, the array->pointer conversion doesn't
128/// apply if the array is an argument to the sizeof or address (&) operators.
129/// In these instances, this routine should *not* be called.
130Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
131 QualType Ty = Expr->getType();
132 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
133
Chris Lattner299b8842008-07-25 21:10:04 +0000134 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
135 ImpCastExprToType(Expr, Context.IntTy);
136 else
137 DefaultFunctionArrayConversion(Expr);
138
139 return Expr;
140}
141
Chris Lattner9305c3d2008-07-25 22:25:12 +0000142/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
143/// do not have a prototype. Arguments that have type float are promoted to
144/// double. All other argument types are converted by UsualUnaryConversions().
145void Sema::DefaultArgumentPromotion(Expr *&Expr) {
146 QualType Ty = Expr->getType();
147 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
148
149 // If this is a 'float' (CVR qualified or typedef) promote to double.
150 if (const BuiltinType *BT = Ty->getAsBuiltinType())
151 if (BT->getKind() == BuiltinType::Float)
152 return ImpCastExprToType(Expr, Context.DoubleTy);
153
154 UsualUnaryConversions(Expr);
155}
156
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000157// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
158// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000159void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000160 DefaultArgumentPromotion(Expr);
161
162 if (!Expr->getType()->isPODType()) {
163 Diag(Expr->getLocStart(),
164 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
165 Expr->getType() << CT;
166 }
167}
168
169
Chris Lattner299b8842008-07-25 21:10:04 +0000170/// UsualArithmeticConversions - Performs various conversions that are common to
171/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
172/// routine returns the first non-arithmetic type found. The client is
173/// responsible for emitting appropriate error diagnostics.
174/// FIXME: verify the conversion rules for "complex int" are consistent with
175/// GCC.
176QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
177 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000178 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000179 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000180
181 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000182
Chris Lattner299b8842008-07-25 21:10:04 +0000183 // For conversion purposes, we ignore any qualifiers.
184 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000185 QualType lhs =
186 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
187 QualType rhs =
188 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000189
190 // If both types are identical, no conversion is needed.
191 if (lhs == rhs)
192 return lhs;
193
194 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
195 // The caller can deal with this (e.g. pointer + int).
196 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
197 return lhs;
198
199 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000200 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000201 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000202 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000203 return destType;
204}
205
206QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
207 // Perform the usual unary conversions. We do this early so that
208 // integral promotions to "int" can allow us to exit early, in the
209 // lhs == rhs check. Also, for conversion purposes, we ignore any
210 // qualifiers. For example, "const float" and "float" are
211 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000212 if (lhs->isPromotableIntegerType())
213 lhs = Context.IntTy;
214 else
215 lhs = lhs.getUnqualifiedType();
216 if (rhs->isPromotableIntegerType())
217 rhs = Context.IntTy;
218 else
219 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000220
Chris Lattner299b8842008-07-25 21:10:04 +0000221 // If both types are identical, no conversion is needed.
222 if (lhs == rhs)
223 return lhs;
224
225 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
226 // The caller can deal with this (e.g. pointer + int).
227 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
228 return lhs;
229
230 // At this point, we have two different arithmetic types.
231
232 // Handle complex types first (C99 6.3.1.8p1).
233 if (lhs->isComplexType() || rhs->isComplexType()) {
234 // if we have an integer operand, the result is the complex type.
235 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
236 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000237 return lhs;
238 }
239 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
240 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000241 return rhs;
242 }
243 // This handles complex/complex, complex/float, or float/complex.
244 // When both operands are complex, the shorter operand is converted to the
245 // type of the longer, and that is the type of the result. This corresponds
246 // to what is done when combining two real floating-point operands.
247 // The fun begins when size promotion occur across type domains.
248 // From H&S 6.3.4: When one operand is complex and the other is a real
249 // floating-point type, the less precise type is converted, within it's
250 // real or complex domain, to the precision of the other type. For example,
251 // when combining a "long double" with a "double _Complex", the
252 // "double _Complex" is promoted to "long double _Complex".
253 int result = Context.getFloatingTypeOrder(lhs, rhs);
254
255 if (result > 0) { // The left side is bigger, convert rhs.
256 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000257 } else if (result < 0) { // The right side is bigger, convert lhs.
258 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000259 }
260 // At this point, lhs and rhs have the same rank/size. Now, make sure the
261 // domains match. This is a requirement for our implementation, C99
262 // does not require this promotion.
263 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
264 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000265 return rhs;
266 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000267 return lhs;
268 }
269 }
270 return lhs; // The domain/size match exactly.
271 }
272 // Now handle "real" floating types (i.e. float, double, long double).
273 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
274 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000275 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000276 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000277 return lhs;
278 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000279 if (rhs->isComplexIntegerType()) {
280 // convert rhs to the complex floating point type.
281 return Context.getComplexType(lhs);
282 }
283 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000284 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000285 return rhs;
286 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000287 if (lhs->isComplexIntegerType()) {
288 // convert lhs to the complex floating point type.
289 return Context.getComplexType(rhs);
290 }
Chris Lattner299b8842008-07-25 21:10:04 +0000291 // We have two real floating types, float/complex combos were handled above.
292 // Convert the smaller operand to the bigger result.
293 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000294 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000295 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000296 assert(result < 0 && "illegal float comparison");
297 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000298 }
299 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
300 // Handle GCC complex int extension.
301 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
302 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
303
304 if (lhsComplexInt && rhsComplexInt) {
305 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000306 rhsComplexInt->getElementType()) >= 0)
307 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000308 return rhs;
309 } else if (lhsComplexInt && rhs->isIntegerType()) {
310 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000311 return lhs;
312 } else if (rhsComplexInt && lhs->isIntegerType()) {
313 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000314 return rhs;
315 }
316 }
317 // Finally, we have two differing integer types.
318 // The rules for this case are in C99 6.3.1.8
319 int compare = Context.getIntegerTypeOrder(lhs, rhs);
320 bool lhsSigned = lhs->isSignedIntegerType(),
321 rhsSigned = rhs->isSignedIntegerType();
322 QualType destType;
323 if (lhsSigned == rhsSigned) {
324 // Same signedness; use the higher-ranked type
325 destType = compare >= 0 ? lhs : rhs;
326 } else if (compare != (lhsSigned ? 1 : -1)) {
327 // The unsigned type has greater than or equal rank to the
328 // signed type, so use the unsigned type
329 destType = lhsSigned ? rhs : lhs;
330 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
331 // The two types are different widths; if we are here, that
332 // means the signed type is larger than the unsigned type, so
333 // use the signed type.
334 destType = lhsSigned ? lhs : rhs;
335 } else {
336 // The signed type is higher-ranked than the unsigned type,
337 // but isn't actually any bigger (like unsigned int and long
338 // on most 32-bit systems). Use the unsigned type corresponding
339 // to the signed type.
340 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
341 }
Chris Lattner299b8842008-07-25 21:10:04 +0000342 return destType;
343}
344
345//===----------------------------------------------------------------------===//
346// Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
Steve Naroff87d58b42007-09-16 03:34:24 +0000350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000351/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens. However, the common case is that StringToks points to one
354/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000355///
356Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000358 assert(NumStringToks && "Must have at least one string!");
359
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000360 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000361 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000362 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000363
364 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
365 for (unsigned i = 0; i != NumStringToks; ++i)
366 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000367
Chris Lattnera6dcce32008-02-11 00:02:17 +0000368 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000369 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000371
372 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
373 if (getLangOptions().CPlusPlus)
374 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000375
Chris Lattnera6dcce32008-02-11 00:02:17 +0000376 // Get an array type for the string, according to C99 6.4.5. This includes
377 // the nul terminator character as well as the string length for pascal
378 // strings.
379 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000380 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000381 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000382
Chris Lattner4b009652007-07-25 00:24:17 +0000383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000384 return Owned(StringLiteral::Create(Context, Literal.GetString(),
385 Literal.GetStringLength(),
386 Literal.AnyWide, StrTy,
387 &StringTokLocs[0],
388 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000389}
390
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
396/// FIXME: This will create BlockDeclRefExprs for global variables,
397/// function references, etc which is suboptimal :) and breaks
398/// things like "integer constant expression" tests.
399static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
400 ValueDecl *VD) {
401 // If the value is defined inside the block, we couldn't snapshot it even if
402 // we wanted to.
403 if (CurBlock->TheDecl == VD->getDeclContext())
404 return false;
405
406 // If this is an enum constant or function, it is constant, don't snapshot.
407 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408 return false;
409
410 // If this is a reference to an extern, static, or global variable, no need to
411 // snapshot it.
412 // FIXME: What about 'const' variables in C++?
413 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
414 return Var->hasLocalStorage();
415
416 return true;
417}
418
419
420
Steve Naroff0acc9c92007-09-15 18:49:24 +0000421/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000422/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000423/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000425/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
427 IdentifierInfo &II,
428 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000429 const CXXScopeSpec *SS,
430 bool isAddressOfOperand) {
431 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000432 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000433}
434
Douglas Gregor566782a2009-01-06 05:10:23 +0000435/// BuildDeclRefExpr - Build either a DeclRefExpr or a
436/// QualifiedDeclRefExpr based on whether or not SS is a
437/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000438DeclRefExpr *
439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
440 bool TypeDependent, bool ValueDependent,
441 const CXXScopeSpec *SS) {
Douglas Gregor7e508262009-03-19 03:51:16 +0000442 if (SS && !SS->isEmpty()) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000443 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
444 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000445 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000446 } else
Steve Naroff774e4152009-01-21 00:14:39 +0000447 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000448}
449
Douglas Gregor723d3332009-01-07 00:43:41 +0000450/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
451/// variable corresponding to the anonymous union or struct whose type
452/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000453static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
454 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000455 assert(Record->isAnonymousStructOrUnion() &&
456 "Record must be an anonymous struct or union!");
457
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000458 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000459 // be an O(1) operation rather than a slow walk through DeclContext's
460 // vector (which itself will be eliminated). DeclGroups might make
461 // this even better.
462 DeclContext *Ctx = Record->getDeclContext();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000463 for (DeclContext::decl_iterator D = Ctx->decls_begin(Context),
464 DEnd = Ctx->decls_end(Context);
Douglas Gregor723d3332009-01-07 00:43:41 +0000465 D != DEnd; ++D) {
466 if (*D == Record) {
467 // The object for the anonymous struct/union directly
468 // follows its type in the list of declarations.
469 ++D;
470 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000471 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000472 return *D;
473 }
474 }
475
476 assert(false && "Missing object for anonymous record");
477 return 0;
478}
479
Sebastian Redlcd883f72009-01-18 18:53:16 +0000480Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000481Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
482 FieldDecl *Field,
483 Expr *BaseObjectExpr,
484 SourceLocation OpLoc) {
485 assert(Field->getDeclContext()->isRecord() &&
486 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
487 && "Field must be stored inside an anonymous struct or union");
488
489 // Construct the sequence of field member references
490 // we'll have to perform to get to the field in the anonymous
491 // union/struct. The list of members is built from the field
492 // outward, so traverse it backwards to go from an object in
493 // the current context to the field we found.
494 llvm::SmallVector<FieldDecl *, 4> AnonFields;
495 AnonFields.push_back(Field);
496 VarDecl *BaseObject = 0;
497 DeclContext *Ctx = Field->getDeclContext();
498 do {
499 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000500 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000501 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
502 AnonFields.push_back(AnonField);
503 else {
504 BaseObject = cast<VarDecl>(AnonObject);
505 break;
506 }
507 Ctx = Ctx->getParent();
508 } while (Ctx->isRecord() &&
509 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
510
511 // Build the expression that refers to the base object, from
512 // which we will build a sequence of member references to each
513 // of the anonymous union objects and, eventually, the field we
514 // found via name lookup.
515 bool BaseObjectIsPointer = false;
516 unsigned ExtraQuals = 0;
517 if (BaseObject) {
518 // BaseObject is an anonymous struct/union variable (and is,
519 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000520 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000521 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000522 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000523 ExtraQuals
524 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
525 } else if (BaseObjectExpr) {
526 // The caller provided the base object expression. Determine
527 // whether its a pointer and whether it adds any qualifiers to the
528 // anonymous struct/union fields we're looking into.
529 QualType ObjectType = BaseObjectExpr->getType();
530 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
531 BaseObjectIsPointer = true;
532 ObjectType = ObjectPtr->getPointeeType();
533 }
534 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
535 } else {
536 // We've found a member of an anonymous struct/union that is
537 // inside a non-anonymous struct/union, so in a well-formed
538 // program our base object expression is "this".
539 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
540 if (!MD->isStatic()) {
541 QualType AnonFieldType
542 = Context.getTagDeclType(
543 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
544 QualType ThisType = Context.getTagDeclType(MD->getParent());
545 if ((Context.getCanonicalType(AnonFieldType)
546 == Context.getCanonicalType(ThisType)) ||
547 IsDerivedFrom(ThisType, AnonFieldType)) {
548 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000549 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000550 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000551 BaseObjectIsPointer = true;
552 }
553 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000554 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
555 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000556 }
557 ExtraQuals = MD->getTypeQualifiers();
558 }
559
560 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000561 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
562 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000563 }
564
565 // Build the implicit member references to the field of the
566 // anonymous struct/union.
567 Expr *Result = BaseObjectExpr;
568 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
569 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
570 FI != FIEnd; ++FI) {
571 QualType MemberType = (*FI)->getType();
572 if (!(*FI)->isMutable()) {
573 unsigned combinedQualifiers
574 = MemberType.getCVRQualifiers() | ExtraQuals;
575 MemberType = MemberType.getQualifiedType(combinedQualifiers);
576 }
Steve Naroff774e4152009-01-21 00:14:39 +0000577 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
578 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000579 BaseObjectIsPointer = false;
580 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000581 }
582
Sebastian Redlcd883f72009-01-18 18:53:16 +0000583 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000584}
585
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000586/// ActOnDeclarationNameExpr - The parser has read some kind of name
587/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
588/// performs lookup on that name and returns an expression that refers
589/// to that name. This routine isn't directly called from the parser,
590/// because the parser doesn't know about DeclarationName. Rather,
591/// this routine is called by ActOnIdentifierExpr,
592/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
593/// which form the DeclarationName from the corresponding syntactic
594/// forms.
595///
596/// HasTrailingLParen indicates whether this identifier is used in a
597/// function call context. LookupCtx is only used for a C++
598/// qualified-id (foo::bar) to indicate the class or namespace that
599/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000600///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000601/// isAddressOfOperand means that this expression is the direct operand
602/// of an address-of operator. This matters because this is the only
603/// situation where a qualified name referencing a non-static member may
604/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000605Sema::OwningExprResult
606Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
607 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000608 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000609 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000610 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000611 if (SS && SS->isInvalid())
612 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000613
614 // C++ [temp.dep.expr]p3:
615 // An id-expression is type-dependent if it contains:
616 // -- a nested-name-specifier that contains a class-name that
617 // names a dependent type.
618 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000619 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
620 Loc, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000621 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000622 }
623
Douglas Gregor411889e2009-02-13 23:20:09 +0000624 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
625 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000626
Douglas Gregor09be81b2009-02-04 17:27:36 +0000627 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000628 if (Lookup.isAmbiguous()) {
629 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
630 SS && SS->isSet() ? SS->getRange()
631 : SourceRange());
632 return ExprError();
633 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000634 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000635
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000636 // If this reference is in an Objective-C method, then ivar lookup happens as
637 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000638 IdentifierInfo *II = Name.getAsIdentifierInfo();
639 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000640 // There are two cases to handle here. 1) scoped lookup could have failed,
641 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000642 // found a decl, but that decl is outside the current instance method (i.e.
643 // a global variable). In these two cases, we do a lookup for an ivar with
644 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000645 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000646 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000647 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000648 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
649 ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000650 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000651 if (DiagnoseUseOfDecl(IV, Loc))
652 return ExprError();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000653 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
654 // If a class method attemps to use a free standing ivar, this is
655 // an error.
656 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
657 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
658 << IV->getDeclName());
659 // If a class method uses a global variable, even if an ivar with
660 // same name exists, use the global.
661 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000662 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
663 ClassDeclared != IFace)
664 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000665 // FIXME: This should use a new expr for a direct reference, don't turn
666 // this into Self->ivar, just return a BareIVarExpr or something.
667 IdentifierInfo &II = Context.Idents.get("self");
668 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
669 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
670 Loc, static_cast<Expr*>(SelfExpr.release()),
671 true, true);
672 Context.setFieldDecl(IFace, IV, MRef);
673 return Owned(MRef);
674 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000675 }
676 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000677 else if (getCurMethodDecl()->isInstanceMethod()) {
678 // We should warn if a local variable hides an ivar.
679 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000680 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000681 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
682 ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000683 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
684 IFace == ClassDeclared)
685 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
686 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000687 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000688 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000689 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000690 QualType T;
691
692 if (getCurMethodDecl()->isInstanceMethod())
693 T = Context.getPointerType(Context.getObjCInterfaceType(
694 getCurMethodDecl()->getClassInterface()));
695 else
696 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000697 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000698 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000699 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000700
Douglas Gregoraa57e862009-02-18 21:56:37 +0000701 // Determine whether this name might be a candidate for
702 // argument-dependent lookup.
703 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
704 HasTrailingLParen;
705
706 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000707 // We've seen something of the form
708 //
709 // identifier(
710 //
711 // and we did not find any entity by the name
712 // "identifier". However, this identifier is still subject to
713 // argument-dependent lookup, so keep track of the name.
714 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
715 Context.OverloadTy,
716 Loc));
717 }
718
Chris Lattner4b009652007-07-25 00:24:17 +0000719 if (D == 0) {
720 // Otherwise, this could be an implicitly declared function reference (legal
721 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000722 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000723 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000724 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000725 else {
726 // If this name wasn't predeclared and if this is not a function call,
727 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000728 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000729 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
730 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000731 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
732 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000733 return ExprError(Diag(Loc, diag::err_undeclared_use)
734 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000735 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000736 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000737 }
738 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000739
Sebastian Redl0c9da212009-02-03 20:19:35 +0000740 // If this is an expression of the form &Class::member, don't build an
741 // implicit member ref, because we want a pointer to the member in general,
742 // not any specific instance's member.
743 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000744 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000745 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000746 QualType DType;
747 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
748 DType = FD->getType().getNonReferenceType();
749 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
750 DType = Method->getType();
751 } else if (isa<OverloadedFunctionDecl>(D)) {
752 DType = Context.OverloadTy;
753 }
754 // Could be an inner type. That's diagnosed below, so ignore it here.
755 if (!DType.isNull()) {
756 // The pointer is type- and value-dependent if it points into something
757 // dependent.
758 bool Dependent = false;
759 for (; DC; DC = DC->getParent()) {
760 // FIXME: could stop early at namespace scope.
761 if (DC->isRecord()) {
762 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
763 if (Context.getTypeDeclType(Record)->isDependentType()) {
764 Dependent = true;
765 break;
766 }
767 }
768 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000769 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000770 }
771 }
772 }
773
Douglas Gregor723d3332009-01-07 00:43:41 +0000774 // We may have found a field within an anonymous union or struct
775 // (C++ [class.union]).
776 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
777 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
778 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000779
Douglas Gregor3257fb52008-12-22 05:46:06 +0000780 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
781 if (!MD->isStatic()) {
782 // C++ [class.mfct.nonstatic]p2:
783 // [...] if name lookup (3.4.1) resolves the name in the
784 // id-expression to a nonstatic nontype member of class X or of
785 // a base class of X, the id-expression is transformed into a
786 // class member access expression (5.2.5) using (*this) (9.3.2)
787 // as the postfix-expression to the left of the '.' operator.
788 DeclContext *Ctx = 0;
789 QualType MemberType;
790 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
791 Ctx = FD->getDeclContext();
792 MemberType = FD->getType();
793
794 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
795 MemberType = RefType->getPointeeType();
796 else if (!FD->isMutable()) {
797 unsigned combinedQualifiers
798 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
799 MemberType = MemberType.getQualifiedType(combinedQualifiers);
800 }
801 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
802 if (!Method->isStatic()) {
803 Ctx = Method->getParent();
804 MemberType = Method->getType();
805 }
806 } else if (OverloadedFunctionDecl *Ovl
807 = dyn_cast<OverloadedFunctionDecl>(D)) {
808 for (OverloadedFunctionDecl::function_iterator
809 Func = Ovl->function_begin(),
810 FuncEnd = Ovl->function_end();
811 Func != FuncEnd; ++Func) {
812 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
813 if (!DMethod->isStatic()) {
814 Ctx = Ovl->getDeclContext();
815 MemberType = Context.OverloadTy;
816 break;
817 }
818 }
819 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000820
821 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000822 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
823 QualType ThisType = Context.getTagDeclType(MD->getParent());
824 if ((Context.getCanonicalType(CtxType)
825 == Context.getCanonicalType(ThisType)) ||
826 IsDerivedFrom(ThisType, CtxType)) {
827 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000828 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000829 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000830 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000831 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000832 }
833 }
834 }
835 }
836
Douglas Gregor8acb7272008-12-11 16:49:14 +0000837 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000838 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
839 if (MD->isStatic())
840 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000841 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
842 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000843 }
844
Douglas Gregor3257fb52008-12-22 05:46:06 +0000845 // Any other ways we could have found the field in a well-formed
846 // program would have been turned into implicit member expressions
847 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000848 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
849 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000850 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000851
Chris Lattner4b009652007-07-25 00:24:17 +0000852 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000853 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000854 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000855 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000856 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000857 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000858
Steve Naroffd6163f32008-09-05 22:11:13 +0000859 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000860 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000861 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
862 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000863 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
864 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
865 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000866 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000867
Douglas Gregoraa57e862009-02-18 21:56:37 +0000868 // Check whether this declaration can be used. Note that we suppress
869 // this check when we're going to perform argument-dependent lookup
870 // on this function name, because this might not be the function
871 // that overload resolution actually selects.
872 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
873 return ExprError();
874
Douglas Gregor48840c72008-12-10 23:01:14 +0000875 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000876 // Warn about constructs like:
877 // if (void *X = foo()) { ... } else { X }.
878 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000879 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
880 Scope *CheckS = S;
881 while (CheckS) {
882 if (CheckS->isWithinElse() &&
Chris Lattner5261d0c2009-03-28 19:18:32 +0000883 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor48840c72008-12-10 23:01:14 +0000884 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000885 ExprError(Diag(Loc, diag::warn_value_always_false)
886 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000887 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000888 ExprError(Diag(Loc, diag::warn_value_always_zero)
889 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000890 break;
891 }
892
893 // Move up one more control parent to check again.
894 CheckS = CheckS->getControlParent();
895 if (CheckS)
896 CheckS = CheckS->getParent();
897 }
898 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000899 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
900 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
901 // C99 DR 316 says that, if a function type comes from a
902 // function definition (without a prototype), that type is only
903 // used for checking compatibility. Therefore, when referencing
904 // the function, we pretend that we don't have the full function
905 // type.
906 QualType T = Func->getType();
907 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000908 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
909 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000910 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
911 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000912 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000913
914 // Only create DeclRefExpr's for valid Decl's.
915 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000916 return ExprError();
917
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000918 // If the identifier reference is inside a block, and it refers to a value
919 // that is outside the block, create a BlockDeclRefExpr instead of a
920 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
921 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000922 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000923 // We do not do this for things like enum constants, global variables, etc,
924 // as they do not get snapshotted.
925 //
926 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000927 // Blocks that have these can't be constant.
928 CurBlock->hasBlockDeclRefExprs = true;
929
Eli Friedman9c2b33f2009-03-22 23:00:19 +0000930 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +0000931 // The BlocksAttr indicates the variable is bound by-reference.
932 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +0000933 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000934
Steve Naroff52059382008-10-10 01:28:17 +0000935 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman9c2b33f2009-03-22 23:00:19 +0000936 ExprTy.addConst();
937 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000938 }
939 // If this reference is not in a block or if the referenced variable is
940 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000941
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000942 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000943 bool ValueDependent = false;
944 if (getLangOptions().CPlusPlus) {
945 // C++ [temp.dep.expr]p3:
946 // An id-expression is type-dependent if it contains:
947 // - an identifier that was declared with a dependent type,
948 if (VD->getType()->isDependentType())
949 TypeDependent = true;
950 // - FIXME: a template-id that is dependent,
951 // - a conversion-function-id that specifies a dependent type,
952 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
953 Name.getCXXNameType()->isDependentType())
954 TypeDependent = true;
955 // - a nested-name-specifier that contains a class-name that
956 // names a dependent type.
957 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000958 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +0000959 DC; DC = DC->getParent()) {
960 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000961 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000962 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
963 if (Context.getTypeDeclType(Record)->isDependentType()) {
964 TypeDependent = true;
965 break;
966 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000967 }
968 }
969 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000970
Douglas Gregora5d84612008-12-10 20:57:37 +0000971 // C++ [temp.dep.constexpr]p2:
972 //
973 // An identifier is value-dependent if it is:
974 // - a name declared with a dependent type,
975 if (TypeDependent)
976 ValueDependent = true;
977 // - the name of a non-type template parameter,
978 else if (isa<NonTypeTemplateParmDecl>(VD))
979 ValueDependent = true;
980 // - a constant with integral or enumeration type and is
981 // initialized with an expression that is value-dependent
982 // (FIXME!).
983 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000984
Sebastian Redlcd883f72009-01-18 18:53:16 +0000985 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
986 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000987}
988
Sebastian Redlcd883f72009-01-18 18:53:16 +0000989Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
990 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000991 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000992
Chris Lattner4b009652007-07-25 00:24:17 +0000993 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000994 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000995 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
996 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
997 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000998 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000999
Chris Lattner7e637512008-01-12 08:14:25 +00001000 // Pre-defined identifiers are of type char[x], where x is the length of the
1001 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001002 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001003 if (FunctionDecl *FD = getCurFunctionDecl())
1004 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001005 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1006 Length = MD->getSynthesizedMethodSize();
1007 else {
1008 Diag(Loc, diag::ext_predef_outside_function);
1009 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1010 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1011 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001012
1013
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001014 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001015 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001016 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001017 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001018}
1019
Sebastian Redlcd883f72009-01-18 18:53:16 +00001020Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001021 llvm::SmallString<16> CharBuffer;
1022 CharBuffer.resize(Tok.getLength());
1023 const char *ThisTokBegin = &CharBuffer[0];
1024 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001025
Chris Lattner4b009652007-07-25 00:24:17 +00001026 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1027 Tok.getLocation(), PP);
1028 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001029 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001030
1031 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1032
Sebastian Redl75324932009-01-20 22:23:13 +00001033 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1034 Literal.isWide(),
1035 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001036}
1037
Sebastian Redlcd883f72009-01-18 18:53:16 +00001038Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1039 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001040 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1041 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001042 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001043 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001044 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001045 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001046 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001047
Chris Lattner4b009652007-07-25 00:24:17 +00001048 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001049 // Add padding so that NumericLiteralParser can overread by one character.
1050 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001051 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001052
Chris Lattner4b009652007-07-25 00:24:17 +00001053 // Get the spelling of the token, which eliminates trigraphs, etc.
1054 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001055
Chris Lattner4b009652007-07-25 00:24:17 +00001056 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1057 Tok.getLocation(), PP);
1058 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001059 return ExprError();
1060
Chris Lattner1de66eb2007-08-26 03:42:43 +00001061 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001062
Chris Lattner1de66eb2007-08-26 03:42:43 +00001063 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001064 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001065 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001066 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001067 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001068 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001069 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001070 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001071
1072 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1073
Ted Kremenekddedbe22007-11-29 00:56:49 +00001074 // isExact will be set by GetFloatValue().
1075 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001076 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1077 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001078
Chris Lattner1de66eb2007-08-26 03:42:43 +00001079 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001080 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001081 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001082 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001083
Neil Booth7421e9c2007-08-29 22:00:19 +00001084 // long long is a C99 feature.
1085 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001086 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001087 Diag(Tok.getLocation(), diag::ext_longlong);
1088
Chris Lattner4b009652007-07-25 00:24:17 +00001089 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001090 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001091
Chris Lattner4b009652007-07-25 00:24:17 +00001092 if (Literal.GetIntegerValue(ResultVal)) {
1093 // If this value didn't fit into uintmax_t, warn and force to ull.
1094 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001095 Ty = Context.UnsignedLongLongTy;
1096 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001097 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001098 } else {
1099 // If this value fits into a ULL, try to figure out what else it fits into
1100 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001101
Chris Lattner4b009652007-07-25 00:24:17 +00001102 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1103 // be an unsigned int.
1104 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1105
1106 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001107 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001108 if (!Literal.isLong && !Literal.isLongLong) {
1109 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001110 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001111
Chris Lattner4b009652007-07-25 00:24:17 +00001112 // Does it fit in a unsigned int?
1113 if (ResultVal.isIntN(IntSize)) {
1114 // Does it fit in a signed int?
1115 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001116 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001117 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001118 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001119 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001120 }
Chris Lattner4b009652007-07-25 00:24:17 +00001121 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001122
Chris Lattner4b009652007-07-25 00:24:17 +00001123 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001124 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001125 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001126
Chris Lattner4b009652007-07-25 00:24:17 +00001127 // Does it fit in a unsigned long?
1128 if (ResultVal.isIntN(LongSize)) {
1129 // Does it fit in a signed long?
1130 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001131 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001132 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001133 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001134 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001135 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001136 }
1137
Chris Lattner4b009652007-07-25 00:24:17 +00001138 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001139 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001140 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001141
Chris Lattner4b009652007-07-25 00:24:17 +00001142 // Does it fit in a unsigned long long?
1143 if (ResultVal.isIntN(LongLongSize)) {
1144 // Does it fit in a signed long long?
1145 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001146 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001147 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001148 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001149 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001150 }
1151 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001152
Chris Lattner4b009652007-07-25 00:24:17 +00001153 // If we still couldn't decide a type, we probably have something that
1154 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001155 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001156 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001157 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001158 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001159 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001160
Chris Lattnere4068872008-05-09 05:59:00 +00001161 if (ResultVal.getBitWidth() != Width)
1162 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001163 }
Sebastian Redl75324932009-01-20 22:23:13 +00001164 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001165 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001166
Chris Lattner1de66eb2007-08-26 03:42:43 +00001167 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1168 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001169 Res = new (Context) ImaginaryLiteral(Res,
1170 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001171
1172 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001173}
1174
Sebastian Redlcd883f72009-01-18 18:53:16 +00001175Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1176 SourceLocation R, ExprArg Val) {
1177 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001178 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001179 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001180}
1181
1182/// The UsualUnaryConversions() function is *not* called by this routine.
1183/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001184bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001185 SourceLocation OpLoc,
1186 const SourceRange &ExprRange,
1187 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001188 if (exprType->isDependentType())
1189 return false;
1190
Chris Lattner4b009652007-07-25 00:24:17 +00001191 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001192 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001193 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001194 if (isSizeof)
1195 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1196 return false;
1197 }
1198
1199 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001200 Diag(OpLoc, diag::ext_sizeof_void_type)
1201 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001202 return false;
1203 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001204
Douglas Gregorc84d8932009-03-09 16:13:40 +00001205 return RequireCompleteType(OpLoc, exprType,
Chris Lattner159fe082009-01-24 19:46:37 +00001206 isSizeof ? diag::err_sizeof_incomplete_type :
1207 diag::err_alignof_incomplete_type,
1208 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001209}
1210
Chris Lattner8d9f7962009-01-24 20:17:12 +00001211bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1212 const SourceRange &ExprRange) {
1213 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001214
Chris Lattner8d9f7962009-01-24 20:17:12 +00001215 // alignof decl is always ok.
1216 if (isa<DeclRefExpr>(E))
1217 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001218
1219 // Cannot know anything else if the expression is dependent.
1220 if (E->isTypeDependent())
1221 return false;
1222
Chris Lattner8d9f7962009-01-24 20:17:12 +00001223 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1224 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1225 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001226 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001227 return true;
1228 }
1229 // Other fields are ok.
1230 return false;
1231 }
1232 }
1233 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1234}
1235
Douglas Gregor396f1142009-03-13 21:01:28 +00001236/// \brief Build a sizeof or alignof expression given a type operand.
1237Action::OwningExprResult
1238Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1239 bool isSizeOf, SourceRange R) {
1240 if (T.isNull())
1241 return ExprError();
1242
1243 if (!T->isDependentType() &&
1244 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1245 return ExprError();
1246
1247 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1248 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1249 Context.getSizeType(), OpLoc,
1250 R.getEnd()));
1251}
1252
1253/// \brief Build a sizeof or alignof expression given an expression
1254/// operand.
1255Action::OwningExprResult
1256Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1257 bool isSizeOf, SourceRange R) {
1258 // Verify that the operand is valid.
1259 bool isInvalid = false;
1260 if (E->isTypeDependent()) {
1261 // Delay type-checking for type-dependent expressions.
1262 } else if (!isSizeOf) {
1263 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1264 } else if (E->isBitField()) { // C99 6.5.3.4p1.
1265 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1266 isInvalid = true;
1267 } else {
1268 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1269 }
1270
1271 if (isInvalid)
1272 return ExprError();
1273
1274 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1275 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1276 Context.getSizeType(), OpLoc,
1277 R.getEnd()));
1278}
1279
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001280/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1281/// the same for @c alignof and @c __alignof
1282/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001283Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001284Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1285 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001286 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001287 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001288
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001289 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001290 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1291 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1292 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001293
Douglas Gregor396f1142009-03-13 21:01:28 +00001294 // Get the end location.
1295 Expr *ArgEx = (Expr *)TyOrEx;
1296 Action::OwningExprResult Result
1297 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1298
1299 if (Result.isInvalid())
1300 DeleteExpr(ArgEx);
1301
1302 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001303}
1304
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001305QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001306 if (V->isTypeDependent())
1307 return Context.DependentTy;
1308
Chris Lattner03931a72007-08-24 21:16:53 +00001309 DefaultFunctionArrayConversion(V);
1310
Chris Lattnera16e42d2007-08-26 05:39:26 +00001311 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001312 if (const ComplexType *CT = V->getType()->getAsComplexType())
1313 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001314
1315 // Otherwise they pass through real integer and floating point types here.
1316 if (V->getType()->isArithmeticType())
1317 return V->getType();
1318
1319 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001320 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1321 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001322 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001323}
1324
1325
Chris Lattner4b009652007-07-25 00:24:17 +00001326
Sebastian Redl8b769972009-01-19 00:08:26 +00001327Action::OwningExprResult
1328Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1329 tok::TokenKind Kind, ExprArg Input) {
1330 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001331
Chris Lattner4b009652007-07-25 00:24:17 +00001332 UnaryOperator::Opcode Opc;
1333 switch (Kind) {
1334 default: assert(0 && "Unknown unary op!");
1335 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1336 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1337 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001338
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001339 if (getLangOptions().CPlusPlus &&
1340 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1341 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001342 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001343 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1344
1345 // C++ [over.inc]p1:
1346 //
1347 // [...] If the function is a member function with one
1348 // parameter (which shall be of type int) or a non-member
1349 // function with two parameters (the second of which shall be
1350 // of type int), it defines the postfix increment operator ++
1351 // for objects of that type. When the postfix increment is
1352 // called as a result of using the ++ operator, the int
1353 // argument will have value zero.
1354 Expr *Args[2] = {
1355 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001356 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1357 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001358 };
1359
1360 // Build the candidate set for overloading
1361 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001362 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001363
1364 // Perform overload resolution.
1365 OverloadCandidateSet::iterator Best;
1366 switch (BestViableFunction(CandidateSet, Best)) {
1367 case OR_Success: {
1368 // We found a built-in operator or an overloaded operator.
1369 FunctionDecl *FnDecl = Best->Function;
1370
1371 if (FnDecl) {
1372 // We matched an overloaded operator. Build a call to that
1373 // operator.
1374
1375 // Convert the arguments.
1376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1377 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001378 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001379 } else {
1380 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001381 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001382 FnDecl->getParamDecl(0)->getType(),
1383 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001384 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001385 }
1386
1387 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001388 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001389 = FnDecl->getType()->getAsFunctionType()->getResultType();
1390 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001391
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001392 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001393 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001394 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001395 UsualUnaryConversions(FnExpr);
1396
Sebastian Redl8b769972009-01-19 00:08:26 +00001397 Input.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001398 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1399 Args, 2, ResultTy,
1400 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001401 } else {
1402 // We matched a built-in operator. Convert the arguments, then
1403 // break out so that we will build the appropriate built-in
1404 // operator node.
1405 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1406 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001407 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001408
1409 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001410 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001411 }
1412
1413 case OR_No_Viable_Function:
1414 // No viable function; fall through to handling this as a
1415 // built-in operator, which will produce an error message for us.
1416 break;
1417
1418 case OR_Ambiguous:
1419 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1420 << UnaryOperator::getOpcodeStr(Opc)
1421 << Arg->getSourceRange();
1422 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001423 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001424
1425 case OR_Deleted:
1426 Diag(OpLoc, diag::err_ovl_deleted_oper)
1427 << Best->Function->isDeleted()
1428 << UnaryOperator::getOpcodeStr(Opc)
1429 << Arg->getSourceRange();
1430 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1431 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001432 }
1433
1434 // Either we found no viable overloaded operator or we matched a
1435 // built-in operator. In either case, fall through to trying to
1436 // build a built-in operation.
1437 }
1438
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001439 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1440 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001441 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001442 return ExprError();
1443 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001444 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001445}
1446
Sebastian Redl8b769972009-01-19 00:08:26 +00001447Action::OwningExprResult
1448Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1449 ExprArg Idx, SourceLocation RLoc) {
1450 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1451 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001452
Douglas Gregor80723c52008-11-19 17:17:41 +00001453 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001454 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001455 LHSExp->getType()->isEnumeralType() ||
1456 RHSExp->getType()->isRecordType() ||
1457 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001458 // Add the appropriate overloaded operators (C++ [over.match.oper])
1459 // to the candidate set.
1460 OverloadCandidateSet CandidateSet;
1461 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001462 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1463 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001464
Douglas Gregor80723c52008-11-19 17:17:41 +00001465 // Perform overload resolution.
1466 OverloadCandidateSet::iterator Best;
1467 switch (BestViableFunction(CandidateSet, Best)) {
1468 case OR_Success: {
1469 // We found a built-in operator or an overloaded operator.
1470 FunctionDecl *FnDecl = Best->Function;
1471
1472 if (FnDecl) {
1473 // We matched an overloaded operator. Build a call to that
1474 // operator.
1475
1476 // Convert the arguments.
1477 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1478 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1479 PerformCopyInitialization(RHSExp,
1480 FnDecl->getParamDecl(0)->getType(),
1481 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001482 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001483 } else {
1484 // Convert the arguments.
1485 if (PerformCopyInitialization(LHSExp,
1486 FnDecl->getParamDecl(0)->getType(),
1487 "passing") ||
1488 PerformCopyInitialization(RHSExp,
1489 FnDecl->getParamDecl(1)->getType(),
1490 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001491 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001492 }
1493
1494 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001495 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001496 = FnDecl->getType()->getAsFunctionType()->getResultType();
1497 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001498
Douglas Gregor80723c52008-11-19 17:17:41 +00001499 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001500 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1501 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001502 UsualUnaryConversions(FnExpr);
1503
Sebastian Redl8b769972009-01-19 00:08:26 +00001504 Base.release();
1505 Idx.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001506 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1507 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001508 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001509 } else {
1510 // We matched a built-in operator. Convert the arguments, then
1511 // break out so that we will build the appropriate built-in
1512 // operator node.
1513 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1514 "passing") ||
1515 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1516 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001517 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001518
1519 break;
1520 }
1521 }
1522
1523 case OR_No_Viable_Function:
1524 // No viable function; fall through to handling this as a
1525 // built-in operator, which will produce an error message for us.
1526 break;
1527
1528 case OR_Ambiguous:
1529 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1530 << "[]"
1531 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1532 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001533 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001534
1535 case OR_Deleted:
1536 Diag(LLoc, diag::err_ovl_deleted_oper)
1537 << Best->Function->isDeleted()
1538 << "[]"
1539 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1540 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1541 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001542 }
1543
1544 // Either we found no viable overloaded operator or we matched a
1545 // built-in operator. In either case, fall through to trying to
1546 // build a built-in operation.
1547 }
1548
Chris Lattner4b009652007-07-25 00:24:17 +00001549 // Perform default conversions.
1550 DefaultFunctionArrayConversion(LHSExp);
1551 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001552
Chris Lattner4b009652007-07-25 00:24:17 +00001553 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1554
1555 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001556 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001557 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001558 // and index from the expression types.
1559 Expr *BaseExpr, *IndexExpr;
1560 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001561 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1562 BaseExpr = LHSExp;
1563 IndexExpr = RHSExp;
1564 ResultType = Context.DependentTy;
1565 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001566 BaseExpr = LHSExp;
1567 IndexExpr = RHSExp;
1568 // FIXME: need to deal with const...
1569 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001570 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001571 // Handle the uncommon case of "123[Ptr]".
1572 BaseExpr = RHSExp;
1573 IndexExpr = LHSExp;
1574 // FIXME: need to deal with const...
1575 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001576 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1577 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001578 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001579
Chris Lattner4b009652007-07-25 00:24:17 +00001580 // FIXME: need to deal with const...
1581 ResultType = VTy->getElementType();
1582 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001583 return ExprError(Diag(LHSExp->getLocStart(),
1584 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1585 }
Chris Lattner4b009652007-07-25 00:24:17 +00001586 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001587 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001588 return ExprError(Diag(IndexExpr->getLocStart(),
1589 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001590
Douglas Gregor05e28f62009-03-24 19:52:54 +00001591 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1592 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1593 // type. Note that Functions are not objects, and that (in C99 parlance)
1594 // incomplete types are not object types.
1595 if (ResultType->isFunctionType()) {
1596 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1597 << ResultType << BaseExpr->getSourceRange();
1598 return ExprError();
1599 }
1600 if (!ResultType->isDependentType() &&
1601 RequireCompleteType(BaseExpr->getLocStart(), ResultType,
1602 diag::err_subscript_incomplete_type,
1603 BaseExpr->getSourceRange()))
1604 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001605
Sebastian Redl8b769972009-01-19 00:08:26 +00001606 Base.release();
1607 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001608 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001609 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001610}
1611
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001612QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001613CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001614 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001615 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001616
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001617 // The vector accessor can't exceed the number of elements.
1618 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001619
Mike Stump9afab102009-02-19 03:04:26 +00001620 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001621 // special names that indicate a subset of exactly half the elements are
1622 // to be selected.
1623 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001624
Nate Begeman1486b502009-01-18 01:47:54 +00001625 // This flag determines whether or not CompName has an 's' char prefix,
1626 // indicating that it is a string of hex values to be used as vector indices.
1627 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001628
1629 // Check that we've found one of the special components, or that the component
1630 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001631 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001632 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1633 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001634 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001635 do
1636 compStr++;
1637 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001638 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001639 do
1640 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001641 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001642 }
Nate Begeman1486b502009-01-18 01:47:54 +00001643
Mike Stump9afab102009-02-19 03:04:26 +00001644 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001645 // We didn't get to the end of the string. This means the component names
1646 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001647 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1648 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001649 return QualType();
1650 }
Mike Stump9afab102009-02-19 03:04:26 +00001651
Nate Begeman1486b502009-01-18 01:47:54 +00001652 // Ensure no component accessor exceeds the width of the vector type it
1653 // operates on.
1654 if (!HalvingSwizzle) {
1655 compStr = CompName.getName();
1656
1657 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001658 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001659
1660 while (*compStr) {
1661 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1662 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1663 << baseType << SourceRange(CompLoc);
1664 return QualType();
1665 }
1666 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001667 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001668
Nate Begeman1486b502009-01-18 01:47:54 +00001669 // If this is a halving swizzle, verify that the base type has an even
1670 // number of elements.
1671 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001672 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001673 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001674 return QualType();
1675 }
Mike Stump9afab102009-02-19 03:04:26 +00001676
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001677 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001678 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001679 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001680 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001681 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001682 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1683 : CompName.getLength();
1684 if (HexSwizzle)
1685 CompSize--;
1686
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001687 if (CompSize == 1)
1688 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001689
Nate Begemanaf6ed502008-04-18 23:10:10 +00001690 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001691 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001692 // diagostics look bad. We want extended vector types to appear built-in.
1693 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1694 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1695 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001696 }
1697 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001698}
1699
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001700static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1701 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001702 const Selector &Sel,
1703 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001704
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001705 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Context, &Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001706 return PD;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001707 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Context, Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001708 return OMD;
1709
1710 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1711 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001712 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1713 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001714 return D;
1715 }
1716 return 0;
1717}
1718
1719static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1720 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001721 const Selector &Sel,
1722 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001723 // Check protocols on qualified interfaces.
1724 Decl *GDecl = 0;
1725 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1726 E = QIdTy->qual_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001727 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001728 GDecl = PD;
1729 break;
1730 }
1731 // Also must look for a getter name which uses property syntax.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001732 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Context, Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001733 GDecl = OMD;
1734 break;
1735 }
1736 }
1737 if (!GDecl) {
1738 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1739 E = QIdTy->qual_end(); I != E; ++I) {
1740 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001741 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001742 if (GDecl)
1743 return GDecl;
1744 }
1745 }
1746 return GDecl;
1747}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001748
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001749/// FindMethodInNestedImplementations - Look up a method in current and
1750/// all base class implementations.
1751///
1752ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1753 const ObjCInterfaceDecl *IFace,
1754 const Selector &Sel) {
1755 ObjCMethodDecl *Method = 0;
1756 if (ObjCImplementationDecl *ImpDecl =
1757 Sema::ObjCImplementations[IFace->getIdentifier()])
1758 Method = ImpDecl->getInstanceMethod(Sel);
1759
1760 if (!Method && IFace->getSuperClass())
1761 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1762 return Method;
1763}
1764
Sebastian Redl8b769972009-01-19 00:08:26 +00001765Action::OwningExprResult
1766Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1767 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001768 IdentifierInfo &Member,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001769 DeclPtrTy ObjCImpDecl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001770 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001771 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001772
1773 // Perform default conversions.
1774 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001775
Steve Naroff2cb66382007-07-26 03:11:44 +00001776 QualType BaseType = BaseExpr->getType();
1777 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001778
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001779 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1780 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001781 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001782 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001783 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001784 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001785 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1786 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001787 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001788 return ExprError(Diag(MemberLoc,
1789 diag::err_typecheck_member_reference_arrow)
1790 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001791 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001792
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001793 // Handle field access to simple records. This also handles access to fields
1794 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001795 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001796 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00001797 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001798 diag::err_typecheck_incomplete_tag,
1799 BaseExpr->getSourceRange()))
1800 return ExprError();
1801
Steve Naroff2cb66382007-07-26 03:11:44 +00001802 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001803 // FIXME: Qualified name lookup for C++ is a bit more complicated
1804 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001805 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001806 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001807 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001808
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001809 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001810 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1811 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00001812 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001813 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1814 MemberLoc, BaseExpr->getSourceRange());
1815 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00001816 }
1817
1818 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001819
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001820 // If the decl being referenced had an error, return an error for this
1821 // sub-expr without emitting another error, in order to avoid cascading
1822 // error cases.
1823 if (MemberDecl->isInvalidDecl())
1824 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001825
Douglas Gregoraa57e862009-02-18 21:56:37 +00001826 // Check the use of this field
1827 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1828 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001829
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001830 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001831 // We may have found a field within an anonymous union or struct
1832 // (C++ [class.union]).
1833 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001834 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001835 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001836
Douglas Gregor82d44772008-12-20 23:49:58 +00001837 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1838 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001839 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001840 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1841 MemberType = Ref->getPointeeType();
1842 else {
1843 unsigned combinedQualifiers =
1844 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001845 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001846 combinedQualifiers &= ~QualType::Const;
1847 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1848 }
Eli Friedman76b49832008-02-06 22:48:16 +00001849
Steve Naroff774e4152009-01-21 00:14:39 +00001850 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1851 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00001852 }
1853
1854 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001855 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00001856 Var, MemberLoc,
1857 Var->getType().getNonReferenceType()));
1858 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001859 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00001860 MemberFn, MemberLoc,
1861 MemberFn->getType()));
1862 if (OverloadedFunctionDecl *Ovl
1863 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001864 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00001865 MemberLoc, Context.OverloadTy));
1866 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001867 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1868 Enum, MemberLoc, Enum->getType()));
Chris Lattner84ad8332009-03-31 08:18:48 +00001869 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001870 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1871 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001872
Douglas Gregor82d44772008-12-20 23:49:58 +00001873 // We found a declaration kind that we didn't expect. This is a
1874 // generic error message that tells the user that she can't refer
1875 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001876 return ExprError(Diag(MemberLoc,
1877 diag::err_typecheck_member_reference_unknown)
1878 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001879 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001880
Chris Lattnere9d71612008-07-21 04:59:05 +00001881 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1882 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001883 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001884 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001885 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(Context,
1886 &Member,
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001887 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001888 // If the decl being referenced had an error, return an error for this
1889 // sub-expr without emitting another error, in order to avoid cascading
1890 // error cases.
1891 if (IV->isInvalidDecl())
1892 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001893
1894 // Check whether we can reference this field.
1895 if (DiagnoseUseOfDecl(IV, MemberLoc))
1896 return ExprError();
Steve Naroff8c56ee02009-03-26 16:01:08 +00001897 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1898 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001899 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1900 if (ObjCMethodDecl *MD = getCurMethodDecl())
1901 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001902 else if (ObjCImpDecl && getCurFunctionDecl()) {
1903 // Case of a c-function declared inside an objc implementation.
1904 // FIXME: For a c-style function nested inside an objc implementation
1905 // class, there is no implementation context available, so we pass down
1906 // the context as argument to this routine. Ideally, this context need
1907 // be passed down in the AST node and somehow calculated from the AST
1908 // for a function decl.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001909 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001910 if (ObjCImplementationDecl *IMPD =
1911 dyn_cast<ObjCImplementationDecl>(ImplDecl))
1912 ClassOfMethodDecl = IMPD->getClassInterface();
1913 else if (ObjCCategoryImplDecl* CatImplClass =
1914 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1915 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00001916 }
Chris Lattner84ad8332009-03-31 08:18:48 +00001917
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001918 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001919 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001920 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001921 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1922 }
1923 // @protected
1924 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1925 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1926 }
Mike Stump9afab102009-02-19 03:04:26 +00001927
1928 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001929 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001930 OpKind == tok::arrow);
1931 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001932 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001933 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001934 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1935 << IFTy->getDecl()->getDeclName() << &Member
1936 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001937 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001938
Chris Lattnere9d71612008-07-21 04:59:05 +00001939 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1940 // pointer to a (potentially qualified) interface type.
1941 const PointerType *PTy;
1942 const ObjCInterfaceType *IFTy;
1943 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1944 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1945 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001946
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001947 // Search for a declared property first.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001948 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Context,
1949 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001950 // Check whether we can reference this property.
1951 if (DiagnoseUseOfDecl(PD, MemberLoc))
1952 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001953
Steve Naroff774e4152009-01-21 00:14:39 +00001954 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001955 MemberLoc, BaseExpr));
1956 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001957
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001958 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001959 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1960 E = IFTy->qual_end(); I != E; ++I)
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001961 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context,
1962 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001963 // Check whether we can reference this property.
1964 if (DiagnoseUseOfDecl(PD, MemberLoc))
1965 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001966
Steve Naroff774e4152009-01-21 00:14:39 +00001967 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001968 MemberLoc, BaseExpr));
1969 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001970
1971 // If that failed, look for an "implicit" property by seeing if the nullary
1972 // selector is implemented.
1973
1974 // FIXME: The logic for looking up nullary and unary selectors should be
1975 // shared with the code in ActOnInstanceMessage.
1976
1977 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001978 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001979
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001980 // If this reference is in an @implementation, check for 'private' methods.
1981 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001982 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001983
Steve Naroff04151f32008-10-22 19:16:27 +00001984 // Look through local category implementations associated with the class.
1985 if (!Getter) {
1986 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1987 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1988 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1989 }
1990 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001991 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001992 // Check if we can reference this property.
1993 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1994 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00001995 }
1996 // If we found a getter then this may be a valid dot-reference, we
1997 // will look for the matching setter, in case it is needed.
1998 Selector SetterSel =
1999 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2000 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002001 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(Context, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002002 if (!Setter) {
2003 // If this reference is in an @implementation, also check for 'private'
2004 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002005 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002006 }
2007 // Look through local category implementations associated with the class.
2008 if (!Setter) {
2009 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2010 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2011 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002012 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002013 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002014
Steve Naroffdede0c92009-03-11 13:48:17 +00002015 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2016 return ExprError();
2017
2018 if (Getter || Setter) {
2019 QualType PType;
2020
2021 if (Getter)
2022 PType = Getter->getResultType();
2023 else {
2024 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2025 E = Setter->param_end(); PI != E; ++PI)
2026 PType = (*PI)->getType();
2027 }
2028 // FIXME: we must check that the setter has property type.
2029 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2030 Setter, MemberLoc, BaseExpr));
2031 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002032 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2033 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002034 }
Steve Naroffd1d44402008-10-20 22:53:06 +00002035 // Handle properties on qualified "id" protocols.
2036 const ObjCQualifiedIdType *QIdTy;
2037 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2038 // Check protocols on qualified interfaces.
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002039 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002040 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002041 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002042 // Check the use of this declaration
2043 if (DiagnoseUseOfDecl(PD, MemberLoc))
2044 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002045
Steve Naroff774e4152009-01-21 00:14:39 +00002046 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002047 MemberLoc, BaseExpr));
2048 }
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002049 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002050 // Check the use of this method.
2051 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2052 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002053
Mike Stump9afab102009-02-19 03:04:26 +00002054 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002055 OMD->getResultType(),
2056 OMD, OpLoc, MemberLoc,
2057 NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00002058 }
2059 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002060
2061 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2062 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00002063 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002064 // Handle properties on ObjC 'Class' types.
2065 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2066 // Also must look for a getter name which uses property syntax.
2067 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2068 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002069 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2070 ObjCMethodDecl *Getter;
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002071 // FIXME: need to also look locally in the implementation.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002072 if ((Getter = IFace->lookupClassMethod(Context, Sel))) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002073 // Check the use of this method.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002074 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002075 return ExprError();
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002076 }
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002077 // If we found a getter then this may be a valid dot-reference, we
2078 // will look for the matching setter, in case it is needed.
2079 Selector SetterSel =
2080 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2081 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002082 ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002083 if (!Setter) {
2084 // If this reference is in an @implementation, also check for 'private'
2085 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002086 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002087 }
2088 // Look through local category implementations associated with the class.
2089 if (!Setter) {
2090 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2091 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2092 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2093 }
2094 }
2095
2096 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2097 return ExprError();
2098
2099 if (Getter || Setter) {
2100 QualType PType;
2101
2102 if (Getter)
2103 PType = Getter->getResultType();
2104 else {
2105 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2106 E = Setter->param_end(); PI != E; ++PI)
2107 PType = (*PI)->getType();
2108 }
2109 // FIXME: we must check that the setter has property type.
2110 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2111 Setter, MemberLoc, BaseExpr));
2112 }
2113 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2114 << &Member << BaseType);
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002115 }
2116 }
2117
Chris Lattnera57cf472008-07-21 04:28:12 +00002118 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002119 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002120 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2121 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002122 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002123 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002124 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002125 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002126
Douglas Gregor762da552009-03-27 06:00:30 +00002127 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2128 << BaseType << BaseExpr->getSourceRange();
2129
2130 // If the user is trying to apply -> or . to a function or function
2131 // pointer, it's probably because they forgot parentheses to call
2132 // the function. Suggest the addition of those parentheses.
2133 if (BaseType == Context.OverloadTy ||
2134 BaseType->isFunctionType() ||
2135 (BaseType->isPointerType() &&
2136 BaseType->getAsPointerType()->isFunctionType())) {
2137 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2138 Diag(Loc, diag::note_member_reference_needs_call)
2139 << CodeModificationHint::CreateInsertion(Loc, "()");
2140 }
2141
2142 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002143}
2144
Douglas Gregor3257fb52008-12-22 05:46:06 +00002145/// ConvertArgumentsForCall - Converts the arguments specified in
2146/// Args/NumArgs to the parameter types of the function FDecl with
2147/// function prototype Proto. Call is the call expression itself, and
2148/// Fn is the function expression. For a C++ member function, this
2149/// routine does not attempt to convert the object argument. Returns
2150/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002151bool
2152Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002153 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002154 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002155 Expr **Args, unsigned NumArgs,
2156 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002157 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002158 // assignment, to the types of the corresponding parameter, ...
2159 unsigned NumArgsInProto = Proto->getNumArgs();
2160 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002161 bool Invalid = false;
2162
Douglas Gregor3257fb52008-12-22 05:46:06 +00002163 // If too few arguments are available (and we don't have default
2164 // arguments for the remaining parameters), don't make the call.
2165 if (NumArgs < NumArgsInProto) {
2166 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2167 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2168 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2169 // Use default arguments for missing arguments
2170 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002171 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002172 }
2173
2174 // If too many are passed and not variadic, error on the extras and drop
2175 // them.
2176 if (NumArgs > NumArgsInProto) {
2177 if (!Proto->isVariadic()) {
2178 Diag(Args[NumArgsInProto]->getLocStart(),
2179 diag::err_typecheck_call_too_many_args)
2180 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2181 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2182 Args[NumArgs-1]->getLocEnd());
2183 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002184 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002185 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002186 }
2187 NumArgsToCheck = NumArgsInProto;
2188 }
Mike Stump9afab102009-02-19 03:04:26 +00002189
Douglas Gregor3257fb52008-12-22 05:46:06 +00002190 // Continue to check argument types (even if we have too few/many args).
2191 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2192 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002193
Douglas Gregor3257fb52008-12-22 05:46:06 +00002194 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002195 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002196 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002197
Eli Friedman83dec9e2009-03-22 22:00:50 +00002198 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2199 ProtoArgType,
2200 diag::err_call_incomplete_argument,
2201 Arg->getSourceRange()))
2202 return true;
2203
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002204 // Pass the argument.
2205 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2206 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002207 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002208 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002209 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002210 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002211
Douglas Gregor3257fb52008-12-22 05:46:06 +00002212 Call->setArg(i, Arg);
2213 }
Mike Stump9afab102009-02-19 03:04:26 +00002214
Douglas Gregor3257fb52008-12-22 05:46:06 +00002215 // If this is a variadic call, handle args passed through "...".
2216 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002217 VariadicCallType CallType = VariadicFunction;
2218 if (Fn->getType()->isBlockPointerType())
2219 CallType = VariadicBlock; // Block
2220 else if (isa<MemberExpr>(Fn))
2221 CallType = VariadicMethod;
2222
Douglas Gregor3257fb52008-12-22 05:46:06 +00002223 // Promote the arguments (C99 6.5.2.2p7).
2224 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2225 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002226 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002227 Call->setArg(i, Arg);
2228 }
2229 }
2230
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002231 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002232}
2233
Steve Naroff87d58b42007-09-16 03:34:24 +00002234/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002235/// This provides the location of the left/right parens and a list of comma
2236/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002237Action::OwningExprResult
2238Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2239 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002240 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002241 unsigned NumArgs = args.size();
2242 Expr *Fn = static_cast<Expr *>(fn.release());
2243 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002244 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002245 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002246 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002247
Douglas Gregor3257fb52008-12-22 05:46:06 +00002248 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002249 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002250 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002251 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2252 bool Dependent = false;
2253 if (Fn->isTypeDependent())
2254 Dependent = true;
2255 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2256 Dependent = true;
2257
2258 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002259 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002260 Context.DependentTy, RParenLoc));
2261
2262 // Determine whether this is a call to an object (C++ [over.call.object]).
2263 if (Fn->getType()->isRecordType())
2264 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2265 CommaLocs, RParenLoc));
2266
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002267 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002268 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2269 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2270 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002271 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2272 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002273 }
2274
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002275 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002276 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002277 Expr *FnExpr = Fn;
2278 bool ADL = true;
2279 while (true) {
2280 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2281 FnExpr = IcExpr->getSubExpr();
2282 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002283 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002284 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002285 ADL = false;
2286 FnExpr = PExpr->getSubExpr();
2287 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002288 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002289 == UnaryOperator::AddrOf) {
2290 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002291 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2292 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2293 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2294 break;
Mike Stump9afab102009-02-19 03:04:26 +00002295 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002296 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2297 UnqualifiedName = DepName->getName();
2298 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002299 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002300 // Any kind of name that does not refer to a declaration (or
2301 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2302 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002303 break;
2304 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002305 }
Mike Stump9afab102009-02-19 03:04:26 +00002306
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002307 OverloadedFunctionDecl *Ovl = 0;
2308 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002309 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002310 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2311 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002312
Douglas Gregorfcb19192009-02-11 23:02:49 +00002313 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002314 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002315 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002316 ADL = false;
2317
Douglas Gregorfcb19192009-02-11 23:02:49 +00002318 // We don't perform ADL in C.
2319 if (!getLangOptions().CPlusPlus)
2320 ADL = false;
2321
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002322 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002323 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2324 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002325 NumArgs, CommaLocs, RParenLoc, ADL);
2326 if (!FDecl)
2327 return ExprError();
2328
2329 // Update Fn to refer to the actual function selected.
2330 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002331 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002332 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002333 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2334 QDRExpr->getLocation(),
2335 false, false,
2336 QDRExpr->getQualifierRange(),
2337 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002338 else
Mike Stump9afab102009-02-19 03:04:26 +00002339 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002340 Fn->getSourceRange().getBegin());
2341 Fn->Destroy(Context);
2342 Fn = NewFn;
2343 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002344 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002345
2346 // Promote the function operand.
2347 UsualUnaryConversions(Fn);
2348
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002349 // Make the call expr early, before semantic checks. This guarantees cleanup
2350 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002351 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2352 Args, NumArgs,
2353 Context.BoolTy,
2354 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002355
Steve Naroffd6163f32008-09-05 22:11:13 +00002356 const FunctionType *FuncT;
2357 if (!Fn->getType()->isBlockPointerType()) {
2358 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2359 // have type pointer to function".
2360 const PointerType *PT = Fn->getType()->getAsPointerType();
2361 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002362 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2363 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002364 FuncT = PT->getPointeeType()->getAsFunctionType();
2365 } else { // This is a block call.
2366 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2367 getAsFunctionType();
2368 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002369 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002370 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2371 << Fn->getType() << Fn->getSourceRange());
2372
Eli Friedman83dec9e2009-03-22 22:00:50 +00002373 // Check for a valid return type
2374 if (!FuncT->getResultType()->isVoidType() &&
2375 RequireCompleteType(Fn->getSourceRange().getBegin(),
2376 FuncT->getResultType(),
2377 diag::err_call_incomplete_return,
2378 TheCall->getSourceRange()))
2379 return ExprError();
2380
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002381 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002382 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002383
Douglas Gregor4fa58902009-02-26 23:50:07 +00002384 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002385 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002386 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002387 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002388 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002389 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002390
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002391 if (FDecl) {
2392 // Check if we have too few/too many template arguments, based
2393 // on our knowledge of the function definition.
2394 const FunctionDecl *Def = 0;
2395 if (FDecl->getBody(Def) && NumArgs != Def->param_size())
2396 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2397 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2398 }
2399
Steve Naroffdb65e052007-08-28 23:30:39 +00002400 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002401 for (unsigned i = 0; i != NumArgs; i++) {
2402 Expr *Arg = Args[i];
2403 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002404 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2405 Arg->getType(),
2406 diag::err_call_incomplete_argument,
2407 Arg->getSourceRange()))
2408 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002409 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002410 }
Chris Lattner4b009652007-07-25 00:24:17 +00002411 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002412
Douglas Gregor3257fb52008-12-22 05:46:06 +00002413 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2414 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002415 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2416 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002417
Chris Lattner2e64c072007-08-10 20:18:51 +00002418 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002419 if (FDecl)
2420 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002421
Sebastian Redl8b769972009-01-19 00:08:26 +00002422 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002423}
2424
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002425Action::OwningExprResult
2426Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2427 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002428 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002429 QualType literalType = QualType::getFromOpaquePtr(Ty);
2430 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002431 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002432 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002433
Eli Friedman8c2173d2008-05-20 05:22:08 +00002434 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002435 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002436 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2437 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregorc84d8932009-03-09 16:13:40 +00002438 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002439 diag::err_typecheck_decl_incomplete_type,
2440 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002441 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002442
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002443 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002444 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002445 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002446
Chris Lattnere5cb5862008-12-04 23:50:19 +00002447 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002448 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002449 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002450 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002451 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002452 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002453 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002454 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002455}
2456
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002457Action::OwningExprResult
2458Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002459 SourceLocation RBraceLoc) {
2460 unsigned NumInit = initlist.size();
2461 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002462
Steve Naroff0acc9c92007-09-15 18:49:24 +00002463 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002464 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002465
Mike Stump9afab102009-02-19 03:04:26 +00002466 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002467 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002468 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002469 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002470}
2471
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002472/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002473bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002474 UsualUnaryConversions(castExpr);
2475
2476 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2477 // type needs to be scalar.
2478 if (castType->isVoidType()) {
2479 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002480 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2481 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002482 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002483 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2484 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2485 (castType->isStructureType() || castType->isUnionType())) {
2486 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002487 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002488 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2489 << castType << castExpr->getSourceRange();
2490 } else if (castType->isUnionType()) {
2491 // GCC cast to union extension
2492 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2493 RecordDecl::field_iterator Field, FieldEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002494 for (Field = RD->field_begin(Context), FieldEnd = RD->field_end(Context);
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002495 Field != FieldEnd; ++Field) {
2496 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2497 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2498 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2499 << castExpr->getSourceRange();
2500 break;
2501 }
2502 }
2503 if (Field == FieldEnd)
2504 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2505 << castExpr->getType() << castExpr->getSourceRange();
2506 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002507 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002508 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002509 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002510 }
Mike Stump9afab102009-02-19 03:04:26 +00002511 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002512 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002513 return Diag(castExpr->getLocStart(),
2514 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002515 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002516 } else if (castExpr->getType()->isVectorType()) {
2517 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2518 return true;
2519 } else if (castType->isVectorType()) {
2520 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2521 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002522 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002523 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002524 }
2525 return false;
2526}
2527
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002528bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002529 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002530
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002531 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002532 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002533 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002534 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002535 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002536 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002537 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002538 } else
2539 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002540 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002541 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002542
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002543 return false;
2544}
2545
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002546Action::OwningExprResult
2547Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2548 SourceLocation RParenLoc, ExprArg Op) {
2549 assert((Ty != 0) && (Op.get() != 0) &&
2550 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002551
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002552 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002553 QualType castType = QualType::getFromOpaquePtr(Ty);
2554
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002555 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002556 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002557 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002558 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002559}
2560
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002561/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2562/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002563/// C99 6.5.15
2564QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2565 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002566 UsualUnaryConversions(Cond);
2567 UsualUnaryConversions(LHS);
2568 UsualUnaryConversions(RHS);
2569 QualType CondTy = Cond->getType();
2570 QualType LHSTy = LHS->getType();
2571 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002572
2573 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002574 if (!Cond->isTypeDependent()) {
2575 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2576 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2577 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002578 return QualType();
2579 }
Chris Lattner4b009652007-07-25 00:24:17 +00002580 }
Mike Stump9afab102009-02-19 03:04:26 +00002581
Chris Lattner992ae932008-01-06 22:42:25 +00002582 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002583 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002584 return Context.DependentTy;
2585
Chris Lattner992ae932008-01-06 22:42:25 +00002586 // If both operands have arithmetic type, do the usual arithmetic conversions
2587 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002588 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2589 UsualArithmeticConversions(LHS, RHS);
2590 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002591 }
Mike Stump9afab102009-02-19 03:04:26 +00002592
Chris Lattner992ae932008-01-06 22:42:25 +00002593 // If both operands are the same structure or union type, the result is that
2594 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002595 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2596 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002597 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002598 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002599 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002600 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00002601 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00002602 }
Mike Stump9afab102009-02-19 03:04:26 +00002603
Chris Lattner992ae932008-01-06 22:42:25 +00002604 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002605 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002606 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2607 if (!LHSTy->isVoidType())
2608 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2609 << RHS->getSourceRange();
2610 if (!RHSTy->isVoidType())
2611 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2612 << LHS->getSourceRange();
2613 ImpCastExprToType(LHS, Context.VoidTy);
2614 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002615 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002616 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002617 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2618 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002619 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2620 Context.isObjCObjectPointerType(LHSTy)) &&
2621 RHS->isNullPointerConstant(Context)) {
2622 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2623 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002624 }
Chris Lattnere2897262009-02-18 04:28:32 +00002625 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2626 Context.isObjCObjectPointerType(RHSTy)) &&
2627 LHS->isNullPointerConstant(Context)) {
2628 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2629 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002630 }
Mike Stump9afab102009-02-19 03:04:26 +00002631
Chris Lattner0ac51632008-01-06 22:50:31 +00002632 // Handle the case where both operands are pointers before we handle null
2633 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002634 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2635 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002636 // get the "pointed to" types
2637 QualType lhptee = LHSPT->getPointeeType();
2638 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002639
Chris Lattner71225142007-07-31 21:27:01 +00002640 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2641 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002642 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002643 // Figure out necessary qualifiers (C99 6.5.15p6)
2644 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002645 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002646 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2647 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002648 return destType;
2649 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002650 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002651 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002652 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002653 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2654 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002655 return destType;
2656 }
Chris Lattner4b009652007-07-25 00:24:17 +00002657
Chris Lattner9c039b52009-02-18 04:38:20 +00002658 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002659 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002660 return LHSTy;
2661 }
Mike Stump9afab102009-02-19 03:04:26 +00002662
Chris Lattnere2897262009-02-18 04:28:32 +00002663 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002664
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002665 // If either type is an Objective-C object type then check
2666 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002667 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002668 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002669 // If both operands are interfaces and either operand can be
2670 // assigned to the other, use that type as the composite
2671 // type. This allows
2672 // xxx ? (A*) a : (B*) b
2673 // where B is a subclass of A.
2674 //
2675 // Additionally, as for assignment, if either type is 'id'
2676 // allow silent coercion. Finally, if the types are
2677 // incompatible then make sure to use 'id' as the composite
2678 // type so the result is acceptable for sending messages to.
2679
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002680 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002681 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002682 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2683 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2684 if (LHSIface && RHSIface &&
2685 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002686 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002687 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002688 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002689 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002690 } else if (Context.isObjCIdStructType(lhptee) ||
2691 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002692 compositeType = Context.getObjCIdType();
2693 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002694 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002695 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002696 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002697 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002698 ImpCastExprToType(LHS, incompatTy);
2699 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002700 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002701 }
Mike Stump9afab102009-02-19 03:04:26 +00002702 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002703 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002704 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2705 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002706 // In this situation, we assume void* type. No especially good
2707 // reason, but this is what gcc does, and we do have to pick
2708 // to get a consistent AST.
2709 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002710 ImpCastExprToType(LHS, incompatTy);
2711 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002712 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002713 }
2714 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002715 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2716 // differently qualified versions of compatible types, the result type is
2717 // a pointer to an appropriately qualified version of the *composite*
2718 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002719 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002720 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002721 ImpCastExprToType(LHS, compositeType);
2722 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002723 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002724 }
Chris Lattner4b009652007-07-25 00:24:17 +00002725 }
Mike Stump9afab102009-02-19 03:04:26 +00002726
Steve Naroff6ba22682009-04-08 17:05:15 +00002727 // GCC compatibility: soften pointer/integer mismatch.
2728 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
2729 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2730 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2731 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
2732 return RHSTy;
2733 }
2734 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
2735 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2736 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2737 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
2738 return LHSTy;
2739 }
2740
Chris Lattner9c039b52009-02-18 04:38:20 +00002741 // Selection between block pointer types is ok as long as they are the same.
2742 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2743 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2744 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002745
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002746 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2747 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002748 // id with statically typed objects).
2749 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002750 // GCC allows qualified id and any Objective-C type to devolve to
2751 // id. Currently localizing to here until clear this should be
2752 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002753 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002754 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002755 Context.isObjCObjectPointerType(RHSTy)) ||
2756 (RHSTy->isObjCQualifiedIdType() &&
2757 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002758 // FIXME: This is not the correct composite type. This only
2759 // happens to work because id can more or less be used anywhere,
2760 // however this may change the type of method sends.
2761 // FIXME: gcc adds some type-checking of the arguments and emits
2762 // (confusing) incompatible comparison warnings in some
2763 // cases. Investigate.
2764 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002765 ImpCastExprToType(LHS, compositeType);
2766 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002767 return compositeType;
2768 }
2769 }
2770
Chris Lattner992ae932008-01-06 22:42:25 +00002771 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002772 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2773 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002774 return QualType();
2775}
2776
Steve Naroff87d58b42007-09-16 03:34:24 +00002777/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002778/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002779Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2780 SourceLocation ColonLoc,
2781 ExprArg Cond, ExprArg LHS,
2782 ExprArg RHS) {
2783 Expr *CondExpr = (Expr *) Cond.get();
2784 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002785
2786 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2787 // was the condition.
2788 bool isLHSNull = LHSExpr == 0;
2789 if (isLHSNull)
2790 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002791
2792 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002793 RHSExpr, QuestionLoc);
2794 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002795 return ExprError();
2796
2797 Cond.release();
2798 LHS.release();
2799 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002800 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002801 isLHSNull ? 0 : LHSExpr,
2802 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002803}
2804
Chris Lattner4b009652007-07-25 00:24:17 +00002805
2806// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002807// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002808// routine is it effectively iqnores the qualifiers on the top level pointee.
2809// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2810// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002811Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002812Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2813 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002814
Chris Lattner4b009652007-07-25 00:24:17 +00002815 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002816 lhptee = lhsType->getAsPointerType()->getPointeeType();
2817 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002818
Chris Lattner4b009652007-07-25 00:24:17 +00002819 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002820 lhptee = Context.getCanonicalType(lhptee);
2821 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002822
Chris Lattner005ed752008-01-04 18:04:52 +00002823 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002824
2825 // C99 6.5.16.1p1: This following citation is common to constraints
2826 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2827 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002828 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002829 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002830 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002831
Mike Stump9afab102009-02-19 03:04:26 +00002832 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2833 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002834 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002835 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002836 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002837 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002838
Chris Lattner4ca3d772008-01-03 22:56:36 +00002839 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002840 assert(rhptee->isFunctionType());
2841 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002842 }
Mike Stump9afab102009-02-19 03:04:26 +00002843
Chris Lattner4ca3d772008-01-03 22:56:36 +00002844 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002845 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002846 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002847
2848 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002849 assert(lhptee->isFunctionType());
2850 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002851 }
Mike Stump9afab102009-02-19 03:04:26 +00002852 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002853 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00002854 lhptee = lhptee.getUnqualifiedType();
2855 rhptee = rhptee.getUnqualifiedType();
2856 if (!Context.typesAreCompatible(lhptee, rhptee)) {
2857 // Check if the pointee types are compatible ignoring the sign.
2858 // We explicitly check for char so that we catch "char" vs
2859 // "unsigned char" on systems where "char" is unsigned.
2860 if (lhptee->isCharType()) {
2861 lhptee = Context.UnsignedCharTy;
2862 } else if (lhptee->isSignedIntegerType()) {
2863 lhptee = Context.getCorrespondingUnsignedType(lhptee);
2864 }
2865 if (rhptee->isCharType()) {
2866 rhptee = Context.UnsignedCharTy;
2867 } else if (rhptee->isSignedIntegerType()) {
2868 rhptee = Context.getCorrespondingUnsignedType(rhptee);
2869 }
2870 if (lhptee == rhptee) {
2871 // Types are compatible ignoring the sign. Qualifier incompatibility
2872 // takes priority over sign incompatibility because the sign
2873 // warning can be disabled.
2874 if (ConvTy != Compatible)
2875 return ConvTy;
2876 return IncompatiblePointerSign;
2877 }
2878 // General pointer incompatibility takes priority over qualifiers.
2879 return IncompatiblePointer;
2880 }
Chris Lattner005ed752008-01-04 18:04:52 +00002881 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002882}
2883
Steve Naroff3454b6c2008-09-04 15:10:53 +00002884/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2885/// block pointer types are compatible or whether a block and normal pointer
2886/// are compatible. It is more restrict than comparing two function pointer
2887// types.
Mike Stump9afab102009-02-19 03:04:26 +00002888Sema::AssignConvertType
2889Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002890 QualType rhsType) {
2891 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002892
Steve Naroff3454b6c2008-09-04 15:10:53 +00002893 // get the "pointed to" type (ignoring qualifiers at the top level)
2894 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002895 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2896
Steve Naroff3454b6c2008-09-04 15:10:53 +00002897 // make sure we operate on the canonical type
2898 lhptee = Context.getCanonicalType(lhptee);
2899 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002900
Steve Naroff3454b6c2008-09-04 15:10:53 +00002901 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002902
Steve Naroff3454b6c2008-09-04 15:10:53 +00002903 // For blocks we enforce that qualifiers are identical.
2904 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2905 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002906
Steve Naroff3454b6c2008-09-04 15:10:53 +00002907 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002908 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002909 return ConvTy;
2910}
2911
Mike Stump9afab102009-02-19 03:04:26 +00002912/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2913/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002914/// pointers. Here are some objectionable examples that GCC considers warnings:
2915///
2916/// int a, *pint;
2917/// short *pshort;
2918/// struct foo *pfoo;
2919///
2920/// pint = pshort; // warning: assignment from incompatible pointer type
2921/// a = pint; // warning: assignment makes integer from pointer without a cast
2922/// pint = a; // warning: assignment makes pointer from integer without a cast
2923/// pint = pfoo; // warning: assignment from incompatible pointer type
2924///
2925/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002926/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002927///
Chris Lattner005ed752008-01-04 18:04:52 +00002928Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002929Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002930 // Get canonical types. We're not formatting these types, just comparing
2931 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002932 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2933 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002934
2935 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002936 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002937
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002938 // If the left-hand side is a reference type, then we are in a
2939 // (rare!) case where we've allowed the use of references in C,
2940 // e.g., as a parameter type in a built-in function. In this case,
2941 // just make sure that the type referenced is compatible with the
2942 // right-hand side type. The caller is responsible for adjusting
2943 // lhsType so that the resulting expression does not have reference
2944 // type.
2945 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2946 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002947 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002948 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002949 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002950
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002951 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2952 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002953 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002954 // Relax integer conversions like we do for pointers below.
2955 if (rhsType->isIntegerType())
2956 return IntToPointer;
2957 if (lhsType->isIntegerType())
2958 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002959 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002960 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002961
Nate Begemanc5f0f652008-07-14 18:02:46 +00002962 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002963 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002964 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2965 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002966 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002967
Nate Begemanc5f0f652008-07-14 18:02:46 +00002968 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002969 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002970 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002971 if (getLangOptions().LaxVectorConversions &&
2972 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002973 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002974 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002975 }
2976 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002977 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002978
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002979 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002980 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002981
Chris Lattner390564e2008-04-07 06:49:41 +00002982 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002983 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002984 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002985
Chris Lattner390564e2008-04-07 06:49:41 +00002986 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002987 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002988
Steve Naroffa982c712008-09-29 18:10:17 +00002989 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002990 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002991 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002992
2993 // Treat block pointers as objects.
2994 if (getLangOptions().ObjC1 &&
2995 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2996 return Compatible;
2997 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002998 return Incompatible;
2999 }
3000
3001 if (isa<BlockPointerType>(lhsType)) {
3002 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003003 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003004
Steve Naroffa982c712008-09-29 18:10:17 +00003005 // Treat block pointers as objects.
3006 if (getLangOptions().ObjC1 &&
3007 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
3008 return Compatible;
3009
Steve Naroff3454b6c2008-09-04 15:10:53 +00003010 if (rhsType->isBlockPointerType())
3011 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003012
Steve Naroff3454b6c2008-09-04 15:10:53 +00003013 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
3014 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003015 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003016 }
Chris Lattner1853da22008-01-04 23:18:45 +00003017 return Incompatible;
3018 }
3019
Chris Lattner390564e2008-04-07 06:49:41 +00003020 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003021 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003022 if (lhsType == Context.BoolTy)
3023 return Compatible;
3024
3025 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003026 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003027
Mike Stump9afab102009-02-19 03:04:26 +00003028 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003029 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003030
3031 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00003032 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003033 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003034 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003035 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003036
Chris Lattner1853da22008-01-04 23:18:45 +00003037 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003038 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003039 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003040 }
3041 return Incompatible;
3042}
3043
Chris Lattner005ed752008-01-04 18:04:52 +00003044Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003045Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003046 if (getLangOptions().CPlusPlus) {
3047 if (!lhsType->isRecordType()) {
3048 // C++ 5.17p3: If the left operand is not of class type, the
3049 // expression is implicitly converted (C++ 4) to the
3050 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003051 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3052 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003053 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00003054 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003055 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003056 }
3057
3058 // FIXME: Currently, we fall through and treat C++ classes like C
3059 // structures.
3060 }
3061
Steve Naroffcdee22d2007-11-27 17:58:44 +00003062 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3063 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003064 if ((lhsType->isPointerType() ||
3065 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003066 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003067 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003068 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003069 return Compatible;
3070 }
Mike Stump9afab102009-02-19 03:04:26 +00003071
Chris Lattner5f505bf2007-10-16 02:55:40 +00003072 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003073 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003074 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003075 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003076 //
Mike Stump9afab102009-02-19 03:04:26 +00003077 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003078 if (!lhsType->isReferenceType())
3079 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003080
Chris Lattner005ed752008-01-04 18:04:52 +00003081 Sema::AssignConvertType result =
3082 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003083
Steve Naroff0f32f432007-08-24 22:33:52 +00003084 // C99 6.5.16.1p2: The value of the right operand is converted to the
3085 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003086 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3087 // so that we can use references in built-in functions even in C.
3088 // The getNonReferenceType() call makes sure that the resulting expression
3089 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00003090 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003091 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003092 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003093}
3094
Chris Lattner005ed752008-01-04 18:04:52 +00003095Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003096Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
3097 return CheckAssignmentConstraints(lhsType, rhsType);
3098}
3099
Chris Lattner1eafdea2008-11-18 01:30:42 +00003100QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003101 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003102 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003103 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003104 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003105}
3106
Mike Stump9afab102009-02-19 03:04:26 +00003107inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003108 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003109 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003110 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003111 QualType lhsType =
3112 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3113 QualType rhsType =
3114 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003115
Nate Begemanc5f0f652008-07-14 18:02:46 +00003116 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003117 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003118 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003119
Nate Begemanc5f0f652008-07-14 18:02:46 +00003120 // Handle the case of a vector & extvector type of the same size and element
3121 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003122 if (getLangOptions().LaxVectorConversions) {
3123 // FIXME: Should we warn here?
3124 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003125 if (const VectorType *RV = rhsType->getAsVectorType())
3126 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003127 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003128 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003129 }
3130 }
3131 }
Mike Stump9afab102009-02-19 03:04:26 +00003132
Nate Begemanc5f0f652008-07-14 18:02:46 +00003133 // If the lhs is an extended vector and the rhs is a scalar of the same type
3134 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003135 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003136 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00003137
3138 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003139 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3140 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003141 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003142 return lhsType;
3143 }
3144 }
3145
Nate Begemanc5f0f652008-07-14 18:02:46 +00003146 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00003147 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003148 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003149 QualType eltType = V->getElementType();
3150
Mike Stump9afab102009-02-19 03:04:26 +00003151 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003152 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3153 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003154 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003155 return rhsType;
3156 }
3157 }
3158
Chris Lattner4b009652007-07-25 00:24:17 +00003159 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003160 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003161 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003162 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003163 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003164}
3165
Chris Lattner4b009652007-07-25 00:24:17 +00003166inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003167 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003168{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003169 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003170 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003171
Steve Naroff8f708362007-08-24 19:07:16 +00003172 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003173
Chris Lattner4b009652007-07-25 00:24:17 +00003174 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003175 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003176 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003177}
3178
3179inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003180 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003181{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003182 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3183 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3184 return CheckVectorOperands(Loc, lex, rex);
3185 return InvalidOperands(Loc, lex, rex);
3186 }
Chris Lattner4b009652007-07-25 00:24:17 +00003187
Steve Naroff8f708362007-08-24 19:07:16 +00003188 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003189
Chris Lattner4b009652007-07-25 00:24:17 +00003190 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003191 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003192 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003193}
3194
3195inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003196 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003197{
Eli Friedman3cd92882009-03-28 01:22:36 +00003198 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3199 QualType compType = CheckVectorOperands(Loc, lex, rex);
3200 if (CompLHSTy) *CompLHSTy = compType;
3201 return compType;
3202 }
Chris Lattner4b009652007-07-25 00:24:17 +00003203
Eli Friedman3cd92882009-03-28 01:22:36 +00003204 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003205
Chris Lattner4b009652007-07-25 00:24:17 +00003206 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003207 if (lex->getType()->isArithmeticType() &&
3208 rex->getType()->isArithmeticType()) {
3209 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003210 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003211 }
Chris Lattner4b009652007-07-25 00:24:17 +00003212
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003213 // Put any potential pointer into PExp
3214 Expr* PExp = lex, *IExp = rex;
3215 if (IExp->getType()->isPointerType())
3216 std::swap(PExp, IExp);
3217
3218 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3219 if (IExp->getType()->isIntegerType()) {
3220 // Check for arithmetic on pointers to incomplete types
Douglas Gregor05e28f62009-03-24 19:52:54 +00003221 if (PTy->getPointeeType()->isVoidType()) {
3222 if (getLangOptions().CPlusPlus) {
3223 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003224 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003225 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003226 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003227
3228 // GNU extension: arithmetic on pointer to void
3229 Diag(Loc, diag::ext_gnu_void_ptr)
3230 << lex->getSourceRange() << rex->getSourceRange();
3231 } else if (PTy->getPointeeType()->isFunctionType()) {
3232 if (getLangOptions().CPlusPlus) {
3233 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3234 << lex->getType() << lex->getSourceRange();
3235 return QualType();
3236 }
3237
3238 // GNU extension: arithmetic on pointer to function
3239 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3240 << lex->getType() << lex->getSourceRange();
3241 } else if (!PTy->isDependentType() &&
3242 RequireCompleteType(Loc, PTy->getPointeeType(),
3243 diag::err_typecheck_arithmetic_incomplete_type,
3244 lex->getSourceRange(), SourceRange(),
3245 lex->getType()))
3246 return QualType();
3247
Eli Friedman3cd92882009-03-28 01:22:36 +00003248 if (CompLHSTy) {
3249 QualType LHSTy = lex->getType();
3250 if (LHSTy->isPromotableIntegerType())
3251 LHSTy = Context.IntTy;
3252 *CompLHSTy = LHSTy;
3253 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003254 return PExp->getType();
3255 }
3256 }
3257
Chris Lattner1eafdea2008-11-18 01:30:42 +00003258 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003259}
3260
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003261// C99 6.5.6
3262QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003263 SourceLocation Loc, QualType* CompLHSTy) {
3264 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3265 QualType compType = CheckVectorOperands(Loc, lex, rex);
3266 if (CompLHSTy) *CompLHSTy = compType;
3267 return compType;
3268 }
Mike Stump9afab102009-02-19 03:04:26 +00003269
Eli Friedman3cd92882009-03-28 01:22:36 +00003270 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003271
Chris Lattnerf6da2912007-12-09 21:53:25 +00003272 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003273
Chris Lattnerf6da2912007-12-09 21:53:25 +00003274 // Handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003275 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) {
3276 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003277 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003278 }
Mike Stump9afab102009-02-19 03:04:26 +00003279
Chris Lattnerf6da2912007-12-09 21:53:25 +00003280 // Either ptr - int or ptr - ptr.
3281 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003282 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003283
Douglas Gregor05e28f62009-03-24 19:52:54 +00003284 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003285
Douglas Gregor05e28f62009-03-24 19:52:54 +00003286 bool ComplainAboutVoid = false;
3287 Expr *ComplainAboutFunc = 0;
3288 if (lpointee->isVoidType()) {
3289 if (getLangOptions().CPlusPlus) {
3290 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3291 << lex->getSourceRange() << rex->getSourceRange();
3292 return QualType();
3293 }
3294
3295 // GNU C extension: arithmetic on pointer to void
3296 ComplainAboutVoid = true;
3297 } else if (lpointee->isFunctionType()) {
3298 if (getLangOptions().CPlusPlus) {
3299 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003300 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003301 return QualType();
3302 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003303
3304 // GNU C extension: arithmetic on pointer to function
3305 ComplainAboutFunc = lex;
3306 } else if (!lpointee->isDependentType() &&
3307 RequireCompleteType(Loc, lpointee,
3308 diag::err_typecheck_sub_ptr_object,
3309 lex->getSourceRange(),
3310 SourceRange(),
3311 lex->getType()))
3312 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003313
3314 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00003315 if (rex->getType()->isIntegerType()) {
3316 if (ComplainAboutVoid)
3317 Diag(Loc, diag::ext_gnu_void_ptr)
3318 << lex->getSourceRange() << rex->getSourceRange();
3319 if (ComplainAboutFunc)
3320 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3321 << ComplainAboutFunc->getType()
3322 << ComplainAboutFunc->getSourceRange();
3323
Eli Friedman3cd92882009-03-28 01:22:36 +00003324 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003325 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00003326 }
Mike Stump9afab102009-02-19 03:04:26 +00003327
Chris Lattnerf6da2912007-12-09 21:53:25 +00003328 // Handle pointer-pointer subtractions.
3329 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003330 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003331
Douglas Gregor05e28f62009-03-24 19:52:54 +00003332 // RHS must be a completely-type object type.
3333 // Handle the GNU void* extension.
3334 if (rpointee->isVoidType()) {
3335 if (getLangOptions().CPlusPlus) {
3336 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3337 << lex->getSourceRange() << rex->getSourceRange();
3338 return QualType();
3339 }
Mike Stump9afab102009-02-19 03:04:26 +00003340
Douglas Gregor05e28f62009-03-24 19:52:54 +00003341 ComplainAboutVoid = true;
3342 } else if (rpointee->isFunctionType()) {
3343 if (getLangOptions().CPlusPlus) {
3344 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003345 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003346 return QualType();
3347 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003348
3349 // GNU extension: arithmetic on pointer to function
3350 if (!ComplainAboutFunc)
3351 ComplainAboutFunc = rex;
3352 } else if (!rpointee->isDependentType() &&
3353 RequireCompleteType(Loc, rpointee,
3354 diag::err_typecheck_sub_ptr_object,
3355 rex->getSourceRange(),
3356 SourceRange(),
3357 rex->getType()))
3358 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003359
Chris Lattnerf6da2912007-12-09 21:53:25 +00003360 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003361 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003362 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003363 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003364 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003365 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003366 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003367 return QualType();
3368 }
Mike Stump9afab102009-02-19 03:04:26 +00003369
Douglas Gregor05e28f62009-03-24 19:52:54 +00003370 if (ComplainAboutVoid)
3371 Diag(Loc, diag::ext_gnu_void_ptr)
3372 << lex->getSourceRange() << rex->getSourceRange();
3373 if (ComplainAboutFunc)
3374 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3375 << ComplainAboutFunc->getType()
3376 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00003377
3378 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003379 return Context.getPointerDiffType();
3380 }
3381 }
Mike Stump9afab102009-02-19 03:04:26 +00003382
Chris Lattner1eafdea2008-11-18 01:30:42 +00003383 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003384}
3385
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003386// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003387QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003388 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003389 // C99 6.5.7p2: Each of the operands shall have integer type.
3390 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003391 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003392
Chris Lattner2c8bff72007-12-12 05:47:28 +00003393 // Shifts don't perform usual arithmetic conversions, they just do integer
3394 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00003395 QualType LHSTy;
3396 if (lex->getType()->isPromotableIntegerType())
3397 LHSTy = Context.IntTy;
3398 else
3399 LHSTy = lex->getType();
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003400 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00003401 ImpCastExprToType(lex, LHSTy);
3402
Chris Lattner2c8bff72007-12-12 05:47:28 +00003403 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003404
Chris Lattner2c8bff72007-12-12 05:47:28 +00003405 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00003406 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003407}
3408
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003409// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003410QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00003411 unsigned OpaqueOpc, bool isRelational) {
3412 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
3413
Nate Begemanc5f0f652008-07-14 18:02:46 +00003414 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003415 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003416
Chris Lattner254f3bc2007-08-26 01:18:55 +00003417 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003418 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3419 UsualArithmeticConversions(lex, rex);
3420 else {
3421 UsualUnaryConversions(lex);
3422 UsualUnaryConversions(rex);
3423 }
Chris Lattner4b009652007-07-25 00:24:17 +00003424 QualType lType = lex->getType();
3425 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003426
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003427 if (!lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003428 // For non-floating point types, check for self-comparisons of the form
3429 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3430 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00003431 // NOTE: Don't warn about comparisons of enum constants. These can arise
3432 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00003433 Expr *LHSStripped = lex->IgnoreParens();
3434 Expr *RHSStripped = rex->IgnoreParens();
3435 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3436 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00003437 if (DRL->getDecl() == DRR->getDecl() &&
3438 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00003439 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003440
3441 if (isa<CastExpr>(LHSStripped))
3442 LHSStripped = LHSStripped->IgnoreParenCasts();
3443 if (isa<CastExpr>(RHSStripped))
3444 RHSStripped = RHSStripped->IgnoreParenCasts();
3445
3446 // Warn about comparisons against a string constant (unless the other
3447 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00003448 Expr *literalString = 0;
3449 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00003450 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003451 !RHSStripped->isNullPointerConstant(Context)) {
3452 literalString = lex;
3453 literalStringStripped = LHSStripped;
3454 }
Chris Lattner4e479f92009-03-08 19:39:53 +00003455 else if ((isa<StringLiteral>(RHSStripped) ||
3456 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003457 !LHSStripped->isNullPointerConstant(Context)) {
3458 literalString = rex;
3459 literalStringStripped = RHSStripped;
3460 }
3461
3462 if (literalString) {
3463 std::string resultComparison;
3464 switch (Opc) {
3465 case BinaryOperator::LT: resultComparison = ") < 0"; break;
3466 case BinaryOperator::GT: resultComparison = ") > 0"; break;
3467 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
3468 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
3469 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
3470 case BinaryOperator::NE: resultComparison = ") != 0"; break;
3471 default: assert(false && "Invalid comparison operator");
3472 }
3473 Diag(Loc, diag::warn_stringcompare)
3474 << isa<ObjCEncodeExpr>(literalStringStripped)
3475 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00003476 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
3477 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
3478 "strcmp(")
3479 << CodeModificationHint::CreateInsertion(
3480 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00003481 resultComparison);
3482 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003483 }
Mike Stump9afab102009-02-19 03:04:26 +00003484
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003485 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003486 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003487
Chris Lattner254f3bc2007-08-26 01:18:55 +00003488 if (isRelational) {
3489 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003490 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003491 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003492 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003493 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003494 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003495 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003496 }
Mike Stump9afab102009-02-19 03:04:26 +00003497
Chris Lattner254f3bc2007-08-26 01:18:55 +00003498 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003499 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003500 }
Mike Stump9afab102009-02-19 03:04:26 +00003501
Chris Lattner22be8422007-08-26 01:10:14 +00003502 bool LHSIsNull = lex->isNullPointerConstant(Context);
3503 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003504
Chris Lattner254f3bc2007-08-26 01:18:55 +00003505 // All of the following pointer related warnings are GCC extensions, except
3506 // when handling null pointer constants. One day, we can consider making them
3507 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003508 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003509 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003510 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003511 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003512 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003513
Steve Naroff3b435622007-11-13 14:57:38 +00003514 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003515 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3516 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003517 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003518 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003519 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003520 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003521 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003522 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003523 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003524 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003525 // Handle block pointer types.
3526 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3527 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3528 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003529
Steve Naroff3454b6c2008-09-04 15:10:53 +00003530 if (!LHSIsNull && !RHSIsNull &&
3531 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003532 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003533 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003534 }
3535 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003536 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003537 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003538 // Allow block pointers to be compared with null pointer constants.
3539 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3540 (lType->isPointerType() && rType->isBlockPointerType())) {
3541 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003542 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003543 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003544 }
3545 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003546 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003547 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003548
Steve Naroff936c4362008-06-03 14:04:54 +00003549 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003550 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003551 const PointerType *LPT = lType->getAsPointerType();
3552 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003553 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003554 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003555 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003556 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003557
Steve Naroff030fcda2008-11-17 19:49:16 +00003558 if (!LPtrToVoid && !RPtrToVoid &&
3559 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003560 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003561 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003562 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003563 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003564 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003565 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003566 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003567 }
Steve Naroff936c4362008-06-03 14:04:54 +00003568 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3569 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003570 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003571 } else {
3572 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003573 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003574 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003575 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003576 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003577 }
Steve Naroff936c4362008-06-03 14:04:54 +00003578 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003579 }
Mike Stump9afab102009-02-19 03:04:26 +00003580 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003581 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003582 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003583 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003584 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003585 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003586 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003587 }
Mike Stump9afab102009-02-19 03:04:26 +00003588 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003589 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003590 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003591 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003592 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003593 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003594 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003595 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003596 // Handle block pointers.
3597 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3598 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003599 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003600 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003601 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003602 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003603 }
3604 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3605 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003606 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003607 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003608 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003609 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003610 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003611 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003612}
3613
Nate Begemanc5f0f652008-07-14 18:02:46 +00003614/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003615/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003616/// like a scalar comparison, a vector comparison produces a vector of integer
3617/// types.
3618QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003619 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003620 bool isRelational) {
3621 // Check to make sure we're operating on vectors of the same type and width,
3622 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003623 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003624 if (vType.isNull())
3625 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003626
Nate Begemanc5f0f652008-07-14 18:02:46 +00003627 QualType lType = lex->getType();
3628 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003629
Nate Begemanc5f0f652008-07-14 18:02:46 +00003630 // For non-floating point types, check for self-comparisons of the form
3631 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3632 // often indicate logic errors in the program.
3633 if (!lType->isFloatingType()) {
3634 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3635 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3636 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003637 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003638 }
Mike Stump9afab102009-02-19 03:04:26 +00003639
Nate Begemanc5f0f652008-07-14 18:02:46 +00003640 // Check for comparisons of floating point operands using != and ==.
3641 if (!isRelational && lType->isFloatingType()) {
3642 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003643 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003644 }
Mike Stump9afab102009-02-19 03:04:26 +00003645
Chris Lattner10687e32009-03-31 07:46:52 +00003646 // FIXME: Vector compare support in the LLVM backend is not fully reliable,
3647 // just reject all vector comparisons for now.
3648 if (1) {
3649 Diag(Loc, diag::err_typecheck_vector_comparison)
3650 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3651 return QualType();
3652 }
3653
Nate Begemanc5f0f652008-07-14 18:02:46 +00003654 // Return the type for the comparison, which is the same as vector type for
3655 // integer vectors, or an integer type of identical size and number of
3656 // elements for floating point vectors.
3657 if (lType->isIntegerType())
3658 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003659
Nate Begemanc5f0f652008-07-14 18:02:46 +00003660 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003661 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003662 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003663 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00003664 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00003665 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3666
Mike Stump9afab102009-02-19 03:04:26 +00003667 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003668 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003669 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3670}
3671
Chris Lattner4b009652007-07-25 00:24:17 +00003672inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003673 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003674{
3675 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003676 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003677
Steve Naroff8f708362007-08-24 19:07:16 +00003678 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003679
Chris Lattner4b009652007-07-25 00:24:17 +00003680 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003681 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003682 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003683}
3684
3685inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003686 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003687{
3688 UsualUnaryConversions(lex);
3689 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003690
Eli Friedmanbea3f842008-05-13 20:16:47 +00003691 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003692 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003693 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003694}
3695
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003696/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3697/// is a read-only property; return true if so. A readonly property expression
3698/// depends on various declarations and thus must be treated specially.
3699///
Mike Stump9afab102009-02-19 03:04:26 +00003700static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003701{
3702 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3703 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3704 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3705 QualType BaseType = PropExpr->getBase()->getType();
3706 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003707 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003708 PTy->getPointeeType()->getAsObjCInterfaceType())
3709 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3710 if (S.isPropertyReadonly(PDecl, IFace))
3711 return true;
3712 }
3713 }
3714 return false;
3715}
3716
Chris Lattner4c2642c2008-11-18 01:22:49 +00003717/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3718/// emit an error and return true. If so, return false.
3719static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003720 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3721 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3722 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003723 if (IsLV == Expr::MLV_Valid)
3724 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003725
Chris Lattner4c2642c2008-11-18 01:22:49 +00003726 unsigned Diag = 0;
3727 bool NeedType = false;
3728 switch (IsLV) { // C99 6.5.16p2
3729 default: assert(0 && "Unknown result from isModifiableLvalue!");
3730 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003731 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003732 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3733 NeedType = true;
3734 break;
Mike Stump9afab102009-02-19 03:04:26 +00003735 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003736 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3737 NeedType = true;
3738 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003739 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003740 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3741 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003742 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003743 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3744 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003745 case Expr::MLV_IncompleteType:
3746 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00003747 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003748 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3749 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003750 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003751 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3752 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003753 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003754 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3755 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003756 case Expr::MLV_ReadonlyProperty:
3757 Diag = diag::error_readonly_property_assignment;
3758 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003759 case Expr::MLV_NoSetterProperty:
3760 Diag = diag::error_nosetter_property_assignment;
3761 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003762 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003763
Chris Lattner4c2642c2008-11-18 01:22:49 +00003764 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003765 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003766 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003767 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003768 return true;
3769}
3770
3771
3772
3773// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003774QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3775 SourceLocation Loc,
3776 QualType CompoundType) {
3777 // Verify that LHS is a modifiable lvalue, and emit error if not.
3778 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003779 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003780
3781 QualType LHSType = LHS->getType();
3782 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003783
Chris Lattner005ed752008-01-04 18:04:52 +00003784 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003785 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003786 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003787 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003788 // Special case of NSObject attributes on c-style pointer types.
3789 if (ConvTy == IncompatiblePointer &&
3790 ((Context.isObjCNSObjectType(LHSType) &&
3791 Context.isObjCObjectPointerType(RHSType)) ||
3792 (Context.isObjCNSObjectType(RHSType) &&
3793 Context.isObjCObjectPointerType(LHSType))))
3794 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003795
Chris Lattner34c85082008-08-21 18:04:13 +00003796 // If the RHS is a unary plus or minus, check to see if they = and + are
3797 // right next to each other. If so, the user may have typo'd "x =+ 4"
3798 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003799 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003800 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3801 RHSCheck = ICE->getSubExpr();
3802 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3803 if ((UO->getOpcode() == UnaryOperator::Plus ||
3804 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003805 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003806 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00003807 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3808 // And there is a space or other character before the subexpr of the
3809 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00003810 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3811 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003812 Diag(Loc, diag::warn_not_compound_assign)
3813 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3814 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00003815 }
Chris Lattner34c85082008-08-21 18:04:13 +00003816 }
3817 } else {
3818 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003819 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003820 }
Chris Lattner005ed752008-01-04 18:04:52 +00003821
Chris Lattner1eafdea2008-11-18 01:30:42 +00003822 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3823 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003824 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003825
Chris Lattner4b009652007-07-25 00:24:17 +00003826 // C99 6.5.16p3: The type of an assignment expression is the type of the
3827 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003828 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003829 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3830 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003831 // C++ 5.17p1: the type of the assignment expression is that of its left
3832 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003833 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003834}
3835
Chris Lattner1eafdea2008-11-18 01:30:42 +00003836// C99 6.5.17
3837QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00003838 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003839 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00003840
3841 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
3842 // incomplete in C++).
3843
Chris Lattner1eafdea2008-11-18 01:30:42 +00003844 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003845}
3846
3847/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3848/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003849QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3850 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003851 if (Op->isTypeDependent())
3852 return Context.DependentTy;
3853
Chris Lattnere65182c2008-11-21 07:05:48 +00003854 QualType ResType = Op->getType();
3855 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003856
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003857 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3858 // Decrement of bool is not allowed.
3859 if (!isInc) {
3860 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3861 return QualType();
3862 }
3863 // Increment of bool sets it to true, but is deprecated.
3864 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3865 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003866 // OK!
3867 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3868 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00003869 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003870 if (getLangOptions().CPlusPlus) {
3871 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3872 << Op->getSourceRange();
3873 return QualType();
3874 }
3875
3876 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003877 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003878 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003879 if (getLangOptions().CPlusPlus) {
3880 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3881 << Op->getType() << Op->getSourceRange();
3882 return QualType();
3883 }
3884
3885 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003886 << ResType << Op->getSourceRange();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00003887 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
3888 diag::err_typecheck_arithmetic_incomplete_type,
3889 Op->getSourceRange(), SourceRange(),
3890 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003891 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003892 } else if (ResType->isComplexType()) {
3893 // C99 does not support ++/-- on complex types, we allow as an extension.
3894 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003895 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003896 } else {
3897 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003898 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003899 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003900 }
Mike Stump9afab102009-02-19 03:04:26 +00003901 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003902 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003903 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003904 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003905 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003906}
3907
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003908/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003909/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003910/// where the declaration is needed for type checking. We only need to
3911/// handle cases when the expression references a function designator
3912/// or is an lvalue. Here are some examples:
3913/// - &(x) => x
3914/// - &*****f => f for f a function designator.
3915/// - &s.xx => s
3916/// - &s.zz[1].yy -> s, if zz is an array
3917/// - *(x + 1) -> x, if x is an array
3918/// - &"123"[2] -> 0
3919/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003920static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003921 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003922 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003923 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003924 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003925 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003926 // Fields cannot be declared with a 'register' storage class.
3927 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003928 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003929 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003930 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003931 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003932 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003933
Douglas Gregord2baafd2008-10-21 16:13:35 +00003934 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003935 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003936 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003937 return 0;
3938 else
3939 return VD;
3940 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003941 case Stmt::UnaryOperatorClass: {
3942 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003943
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003944 switch(UO->getOpcode()) {
3945 case UnaryOperator::Deref: {
3946 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003947 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3948 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3949 if (!VD || VD->getType()->isPointerType())
3950 return 0;
3951 return VD;
3952 }
3953 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003954 }
3955 case UnaryOperator::Real:
3956 case UnaryOperator::Imag:
3957 case UnaryOperator::Extension:
3958 return getPrimaryDecl(UO->getSubExpr());
3959 default:
3960 return 0;
3961 }
3962 }
3963 case Stmt::BinaryOperatorClass: {
3964 BinaryOperator *BO = cast<BinaryOperator>(E);
3965
3966 // Handle cases involving pointer arithmetic. The result of an
3967 // Assign or AddAssign is not an lvalue so they can be ignored.
3968
3969 // (x + n) or (n + x) => x
3970 if (BO->getOpcode() == BinaryOperator::Add) {
3971 if (BO->getLHS()->getType()->isPointerType()) {
3972 return getPrimaryDecl(BO->getLHS());
3973 } else if (BO->getRHS()->getType()->isPointerType()) {
3974 return getPrimaryDecl(BO->getRHS());
3975 }
3976 }
3977
3978 return 0;
3979 }
Chris Lattner4b009652007-07-25 00:24:17 +00003980 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003981 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003982 case Stmt::ImplicitCastExprClass:
3983 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003984 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003985 default:
3986 return 0;
3987 }
3988}
3989
3990/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003991/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003992/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003993/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003994/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003995/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003996/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003997QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003998 if (op->isTypeDependent())
3999 return Context.DependentTy;
4000
Steve Naroff9c6c3592008-01-13 17:10:08 +00004001 if (getLangOptions().C99) {
4002 // Implement C99-only parts of addressof rules.
4003 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4004 if (uOp->getOpcode() == UnaryOperator::Deref)
4005 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4006 // (assuming the deref expression is valid).
4007 return uOp->getSubExpr()->getType();
4008 }
4009 // Technically, there should be a check for array subscript
4010 // expressions here, but the result of one is always an lvalue anyway.
4011 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004012 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004013 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004014
Chris Lattner4b009652007-07-25 00:24:17 +00004015 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00004016 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
4017 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004018 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4019 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004020 return QualType();
4021 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00004022 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00004023 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
4024 if (Field->isBitField()) {
4025 Diag(OpLoc, diag::err_typecheck_address_of)
4026 << "bit-field" << op->getSourceRange();
4027 return QualType();
4028 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00004029 }
4030 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00004031 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4032 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00004033 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004034 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004035 return QualType();
4036 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004037 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004038 // with the register storage-class specifier.
4039 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4040 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004041 Diag(OpLoc, diag::err_typecheck_address_of)
4042 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004043 return QualType();
4044 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004045 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004046 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00004047 } else if (isa<FieldDecl>(dcl)) {
4048 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004049 // Could be a pointer to member, though, if there is an explicit
4050 // scope qualifier for the class.
4051 if (isa<QualifiedDeclRefExpr>(op)) {
4052 DeclContext *Ctx = dcl->getDeclContext();
4053 if (Ctx && Ctx->isRecord())
4054 return Context.getMemberPointerType(op->getType(),
4055 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4056 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004057 } else if (isa<FunctionDecl>(dcl)) {
4058 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004059 // As above.
4060 if (isa<QualifiedDeclRefExpr>(op)) {
4061 DeclContext *Ctx = dcl->getDeclContext();
4062 if (Ctx && Ctx->isRecord())
4063 return Context.getMemberPointerType(op->getType(),
4064 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4065 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004066 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004067 else
Chris Lattner4b009652007-07-25 00:24:17 +00004068 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004069 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004070
Chris Lattner4b009652007-07-25 00:24:17 +00004071 // If the operand has type "type", the result has type "pointer to type".
4072 return Context.getPointerType(op->getType());
4073}
4074
Chris Lattnerda5c0872008-11-23 09:13:29 +00004075QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004076 if (Op->isTypeDependent())
4077 return Context.DependentTy;
4078
Chris Lattnerda5c0872008-11-23 09:13:29 +00004079 UsualUnaryConversions(Op);
4080 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004081
Chris Lattnerda5c0872008-11-23 09:13:29 +00004082 // Note that per both C89 and C99, this is always legal, even if ptype is an
4083 // incomplete type or void. It would be possible to warn about dereferencing
4084 // a void pointer, but it's completely well-defined, and such a warning is
4085 // unlikely to catch any mistakes.
4086 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004087 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004088
Chris Lattner77d52da2008-11-20 06:06:08 +00004089 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004090 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004091 return QualType();
4092}
4093
4094static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4095 tok::TokenKind Kind) {
4096 BinaryOperator::Opcode Opc;
4097 switch (Kind) {
4098 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004099 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4100 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004101 case tok::star: Opc = BinaryOperator::Mul; break;
4102 case tok::slash: Opc = BinaryOperator::Div; break;
4103 case tok::percent: Opc = BinaryOperator::Rem; break;
4104 case tok::plus: Opc = BinaryOperator::Add; break;
4105 case tok::minus: Opc = BinaryOperator::Sub; break;
4106 case tok::lessless: Opc = BinaryOperator::Shl; break;
4107 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4108 case tok::lessequal: Opc = BinaryOperator::LE; break;
4109 case tok::less: Opc = BinaryOperator::LT; break;
4110 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4111 case tok::greater: Opc = BinaryOperator::GT; break;
4112 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4113 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4114 case tok::amp: Opc = BinaryOperator::And; break;
4115 case tok::caret: Opc = BinaryOperator::Xor; break;
4116 case tok::pipe: Opc = BinaryOperator::Or; break;
4117 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4118 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4119 case tok::equal: Opc = BinaryOperator::Assign; break;
4120 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4121 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4122 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4123 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4124 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4125 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4126 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4127 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4128 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4129 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4130 case tok::comma: Opc = BinaryOperator::Comma; break;
4131 }
4132 return Opc;
4133}
4134
4135static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4136 tok::TokenKind Kind) {
4137 UnaryOperator::Opcode Opc;
4138 switch (Kind) {
4139 default: assert(0 && "Unknown unary op!");
4140 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4141 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4142 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4143 case tok::star: Opc = UnaryOperator::Deref; break;
4144 case tok::plus: Opc = UnaryOperator::Plus; break;
4145 case tok::minus: Opc = UnaryOperator::Minus; break;
4146 case tok::tilde: Opc = UnaryOperator::Not; break;
4147 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004148 case tok::kw___real: Opc = UnaryOperator::Real; break;
4149 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4150 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4151 }
4152 return Opc;
4153}
4154
Douglas Gregord7f915e2008-11-06 23:29:22 +00004155/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4156/// operator @p Opc at location @c TokLoc. This routine only supports
4157/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004158Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4159 unsigned Op,
4160 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004161 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004162 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004163 // The following two variables are used for compound assignment operators
4164 QualType CompLHSTy; // Type of LHS after promotions for computation
4165 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004166
4167 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004168 case BinaryOperator::Assign:
4169 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4170 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004171 case BinaryOperator::PtrMemD:
4172 case BinaryOperator::PtrMemI:
4173 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4174 Opc == BinaryOperator::PtrMemI);
4175 break;
4176 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004177 case BinaryOperator::Div:
4178 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4179 break;
4180 case BinaryOperator::Rem:
4181 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4182 break;
4183 case BinaryOperator::Add:
4184 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4185 break;
4186 case BinaryOperator::Sub:
4187 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4188 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004189 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004190 case BinaryOperator::Shr:
4191 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4192 break;
4193 case BinaryOperator::LE:
4194 case BinaryOperator::LT:
4195 case BinaryOperator::GE:
4196 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004197 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004198 break;
4199 case BinaryOperator::EQ:
4200 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004201 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004202 break;
4203 case BinaryOperator::And:
4204 case BinaryOperator::Xor:
4205 case BinaryOperator::Or:
4206 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4207 break;
4208 case BinaryOperator::LAnd:
4209 case BinaryOperator::LOr:
4210 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4211 break;
4212 case BinaryOperator::MulAssign:
4213 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004214 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4215 CompLHSTy = CompResultTy;
4216 if (!CompResultTy.isNull())
4217 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004218 break;
4219 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004220 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4221 CompLHSTy = CompResultTy;
4222 if (!CompResultTy.isNull())
4223 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004224 break;
4225 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004226 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4227 if (!CompResultTy.isNull())
4228 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004229 break;
4230 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004231 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4232 if (!CompResultTy.isNull())
4233 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004234 break;
4235 case BinaryOperator::ShlAssign:
4236 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004237 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4238 CompLHSTy = CompResultTy;
4239 if (!CompResultTy.isNull())
4240 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004241 break;
4242 case BinaryOperator::AndAssign:
4243 case BinaryOperator::XorAssign:
4244 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004245 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4246 CompLHSTy = CompResultTy;
4247 if (!CompResultTy.isNull())
4248 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004249 break;
4250 case BinaryOperator::Comma:
4251 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4252 break;
4253 }
4254 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004255 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00004256 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00004257 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4258 else
4259 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00004260 CompLHSTy, CompResultTy,
4261 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004262}
4263
Chris Lattner4b009652007-07-25 00:24:17 +00004264// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004265Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4266 tok::TokenKind Kind,
4267 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004268 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004269 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00004270
Steve Naroff87d58b42007-09-16 03:34:24 +00004271 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4272 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004273
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004274 if (getLangOptions().CPlusPlus &&
4275 (lhs->getType()->isOverloadableType() ||
4276 rhs->getType()->isOverloadableType())) {
4277 // Find all of the overloaded operators visible from this
4278 // point. We perform both an operator-name lookup from the local
4279 // scope and an argument-dependent lookup based on the types of
4280 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004281 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004282 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4283 if (OverOp != OO_None) {
4284 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4285 Functions);
4286 Expr *Args[2] = { lhs, rhs };
4287 DeclarationName OpName
4288 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4289 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004290 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004291
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004292 // Build the (potentially-overloaded, potentially-dependent)
4293 // binary operation.
4294 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004295 }
4296
Douglas Gregord7f915e2008-11-06 23:29:22 +00004297 // Build a built-in binary operation.
4298 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004299}
4300
Douglas Gregorc78182d2009-03-13 23:49:33 +00004301Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4302 unsigned OpcIn,
4303 ExprArg InputArg) {
4304 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004305
Douglas Gregorc78182d2009-03-13 23:49:33 +00004306 // FIXME: Input is modified below, but InputArg is not updated
4307 // appropriately.
4308 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004309 QualType resultType;
4310 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004311 case UnaryOperator::PostInc:
4312 case UnaryOperator::PostDec:
4313 case UnaryOperator::OffsetOf:
4314 assert(false && "Invalid unary operator");
4315 break;
4316
Chris Lattner4b009652007-07-25 00:24:17 +00004317 case UnaryOperator::PreInc:
4318 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004319 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4320 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004321 break;
Mike Stump9afab102009-02-19 03:04:26 +00004322 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004323 resultType = CheckAddressOfOperand(Input, OpLoc);
4324 break;
Mike Stump9afab102009-02-19 03:04:26 +00004325 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004326 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004327 resultType = CheckIndirectionOperand(Input, OpLoc);
4328 break;
4329 case UnaryOperator::Plus:
4330 case UnaryOperator::Minus:
4331 UsualUnaryConversions(Input);
4332 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004333 if (resultType->isDependentType())
4334 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004335 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4336 break;
4337 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4338 resultType->isEnumeralType())
4339 break;
4340 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4341 Opc == UnaryOperator::Plus &&
4342 resultType->isPointerType())
4343 break;
4344
Sebastian Redl8b769972009-01-19 00:08:26 +00004345 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4346 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004347 case UnaryOperator::Not: // bitwise complement
4348 UsualUnaryConversions(Input);
4349 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004350 if (resultType->isDependentType())
4351 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004352 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4353 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4354 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004355 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004356 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004357 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004358 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4359 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004360 break;
4361 case UnaryOperator::LNot: // logical negation
4362 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4363 DefaultFunctionArrayConversion(Input);
4364 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004365 if (resultType->isDependentType())
4366 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004367 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004368 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4369 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004370 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004371 // In C++, it's bool. C++ 5.3.1p8
4372 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004373 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004374 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004375 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004376 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004377 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004378 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004379 resultType = Input->getType();
4380 break;
4381 }
4382 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004383 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004384
4385 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004386 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004387}
4388
Douglas Gregorc78182d2009-03-13 23:49:33 +00004389// Unary Operators. 'Tok' is the token for the operator.
4390Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4391 tok::TokenKind Op, ExprArg input) {
4392 Expr *Input = (Expr*)input.get();
4393 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4394
4395 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4396 // Find all of the overloaded operators visible from this
4397 // point. We perform both an operator-name lookup from the local
4398 // scope and an argument-dependent lookup based on the types of
4399 // the arguments.
4400 FunctionSet Functions;
4401 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4402 if (OverOp != OO_None) {
4403 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4404 Functions);
4405 DeclarationName OpName
4406 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4407 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4408 }
4409
4410 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4411 }
4412
4413 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4414}
4415
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004416/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004417Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4418 SourceLocation LabLoc,
4419 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004420 // Look up the record for this label identifier.
Steve Naroffff9ecaf2009-03-13 16:03:38 +00004421 LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4422 LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004423
Daniel Dunbar879788d2008-08-04 16:51:22 +00004424 // If we haven't seen this label yet, create a forward reference. It
4425 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004426 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004427 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004428
Chris Lattner4b009652007-07-25 00:24:17 +00004429 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004430 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4431 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004432}
4433
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004434Sema::OwningExprResult
4435Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4436 SourceLocation RPLoc) { // "({..})"
4437 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004438 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4439 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4440
Eli Friedmanbc941e12009-01-24 23:09:00 +00004441 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4442 if (isFileScope) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004443 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004444 }
4445
Chris Lattner4b009652007-07-25 00:24:17 +00004446 // FIXME: there are a variety of strange constraints to enforce here, for
4447 // example, it is not possible to goto into a stmt expression apparently.
4448 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004449
Chris Lattner4b009652007-07-25 00:24:17 +00004450 // FIXME: the last statement in the compount stmt has its value used. We
4451 // should not warn about it being unused.
4452
4453 // If there are sub stmts in the compound stmt, take the type of the last one
4454 // as the type of the stmtexpr.
4455 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004456
Chris Lattner200964f2008-07-26 19:51:01 +00004457 if (!Compound->body_empty()) {
4458 Stmt *LastStmt = Compound->body_back();
4459 // If LastStmt is a label, skip down through into the body.
4460 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4461 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004462
Chris Lattner200964f2008-07-26 19:51:01 +00004463 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004464 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004465 }
Mike Stump9afab102009-02-19 03:04:26 +00004466
Eli Friedman2b128322009-03-23 00:24:07 +00004467 // FIXME: Check that expression type is complete/non-abstract; statement
4468 // expressions are not lvalues.
4469
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004470 substmt.release();
4471 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004472}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004473
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004474Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4475 SourceLocation BuiltinLoc,
4476 SourceLocation TypeLoc,
4477 TypeTy *argty,
4478 OffsetOfComponent *CompPtr,
4479 unsigned NumComponents,
4480 SourceLocation RPLoc) {
4481 // FIXME: This function leaks all expressions in the offset components on
4482 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004483 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4484 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004485
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004486 bool Dependent = ArgTy->isDependentType();
4487
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004488 // We must have at least one component that refers to the type, and the first
4489 // one is known to be a field designator. Verify that the ArgTy represents
4490 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004491 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004492 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004493
Eli Friedman2b128322009-03-23 00:24:07 +00004494 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4495 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004496
Eli Friedman342d9432009-02-27 06:44:11 +00004497 // Otherwise, create a null pointer as the base, and iteratively process
4498 // the offsetof designators.
4499 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4500 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004501 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004502 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004503
Chris Lattnerb37522e2007-08-31 21:49:13 +00004504 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4505 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004506 // FIXME: This diagnostic isn't actually visible because the location is in
4507 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004508 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004509 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4510 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004511
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004512 if (!Dependent) {
4513 // FIXME: Dependent case loses a lot of information here. And probably
4514 // leaks like a sieve.
4515 for (unsigned i = 0; i != NumComponents; ++i) {
4516 const OffsetOfComponent &OC = CompPtr[i];
4517 if (OC.isBrackets) {
4518 // Offset of an array sub-field. TODO: Should we allow vector elements?
4519 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4520 if (!AT) {
4521 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004522 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4523 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004524 }
4525
4526 // FIXME: C++: Verify that operator[] isn't overloaded.
4527
Eli Friedman342d9432009-02-27 06:44:11 +00004528 // Promote the array so it looks more like a normal array subscript
4529 // expression.
4530 DefaultFunctionArrayConversion(Res);
4531
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004532 // C99 6.5.2.1p1
4533 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004534 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004535 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004536 return ExprError(Diag(Idx->getLocStart(),
4537 diag::err_typecheck_subscript)
4538 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004539
4540 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4541 OC.LocEnd);
4542 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004543 }
Mike Stump9afab102009-02-19 03:04:26 +00004544
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004545 const RecordType *RC = Res->getType()->getAsRecordType();
4546 if (!RC) {
4547 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004548 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4549 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004550 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004551
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004552 // Get the decl corresponding to this.
4553 RecordDecl *RD = RC->getDecl();
4554 FieldDecl *MemberDecl
4555 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4556 LookupMemberName)
4557 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004558 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004559 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004560 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4561 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00004562
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004563 // FIXME: C++: Verify that MemberDecl isn't a static field.
4564 // FIXME: Verify that MemberDecl isn't a bitfield.
4565 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4566 // matter here.
4567 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004568 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004569 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004570 }
Mike Stump9afab102009-02-19 03:04:26 +00004571
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004572 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4573 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004574}
4575
4576
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004577Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4578 TypeTy *arg1,TypeTy *arg2,
4579 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00004580 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4581 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004582
Steve Naroff63bad2d2007-08-01 22:05:33 +00004583 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004584
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004585 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4586 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00004587}
4588
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004589Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4590 ExprArg cond,
4591 ExprArg expr1, ExprArg expr2,
4592 SourceLocation RPLoc) {
4593 Expr *CondExpr = static_cast<Expr*>(cond.get());
4594 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4595 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00004596
Steve Naroff93c53012007-08-03 21:21:27 +00004597 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4598
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004599 QualType resType;
4600 if (CondExpr->isValueDependent()) {
4601 resType = Context.DependentTy;
4602 } else {
4603 // The conditional expression is required to be a constant expression.
4604 llvm::APSInt condEval(32);
4605 SourceLocation ExpLoc;
4606 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004607 return ExprError(Diag(ExpLoc,
4608 diag::err_typecheck_choose_expr_requires_constant)
4609 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00004610
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004611 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4612 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4613 }
4614
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004615 cond.release(); expr1.release(); expr2.release();
4616 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4617 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00004618}
4619
Steve Naroff52a81c02008-09-03 18:15:37 +00004620//===----------------------------------------------------------------------===//
4621// Clang Extensions.
4622//===----------------------------------------------------------------------===//
4623
4624/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004625void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004626 // Analyze block parameters.
4627 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004628
Steve Naroff52a81c02008-09-03 18:15:37 +00004629 // Add BSI to CurBlock.
4630 BSI->PrevBlockInfo = CurBlock;
4631 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004632
Steve Naroff52a81c02008-09-03 18:15:37 +00004633 BSI->ReturnType = 0;
4634 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004635 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004636
Steve Naroff52059382008-10-10 01:28:17 +00004637 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004638 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004639}
4640
Mike Stumpc1fddff2009-02-04 22:31:32 +00004641void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4642 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4643
4644 if (ParamInfo.getNumTypeObjects() == 0
4645 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4646 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4647
4648 // The type is entirely optional as well, if none, use DependentTy.
4649 if (T.isNull())
4650 T = Context.DependentTy;
4651
4652 // The parameter list is optional, if there was none, assume ().
4653 if (!T->isFunctionType())
4654 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4655
4656 CurBlock->hasPrototype = true;
4657 CurBlock->isVariadic = false;
4658 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4659 .getTypePtr();
4660
4661 if (!RetTy->isDependentType())
4662 CurBlock->ReturnType = RetTy;
4663 return;
4664 }
4665
Steve Naroff52a81c02008-09-03 18:15:37 +00004666 // Analyze arguments to block.
4667 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4668 "Not a function declarator!");
4669 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004670
Steve Naroff52059382008-10-10 01:28:17 +00004671 CurBlock->hasPrototype = FTI.hasPrototype;
4672 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004673
Steve Naroff52a81c02008-09-03 18:15:37 +00004674 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4675 // no arguments, not a function that takes a single void argument.
4676 if (FTI.hasPrototype &&
4677 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00004678 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
4679 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004680 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004681 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004682 } else if (FTI.hasPrototype) {
4683 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00004684 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00004685 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004686 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4687
4688 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4689 .getTypePtr();
4690
4691 if (!RetTy->isDependentType())
4692 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004693 }
Steve Naroff494cb0f2009-03-13 16:56:44 +00004694 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
4695 CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004696
Steve Naroff52059382008-10-10 01:28:17 +00004697 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4698 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4699 // If this has an identifier, add it to the scope stack.
4700 if ((*AI)->getIdentifier())
4701 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004702}
4703
4704/// ActOnBlockError - If there is an error parsing a block, this callback
4705/// is invoked to pop the information about the block from the action impl.
4706void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4707 // Ensure that CurBlock is deleted.
4708 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004709
Steve Naroff52a81c02008-09-03 18:15:37 +00004710 // Pop off CurBlock, handle nested blocks.
4711 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004712
Steve Naroff52a81c02008-09-03 18:15:37 +00004713 // FIXME: Delete the ParmVarDecl objects as well???
Douglas Gregorc1408ea2009-03-11 23:54:15 +00004714
Steve Naroff52a81c02008-09-03 18:15:37 +00004715}
4716
4717/// ActOnBlockStmtExpr - This is called when the body of a block statement
4718/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004719Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4720 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00004721 // If blocks are disabled, emit an error.
4722 if (!LangOpts.Blocks)
4723 Diag(CaretLoc, diag::err_blocks_disable);
4724
Steve Naroff52a81c02008-09-03 18:15:37 +00004725 // Ensure that CurBlock is deleted.
4726 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00004727
Steve Naroff52059382008-10-10 01:28:17 +00004728 PopDeclContext();
4729
Steve Naroff52a81c02008-09-03 18:15:37 +00004730 // Pop off CurBlock, handle nested blocks.
4731 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004732
Steve Naroff52a81c02008-09-03 18:15:37 +00004733 QualType RetTy = Context.VoidTy;
4734 if (BSI->ReturnType)
4735 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004736
Steve Naroff52a81c02008-09-03 18:15:37 +00004737 llvm::SmallVector<QualType, 8> ArgTypes;
4738 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4739 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004740
Steve Naroff52a81c02008-09-03 18:15:37 +00004741 QualType BlockTy;
4742 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004743 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004744 else
4745 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004746 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004747
Eli Friedman2b128322009-03-23 00:24:07 +00004748 // FIXME: Check that return/parameter types are complete/non-abstract
4749
Steve Naroff52a81c02008-09-03 18:15:37 +00004750 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004751
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004752 BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4753 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4754 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00004755}
4756
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004757Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4758 ExprArg expr, TypeTy *type,
4759 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004760 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00004761 Expr *E = static_cast<Expr*>(expr.get());
4762 Expr *OrigExpr = E;
4763
Anders Carlsson36760332007-10-15 20:28:48 +00004764 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004765
4766 // Get the va_list type
4767 QualType VaListType = Context.getBuiltinVaListType();
4768 // Deal with implicit array decay; for example, on x86-64,
4769 // va_list is an array, but it's supposed to decay to
4770 // a pointer for va_arg.
4771 if (VaListType->isArrayType())
4772 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004773 // Make sure the input expression also decays appropriately.
4774 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004775
Chris Lattnercb9469d2009-04-06 17:07:34 +00004776 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004777 return ExprError(Diag(E->getLocStart(),
4778 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00004779 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00004780 }
Mike Stump9afab102009-02-19 03:04:26 +00004781
Eli Friedman2b128322009-03-23 00:24:07 +00004782 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00004783 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004784
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004785 expr.release();
4786 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4787 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00004788}
4789
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004790Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00004791 // The type of __null will be int or long, depending on the size of
4792 // pointers on the target.
4793 QualType Ty;
4794 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4795 Ty = Context.IntTy;
4796 else
4797 Ty = Context.LongTy;
4798
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004799 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00004800}
4801
Chris Lattner005ed752008-01-04 18:04:52 +00004802bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4803 SourceLocation Loc,
4804 QualType DstType, QualType SrcType,
4805 Expr *SrcExpr, const char *Flavor) {
4806 // Decode the result (notice that AST's are still created for extensions).
4807 bool isInvalid = false;
4808 unsigned DiagKind;
4809 switch (ConvTy) {
4810 default: assert(0 && "Unknown conversion type");
4811 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004812 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004813 DiagKind = diag::ext_typecheck_convert_pointer_int;
4814 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004815 case IntToPointer:
4816 DiagKind = diag::ext_typecheck_convert_int_pointer;
4817 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004818 case IncompatiblePointer:
4819 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4820 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00004821 case IncompatiblePointerSign:
4822 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
4823 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004824 case FunctionVoidPointer:
4825 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4826 break;
4827 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004828 // If the qualifiers lost were because we were applying the
4829 // (deprecated) C++ conversion from a string literal to a char*
4830 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4831 // Ideally, this check would be performed in
4832 // CheckPointerTypesForAssignment. However, that would require a
4833 // bit of refactoring (so that the second argument is an
4834 // expression, rather than a type), which should be done as part
4835 // of a larger effort to fix CheckPointerTypesForAssignment for
4836 // C++ semantics.
4837 if (getLangOptions().CPlusPlus &&
4838 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4839 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004840 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4841 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004842 case IntToBlockPointer:
4843 DiagKind = diag::err_int_to_block_pointer;
4844 break;
4845 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004846 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004847 break;
Steve Naroff19608432008-10-14 22:18:38 +00004848 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004849 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004850 // it can give a more specific diagnostic.
4851 DiagKind = diag::warn_incompatible_qualified_id;
4852 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004853 case IncompatibleVectors:
4854 DiagKind = diag::warn_incompatible_vectors;
4855 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004856 case Incompatible:
4857 DiagKind = diag::err_typecheck_convert_incompatible;
4858 isInvalid = true;
4859 break;
4860 }
Mike Stump9afab102009-02-19 03:04:26 +00004861
Chris Lattner271d4c22008-11-24 05:29:24 +00004862 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4863 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004864 return isInvalid;
4865}
Anders Carlssond5201b92008-11-30 19:50:32 +00004866
4867bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4868{
4869 Expr::EvalResult EvalResult;
4870
Mike Stump9afab102009-02-19 03:04:26 +00004871 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004872 EvalResult.HasSideEffects) {
4873 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4874
4875 if (EvalResult.Diag) {
4876 // We only show the note if it's not the usual "invalid subexpression"
4877 // or if it's actually in a subexpression.
4878 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4879 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4880 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4881 }
Mike Stump9afab102009-02-19 03:04:26 +00004882
Anders Carlssond5201b92008-11-30 19:50:32 +00004883 return true;
4884 }
4885
4886 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004887 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004888 E->getSourceRange();
4889
4890 // Print the reason it's not a constant.
4891 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4892 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4893 }
Mike Stump9afab102009-02-19 03:04:26 +00004894
Anders Carlssond5201b92008-11-30 19:50:32 +00004895 if (Result)
4896 *Result = EvalResult.Val.getInt();
4897 return false;
4898}