blob: f9d89fdb0be36698b61c8d019928223872c8200a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Douglas Gregor48f3bb92009-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 Lattner76a642f2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregor48f3bb92009-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 Lattnerf15970c2009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62 MD->isInstanceMethod());
63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64 }
65 }
66 }
67
68 if (!isSilenced)
Chris Lattner76a642f2009-02-15 22:43:40 +000069 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70 }
71
Douglas Gregor48f3bb92009-02-18 21:56:37 +000072 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000074 if (FD->isDeleted()) {
75 Diag(Loc, diag::err_deleted_function_use);
76 Diag(D->getLocation(), diag::note_unavailable_here) << true;
77 return true;
78 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000079 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000080
81 // See if the decl is unavailable
82 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner76a642f2009-02-15 22:43:40 +000083 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000084 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85 }
86
Douglas Gregor48f3bb92009-02-18 21:56:37 +000087 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000088}
89
Douglas Gregor4b2d3f72009-02-26 21:00:50 +000090SourceRange Sema::getExprRange(ExprTy *E) const {
91 Expr *Ex = (Expr *)E;
92 return Ex? Ex->getSourceRange() : SourceRange();
93}
94
Chris Lattnere7a2e912008-07-25 21:10:04 +000095//===----------------------------------------------------------------------===//
96// Standard Promotions and Conversions
97//===----------------------------------------------------------------------===//
98
Chris Lattnere7a2e912008-07-25 21:10:04 +000099/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
100void Sema::DefaultFunctionArrayConversion(Expr *&E) {
101 QualType Ty = E->getType();
102 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
103
Chris Lattnere7a2e912008-07-25 21:10:04 +0000104 if (Ty->isFunctionType())
105 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +0000106 else if (Ty->isArrayType()) {
107 // In C90 mode, arrays only promote to pointers if the array expression is
108 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
109 // type 'array of type' is converted to an expression that has type 'pointer
110 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
111 // that has type 'array of type' ...". The relevant change is "an lvalue"
112 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000113 //
114 // C++ 4.2p1:
115 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
116 // T" can be converted to an rvalue of type "pointer to T".
117 //
118 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
119 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +0000120 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
121 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000122}
123
124/// UsualUnaryConversions - Performs various conversions that are common to most
125/// operators (C99 6.3). The conversions of array and function types are
126/// sometimes surpressed. For example, the array->pointer conversion doesn't
127/// apply if the array is an argument to the sizeof or address (&) operators.
128/// In these instances, this routine should *not* be called.
129Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
130 QualType Ty = Expr->getType();
131 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
132
Chris Lattnere7a2e912008-07-25 21:10:04 +0000133 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
134 ImpCastExprToType(Expr, Context.IntTy);
135 else
136 DefaultFunctionArrayConversion(Expr);
137
138 return Expr;
139}
140
Chris Lattner05faf172008-07-25 22:25:12 +0000141/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
142/// do not have a prototype. Arguments that have type float are promoted to
143/// double. All other argument types are converted by UsualUnaryConversions().
144void Sema::DefaultArgumentPromotion(Expr *&Expr) {
145 QualType Ty = Expr->getType();
146 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
147
148 // If this is a 'float' (CVR qualified or typedef) promote to double.
149 if (const BuiltinType *BT = Ty->getAsBuiltinType())
150 if (BT->getKind() == BuiltinType::Float)
151 return ImpCastExprToType(Expr, Context.DoubleTy);
152
153 UsualUnaryConversions(Expr);
154}
155
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000156// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
157// will warn if the resulting type is not a POD type.
Chris Lattner76a642f2009-02-15 22:43:40 +0000158void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000159 DefaultArgumentPromotion(Expr);
160
161 if (!Expr->getType()->isPODType()) {
162 Diag(Expr->getLocStart(),
163 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
164 Expr->getType() << CT;
165 }
166}
167
168
Chris Lattnere7a2e912008-07-25 21:10:04 +0000169/// UsualArithmeticConversions - Performs various conversions that are common to
170/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
171/// routine returns the first non-arithmetic type found. The client is
172/// responsible for emitting appropriate error diagnostics.
173/// FIXME: verify the conversion rules for "complex int" are consistent with
174/// GCC.
175QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
176 bool isCompAssign) {
177 if (!isCompAssign) {
178 UsualUnaryConversions(lhsExpr);
179 UsualUnaryConversions(rhsExpr);
180 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000181
Chris Lattnere7a2e912008-07-25 21:10:04 +0000182 // For conversion purposes, we ignore any qualifiers.
183 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000184 QualType lhs =
185 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
186 QualType rhs =
187 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000188
189 // If both types are identical, no conversion is needed.
190 if (lhs == rhs)
191 return lhs;
192
193 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
194 // The caller can deal with this (e.g. pointer + int).
195 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
196 return lhs;
197
198 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
199 if (!isCompAssign) {
200 ImpCastExprToType(lhsExpr, destType);
201 ImpCastExprToType(rhsExpr, destType);
202 }
203 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 Lattner76a642f2009-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 Gregoreb8f3062008-11-12 17:17:38 +0000220
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000257 } else if (result < 0) { // The right side is bigger, convert lhs.
258 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000265 return rhs;
266 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-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 Carlsson5b1f3f02008-12-10 23:30:05 +0000275 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000276 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000277 return lhs;
278 }
Anders Carlsson5b1f3f02008-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 Lattnere7a2e912008-07-25 21:10:04 +0000284 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000285 return rhs;
286 }
Anders Carlsson5b1f3f02008-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 Lattnere7a2e912008-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 Lattner76a642f2009-02-15 22:43:40 +0000294 if (result > 0) // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000295 return lhs;
Chris Lattner76a642f2009-02-15 22:43:40 +0000296 assert(result < 0 && "illegal float comparison");
297 return rhs; // convert the lhs
Chris Lattnere7a2e912008-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 Lattner76a642f2009-02-15 22:43:40 +0000306 rhsComplexInt->getElementType()) >= 0)
307 return lhs; // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000308 return rhs;
309 } else if (lhsComplexInt && rhs->isIntegerType()) {
310 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000311 return lhs;
312 } else if (rhsComplexInt && lhs->isIntegerType()) {
313 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000342 return destType;
343}
344
345//===----------------------------------------------------------------------===//
346// Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
Steve Narofff69936d2007-09-16 03:34:24 +0000350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Redlcd965b92009-01-18 18:53:16 +0000355///
356Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 assert(NumStringToks && "Must have at least one string!");
359
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000360 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000362 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000363
364 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
365 for (unsigned i = 0; i != NumStringToks; ++i)
366 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000367
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000368 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000369 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-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 Redlcd965b92009-01-18 18:53:16 +0000375
Chris Lattnera7ad98f2008-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 Lattnerdbb1ecc2009-02-26 23:01:51 +0000380 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000381 ArrayType::Normal, 0);
Chris Lattner726e1682009-02-18 05:49:11 +0000382
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattner2085fd62009-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000389}
390
Chris Lattner639e2d32008-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 Naroff08d92e42007-09-15 18:49:24 +0000421/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000422/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000423/// identifier is used in a function call context.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000425/// class or namespace that the identifier must be a member of.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
427 IdentifierInfo &II,
428 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000429 const CXXScopeSpec *SS,
430 bool isAddressOfOperand) {
431 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor17330012009-02-04 15:01:18 +0000432 isAddressOfOperand);
Douglas Gregor10c42622008-11-18 15:03:34 +0000433}
434
Douglas Gregor1a49af92009-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 Redlebc07d52009-02-03 20:19:35 +0000438DeclRefExpr *
439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
440 bool TypeDependent, bool ValueDependent,
441 const CXXScopeSpec *SS) {
Steve Naroff6ece14c2009-01-21 00:14:39 +0000442 if (SS && !SS->isEmpty())
443 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Mike Stumpeed9cac2009-02-19 03:04:26 +0000444 ValueDependent,
445 SS->getRange().getBegin());
Steve Naroff6ece14c2009-01-21 00:14:39 +0000446 else
447 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000448}
449
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000453static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000454 assert(Record->isAnonymousStructOrUnion() &&
455 "Record must be an anonymous struct or union!");
456
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000457 // FIXME: Once Decls are directly linked together, this will
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000458 // be an O(1) operation rather than a slow walk through DeclContext's
459 // vector (which itself will be eliminated). DeclGroups might make
460 // this even better.
461 DeclContext *Ctx = Record->getDeclContext();
462 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
463 DEnd = Ctx->decls_end();
464 D != DEnd; ++D) {
465 if (*D == Record) {
466 // The object for the anonymous struct/union directly
467 // follows its type in the list of declarations.
468 ++D;
469 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000470 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000471 return *D;
472 }
473 }
474
475 assert(false && "Missing object for anonymous record");
476 return 0;
477}
478
Sebastian Redlcd965b92009-01-18 18:53:16 +0000479Sema::OwningExprResult
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000480Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
481 FieldDecl *Field,
482 Expr *BaseObjectExpr,
483 SourceLocation OpLoc) {
484 assert(Field->getDeclContext()->isRecord() &&
485 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
486 && "Field must be stored inside an anonymous struct or union");
487
488 // Construct the sequence of field member references
489 // we'll have to perform to get to the field in the anonymous
490 // union/struct. The list of members is built from the field
491 // outward, so traverse it backwards to go from an object in
492 // the current context to the field we found.
493 llvm::SmallVector<FieldDecl *, 4> AnonFields;
494 AnonFields.push_back(Field);
495 VarDecl *BaseObject = 0;
496 DeclContext *Ctx = Field->getDeclContext();
497 do {
498 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000499 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000500 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
501 AnonFields.push_back(AnonField);
502 else {
503 BaseObject = cast<VarDecl>(AnonObject);
504 break;
505 }
506 Ctx = Ctx->getParent();
507 } while (Ctx->isRecord() &&
508 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
509
510 // Build the expression that refers to the base object, from
511 // which we will build a sequence of member references to each
512 // of the anonymous union objects and, eventually, the field we
513 // found via name lookup.
514 bool BaseObjectIsPointer = false;
515 unsigned ExtraQuals = 0;
516 if (BaseObject) {
517 // BaseObject is an anonymous struct/union variable (and is,
518 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000519 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000520 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000521 SourceLocation());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000522 ExtraQuals
523 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
524 } else if (BaseObjectExpr) {
525 // The caller provided the base object expression. Determine
526 // whether its a pointer and whether it adds any qualifiers to the
527 // anonymous struct/union fields we're looking into.
528 QualType ObjectType = BaseObjectExpr->getType();
529 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
530 BaseObjectIsPointer = true;
531 ObjectType = ObjectPtr->getPointeeType();
532 }
533 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
534 } else {
535 // We've found a member of an anonymous struct/union that is
536 // inside a non-anonymous struct/union, so in a well-formed
537 // program our base object expression is "this".
538 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
539 if (!MD->isStatic()) {
540 QualType AnonFieldType
541 = Context.getTagDeclType(
542 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
543 QualType ThisType = Context.getTagDeclType(MD->getParent());
544 if ((Context.getCanonicalType(AnonFieldType)
545 == Context.getCanonicalType(ThisType)) ||
546 IsDerivedFrom(ThisType, AnonFieldType)) {
547 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000548 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000549 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000550 BaseObjectIsPointer = true;
551 }
552 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000553 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
554 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000555 }
556 ExtraQuals = MD->getTypeQualifiers();
557 }
558
559 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000560 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
561 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000562 }
563
564 // Build the implicit member references to the field of the
565 // anonymous struct/union.
566 Expr *Result = BaseObjectExpr;
567 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
568 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
569 FI != FIEnd; ++FI) {
570 QualType MemberType = (*FI)->getType();
571 if (!(*FI)->isMutable()) {
572 unsigned combinedQualifiers
573 = MemberType.getCVRQualifiers() | ExtraQuals;
574 MemberType = MemberType.getQualifiedType(combinedQualifiers);
575 }
Steve Naroff6ece14c2009-01-21 00:14:39 +0000576 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
577 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000578 BaseObjectIsPointer = false;
579 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000580 }
581
Sebastian Redlcd965b92009-01-18 18:53:16 +0000582 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000583}
584
Douglas Gregor10c42622008-11-18 15:03:34 +0000585/// ActOnDeclarationNameExpr - The parser has read some kind of name
586/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
587/// performs lookup on that name and returns an expression that refers
588/// to that name. This routine isn't directly called from the parser,
589/// because the parser doesn't know about DeclarationName. Rather,
590/// this routine is called by ActOnIdentifierExpr,
591/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
592/// which form the DeclarationName from the corresponding syntactic
593/// forms.
594///
595/// HasTrailingLParen indicates whether this identifier is used in a
596/// function call context. LookupCtx is only used for a C++
597/// qualified-id (foo::bar) to indicate the class or namespace that
598/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000599///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000600/// isAddressOfOperand means that this expression is the direct operand
601/// of an address-of operator. This matters because this is the only
602/// situation where a qualified name referencing a non-static member may
603/// appear outside a member function of this class.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000604Sema::OwningExprResult
605Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
606 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +0000607 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000608 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000609 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000610 if (SS && SS->isInvalid())
611 return ExprError();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000612 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
613 false, true, Loc);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000614
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000615 NamedDecl *D = 0;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000616 if (Lookup.isAmbiguous()) {
617 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
618 SS && SS->isSet() ? SS->getRange()
619 : SourceRange());
620 return ExprError();
621 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +0000622 D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000623
Chris Lattner8a934232008-03-31 00:36:02 +0000624 // If this reference is in an Objective-C method, then ivar lookup happens as
625 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000626 IdentifierInfo *II = Name.getAsIdentifierInfo();
627 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000628 // There are two cases to handle here. 1) scoped lookup could have failed,
629 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000630 // found a decl, but that decl is outside the current instance method (i.e.
631 // a global variable). In these two cases, we do a lookup for an ivar with
632 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000633 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000634 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000635 ObjCInterfaceDecl *ClassDeclared;
636 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000637 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000638 if (DiagnoseUseOfDecl(IV, Loc))
639 return ExprError();
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000640 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
641 // If a class method attemps to use a free standing ivar, this is
642 // an error.
643 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
644 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
645 << IV->getDeclName());
646 // If a class method uses a global variable, even if an ivar with
647 // same name exists, use the global.
648 if (!IsClsMethod) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000649 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
650 ClassDeclared != IFace)
651 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000652 // FIXME: This should use a new expr for a direct reference, don't turn
653 // this into Self->ivar, just return a BareIVarExpr or something.
654 IdentifierInfo &II = Context.Idents.get("self");
655 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
656 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
657 Loc, static_cast<Expr*>(SelfExpr.release()),
658 true, true);
659 Context.setFieldDecl(IFace, IV, MRef);
660 return Owned(MRef);
661 }
Chris Lattner8a934232008-03-31 00:36:02 +0000662 }
663 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000664 else if (getCurMethodDecl()->isInstanceMethod()) {
665 // We should warn if a local variable hides an ivar.
666 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000667 ObjCInterfaceDecl *ClassDeclared;
668 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
669 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
670 IFace == ClassDeclared)
671 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
672 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000673 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000674 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000675 if (D == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000676 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000677 getCurMethodDecl()->getClassInterface()));
Steve Naroff6ece14c2009-01-21 00:14:39 +0000678 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000679 }
Chris Lattner8a934232008-03-31 00:36:02 +0000680 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000681
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000682 // Determine whether this name might be a candidate for
683 // argument-dependent lookup.
684 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
685 HasTrailingLParen;
686
687 if (ADL && D == 0) {
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000688 // We've seen something of the form
689 //
690 // identifier(
691 //
692 // and we did not find any entity by the name
693 // "identifier". However, this identifier is still subject to
694 // argument-dependent lookup, so keep track of the name.
695 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
696 Context.OverloadTy,
697 Loc));
698 }
699
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 if (D == 0) {
701 // Otherwise, this could be an implicitly declared function reference (legal
702 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000703 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000704 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000705 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 else {
707 // If this name wasn't predeclared and if this is not a function call,
708 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000709 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000710 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
711 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000712 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
713 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000714 return ExprError(Diag(Loc, diag::err_undeclared_use)
715 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000716 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000717 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 }
719 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000720
Sebastian Redlebc07d52009-02-03 20:19:35 +0000721 // If this is an expression of the form &Class::member, don't build an
722 // implicit member ref, because we want a pointer to the member in general,
723 // not any specific instance's member.
724 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000725 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000726 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000727 QualType DType;
728 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
729 DType = FD->getType().getNonReferenceType();
730 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
731 DType = Method->getType();
732 } else if (isa<OverloadedFunctionDecl>(D)) {
733 DType = Context.OverloadTy;
734 }
735 // Could be an inner type. That's diagnosed below, so ignore it here.
736 if (!DType.isNull()) {
737 // The pointer is type- and value-dependent if it points into something
738 // dependent.
739 bool Dependent = false;
740 for (; DC; DC = DC->getParent()) {
741 // FIXME: could stop early at namespace scope.
742 if (DC->isRecord()) {
743 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
744 if (Context.getTypeDeclType(Record)->isDependentType()) {
745 Dependent = true;
746 break;
747 }
748 }
749 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000750 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redlebc07d52009-02-03 20:19:35 +0000751 }
752 }
753 }
754
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000755 // We may have found a field within an anonymous union or struct
756 // (C++ [class.union]).
757 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
758 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
759 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000760
Douglas Gregor88a35142008-12-22 05:46:06 +0000761 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
762 if (!MD->isStatic()) {
763 // C++ [class.mfct.nonstatic]p2:
764 // [...] if name lookup (3.4.1) resolves the name in the
765 // id-expression to a nonstatic nontype member of class X or of
766 // a base class of X, the id-expression is transformed into a
767 // class member access expression (5.2.5) using (*this) (9.3.2)
768 // as the postfix-expression to the left of the '.' operator.
769 DeclContext *Ctx = 0;
770 QualType MemberType;
771 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
772 Ctx = FD->getDeclContext();
773 MemberType = FD->getType();
774
775 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
776 MemberType = RefType->getPointeeType();
777 else if (!FD->isMutable()) {
778 unsigned combinedQualifiers
779 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
780 MemberType = MemberType.getQualifiedType(combinedQualifiers);
781 }
782 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
783 if (!Method->isStatic()) {
784 Ctx = Method->getParent();
785 MemberType = Method->getType();
786 }
787 } else if (OverloadedFunctionDecl *Ovl
788 = dyn_cast<OverloadedFunctionDecl>(D)) {
789 for (OverloadedFunctionDecl::function_iterator
790 Func = Ovl->function_begin(),
791 FuncEnd = Ovl->function_end();
792 Func != FuncEnd; ++Func) {
793 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
794 if (!DMethod->isStatic()) {
795 Ctx = Ovl->getDeclContext();
796 MemberType = Context.OverloadTy;
797 break;
798 }
799 }
800 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000801
802 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000803 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
804 QualType ThisType = Context.getTagDeclType(MD->getParent());
805 if ((Context.getCanonicalType(CtxType)
806 == Context.getCanonicalType(ThisType)) ||
807 IsDerivedFrom(ThisType, CtxType)) {
808 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000809 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000810 MD->getThisType(Context));
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000811 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stumpeed9cac2009-02-19 03:04:26 +0000812 SourceLocation(), MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000813 }
814 }
815 }
816 }
817
Douglas Gregor44b43212008-12-11 16:49:14 +0000818 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000819 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
820 if (MD->isStatic())
821 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000822 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
823 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000824 }
825
Douglas Gregor88a35142008-12-22 05:46:06 +0000826 // Any other ways we could have found the field in a well-formed
827 // program would have been turned into implicit member expressions
828 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000829 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
830 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000831 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000832
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000834 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000835 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000836 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000837 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000838 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000839
Steve Naroffdd972f22008-09-05 22:11:13 +0000840 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000841 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000842 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
843 false, false, SS));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000844 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
845 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
846 false, false, SS));
Steve Naroffdd972f22008-09-05 22:11:13 +0000847 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000848
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000849 // Check whether this declaration can be used. Note that we suppress
850 // this check when we're going to perform argument-dependent lookup
851 // on this function name, because this might not be the function
852 // that overload resolution actually selects.
853 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
854 return ExprError();
855
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000856 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000857 // Warn about constructs like:
858 // if (void *X = foo()) { ... } else { X }.
859 // In the else block, the pointer is always false.
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000860 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
861 Scope *CheckS = S;
862 while (CheckS) {
863 if (CheckS->isWithinElse() &&
864 CheckS->getControlParent()->isDeclScope(Var)) {
865 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000866 ExprError(Diag(Loc, diag::warn_value_always_false)
867 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000868 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000869 ExprError(Diag(Loc, diag::warn_value_always_zero)
870 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000871 break;
872 }
873
874 // Move up one more control parent to check again.
875 CheckS = CheckS->getControlParent();
876 if (CheckS)
877 CheckS = CheckS->getParent();
878 }
879 }
Douglas Gregor2224f842009-02-25 16:33:18 +0000880 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
881 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
882 // C99 DR 316 says that, if a function type comes from a
883 // function definition (without a prototype), that type is only
884 // used for checking compatibility. Therefore, when referencing
885 // the function, we pretend that we don't have the full function
886 // type.
887 QualType T = Func->getType();
888 QualType NoProtoType = T;
Douglas Gregor72564e72009-02-26 23:50:07 +0000889 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
890 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor2224f842009-02-25 16:33:18 +0000891 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
892 }
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000893 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000894
895 // Only create DeclRefExpr's for valid Decl's.
896 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000897 return ExprError();
898
Chris Lattner639e2d32008-10-20 05:16:36 +0000899 // If the identifier reference is inside a block, and it refers to a value
900 // that is outside the block, create a BlockDeclRefExpr instead of a
901 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
902 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000903 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000904 // We do not do this for things like enum constants, global variables, etc,
905 // as they do not get snapshotted.
906 //
907 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpb83d2872009-02-19 22:01:56 +0000908 // Blocks that have these can't be constant.
909 CurBlock->hasBlockDeclRefExprs = true;
910
Steve Naroff090276f2008-10-10 01:28:17 +0000911 // The BlocksAttr indicates the variable is bound by-reference.
912 if (VD->getAttr<BlocksAttr>())
Steve Naroff6ece14c2009-01-21 00:14:39 +0000913 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000914 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000915
Steve Naroff090276f2008-10-10 01:28:17 +0000916 // Variable will be bound by-copy, make it const within the closure.
917 VD->getType().addConst();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000918 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000919 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +0000920 }
921 // If this reference is not in a block or if the referenced variable is
922 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000923
Douglas Gregor898574e2008-12-05 23:32:09 +0000924 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000925 bool ValueDependent = false;
926 if (getLangOptions().CPlusPlus) {
927 // C++ [temp.dep.expr]p3:
928 // An id-expression is type-dependent if it contains:
929 // - an identifier that was declared with a dependent type,
930 if (VD->getType()->isDependentType())
931 TypeDependent = true;
932 // - FIXME: a template-id that is dependent,
933 // - a conversion-function-id that specifies a dependent type,
934 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
935 Name.getCXXNameType()->isDependentType())
936 TypeDependent = true;
937 // - a nested-name-specifier that contains a class-name that
938 // names a dependent type.
939 else if (SS && !SS->isEmpty()) {
940 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
941 DC; DC = DC->getParent()) {
942 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000943 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000944 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
945 if (Context.getTypeDeclType(Record)->isDependentType()) {
946 TypeDependent = true;
947 break;
948 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000949 }
950 }
951 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000952
Douglas Gregor83f96f62008-12-10 20:57:37 +0000953 // C++ [temp.dep.constexpr]p2:
954 //
955 // An identifier is value-dependent if it is:
956 // - a name declared with a dependent type,
957 if (TypeDependent)
958 ValueDependent = true;
959 // - the name of a non-type template parameter,
960 else if (isa<NonTypeTemplateParmDecl>(VD))
961 ValueDependent = true;
962 // - a constant with integral or enumeration type and is
963 // initialized with an expression that is value-dependent
964 // (FIXME!).
965 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000966
Sebastian Redlcd965b92009-01-18 18:53:16 +0000967 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
968 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000969}
970
Sebastian Redlcd965b92009-01-18 18:53:16 +0000971Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
972 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000973 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000974
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000976 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000977 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
978 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
979 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000981
Chris Lattnerfa28b302008-01-12 08:14:25 +0000982 // Pre-defined identifiers are of type char[x], where x is the length of the
983 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000984 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000985 if (FunctionDecl *FD = getCurFunctionDecl())
986 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000987 else if (ObjCMethodDecl *MD = getCurMethodDecl())
988 Length = MD->getSynthesizedMethodSize();
989 else {
990 Diag(Loc, diag::ext_predef_outside_function);
991 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
992 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
993 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000994
995
Chris Lattner8f978d52008-01-12 19:32:28 +0000996 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000997 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000998 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000999 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001000}
1001
Sebastian Redlcd965b92009-01-18 18:53:16 +00001002Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 llvm::SmallString<16> CharBuffer;
1004 CharBuffer.resize(Tok.getLength());
1005 const char *ThisTokBegin = &CharBuffer[0];
1006 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001007
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1009 Tok.getLocation(), PP);
1010 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001011 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001012
1013 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1014
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001015 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1016 Literal.isWide(),
1017 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001018}
1019
Sebastian Redlcd965b92009-01-18 18:53:16 +00001020Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1021 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1023 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001024 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001025 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001026 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001027 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 }
Ted Kremenek28396602009-01-13 23:19:12 +00001029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001031 // Add padding so that NumericLiteralParser can overread by one character.
1032 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001034
Reid Spencer5f016e22007-07-11 17:01:13 +00001035 // Get the spelling of the token, which eliminates trigraphs, etc.
1036 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001037
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1039 Tok.getLocation(), PP);
1040 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001041 return ExprError();
1042
Chris Lattner5d661452007-08-26 03:42:43 +00001043 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001044
Chris Lattner5d661452007-08-26 03:42:43 +00001045 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001046 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001047 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001048 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001049 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001050 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001051 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001052 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001053
1054 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1055
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001056 // isExact will be set by GetFloatValue().
1057 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001058 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1059 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001060
Chris Lattner5d661452007-08-26 03:42:43 +00001061 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001062 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001063 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001064 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001065
Neil Boothb9449512007-08-29 22:00:19 +00001066 // long long is a C99 feature.
1067 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001068 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001069 Diag(Tok.getLocation(), diag::ext_longlong);
1070
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001072 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 if (Literal.GetIntegerValue(ResultVal)) {
1075 // If this value didn't fit into uintmax_t, warn and force to ull.
1076 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001077 Ty = Context.UnsignedLongLongTy;
1078 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001079 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001080 } else {
1081 // If this value fits into a ULL, try to figure out what else it fits into
1082 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001083
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1085 // be an unsigned int.
1086 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1087
1088 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001089 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001090 if (!Literal.isLong && !Literal.isLongLong) {
1091 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001092 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001093
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 // Does it fit in a unsigned int?
1095 if (ResultVal.isIntN(IntSize)) {
1096 // Does it fit in a signed int?
1097 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001098 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001100 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001101 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001104
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001106 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001107 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001108
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 // Does it fit in a unsigned long?
1110 if (ResultVal.isIntN(LongSize)) {
1111 // Does it fit in a signed long?
1112 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001113 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001115 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001116 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001118 }
1119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001121 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001122 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001123
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 // Does it fit in a unsigned long long?
1125 if (ResultVal.isIntN(LongLongSize)) {
1126 // Does it fit in a signed long long?
1127 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001128 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001130 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001131 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 }
1133 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001134
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 // If we still couldn't decide a type, we probably have something that
1136 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001137 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001139 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001140 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001142
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001143 if (ResultVal.getBitWidth() != Width)
1144 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001146 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001148
Chris Lattner5d661452007-08-26 03:42:43 +00001149 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1150 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001151 Res = new (Context) ImaginaryLiteral(Res,
1152 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001153
1154 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001155}
1156
Sebastian Redlcd965b92009-01-18 18:53:16 +00001157Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1158 SourceLocation R, ExprArg Val) {
1159 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001160 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001161 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001162}
1163
1164/// The UsualUnaryConversions() function is *not* called by this routine.
1165/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001166bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001167 SourceLocation OpLoc,
1168 const SourceRange &ExprRange,
1169 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001170 if (exprType->isDependentType())
1171 return false;
1172
Reid Spencer5f016e22007-07-11 17:01:13 +00001173 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001174 if (isa<FunctionType>(exprType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 // alignof(function) is allowed.
Chris Lattner01072922009-01-24 19:46:37 +00001176 if (isSizeof)
1177 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1178 return false;
1179 }
1180
1181 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001182 Diag(OpLoc, diag::ext_sizeof_void_type)
1183 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001184 return false;
1185 }
Sebastian Redl05189992008-11-11 17:56:53 +00001186
Chris Lattner01072922009-01-24 19:46:37 +00001187 return DiagnoseIncompleteType(OpLoc, exprType,
1188 isSizeof ? diag::err_sizeof_incomplete_type :
1189 diag::err_alignof_incomplete_type,
1190 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +00001191}
1192
Chris Lattner31e21e02009-01-24 20:17:12 +00001193bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1194 const SourceRange &ExprRange) {
1195 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001196
Chris Lattner31e21e02009-01-24 20:17:12 +00001197 // alignof decl is always ok.
1198 if (isa<DeclRefExpr>(E))
1199 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001200
1201 // Cannot know anything else if the expression is dependent.
1202 if (E->isTypeDependent())
1203 return false;
1204
Chris Lattner31e21e02009-01-24 20:17:12 +00001205 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1206 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1207 if (FD->isBitField()) {
Chris Lattnerda027472009-01-24 21:29:22 +00001208 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner31e21e02009-01-24 20:17:12 +00001209 return true;
1210 }
1211 // Other fields are ok.
1212 return false;
1213 }
1214 }
1215 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1216}
1217
Sebastian Redl05189992008-11-11 17:56:53 +00001218/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1219/// the same for @c alignof and @c __alignof
1220/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001221Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001222Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1223 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001225 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001226
Sebastian Redl05189992008-11-11 17:56:53 +00001227 QualType ArgTy;
1228 SourceRange Range;
1229 if (isType) {
1230 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1231 Range = ArgRange;
Chris Lattner694b1e42009-01-24 19:49:13 +00001232
1233 // Verify that the operand is valid.
1234 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1235 return ExprError();
Sebastian Redl05189992008-11-11 17:56:53 +00001236 } else {
1237 // Get the end location.
1238 Expr *ArgEx = (Expr *)TyOrEx;
1239 Range = ArgEx->getSourceRange();
1240 ArgTy = ArgEx->getType();
Chris Lattner694b1e42009-01-24 19:49:13 +00001241
1242 // Verify that the operand is valid.
Chris Lattner31e21e02009-01-24 20:17:12 +00001243 bool isInvalid;
Chris Lattnerda027472009-01-24 21:29:22 +00001244 if (!isSizeof) {
Chris Lattner31e21e02009-01-24 20:17:12 +00001245 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattnerda027472009-01-24 21:29:22 +00001246 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1247 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1248 isInvalid = true;
1249 } else {
1250 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1251 }
Chris Lattner31e21e02009-01-24 20:17:12 +00001252
1253 if (isInvalid) {
Chris Lattner694b1e42009-01-24 19:49:13 +00001254 DeleteExpr(ArgEx);
1255 return ExprError();
1256 }
Sebastian Redl05189992008-11-11 17:56:53 +00001257 }
1258
Sebastian Redl05189992008-11-11 17:56:53 +00001259 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001260 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner01072922009-01-24 19:46:37 +00001261 Context.getSizeType(), OpLoc,
1262 Range.getEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001263}
1264
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001265QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001266 if (V->isTypeDependent())
1267 return Context.DependentTy;
1268
Chris Lattnerdbb36972007-08-24 21:16:53 +00001269 DefaultFunctionArrayConversion(V);
1270
Chris Lattnercc26ed72007-08-26 05:39:26 +00001271 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001272 if (const ComplexType *CT = V->getType()->getAsComplexType())
1273 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001274
1275 // Otherwise they pass through real integer and floating point types here.
1276 if (V->getType()->isArithmeticType())
1277 return V->getType();
1278
1279 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001280 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1281 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001282 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001283}
1284
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286
Sebastian Redl0eb23302009-01-19 00:08:26 +00001287Action::OwningExprResult
1288Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1289 tok::TokenKind Kind, ExprArg Input) {
1290 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001291
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 UnaryOperator::Opcode Opc;
1293 switch (Kind) {
1294 default: assert(0 && "Unknown unary op!");
1295 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1296 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1297 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001298
Douglas Gregor74253732008-11-19 15:42:04 +00001299 if (getLangOptions().CPlusPlus &&
1300 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1301 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001302 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001303 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1304
1305 // C++ [over.inc]p1:
1306 //
1307 // [...] If the function is a member function with one
1308 // parameter (which shall be of type int) or a non-member
1309 // function with two parameters (the second of which shall be
1310 // of type int), it defines the postfix increment operator ++
1311 // for objects of that type. When the postfix increment is
1312 // called as a result of using the ++ operator, the int
1313 // argument will have value zero.
1314 Expr *Args[2] = {
1315 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001316 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1317 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001318 };
1319
1320 // Build the candidate set for overloading
1321 OverloadCandidateSet CandidateSet;
Douglas Gregorf680a0f2009-02-04 16:44:47 +00001322 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1323 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001324
1325 // Perform overload resolution.
1326 OverloadCandidateSet::iterator Best;
1327 switch (BestViableFunction(CandidateSet, Best)) {
1328 case OR_Success: {
1329 // We found a built-in operator or an overloaded operator.
1330 FunctionDecl *FnDecl = Best->Function;
1331
1332 if (FnDecl) {
1333 // We matched an overloaded operator. Build a call to that
1334 // operator.
1335
1336 // Convert the arguments.
1337 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1338 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001339 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001340 } else {
1341 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001342 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001343 FnDecl->getParamDecl(0)->getType(),
1344 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001345 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001346 }
1347
1348 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001349 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001350 = FnDecl->getType()->getAsFunctionType()->getResultType();
1351 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001352
Douglas Gregor74253732008-11-19 15:42:04 +00001353 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001354 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump488e25b2009-02-19 02:54:59 +00001355 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00001356 UsualUnaryConversions(FnExpr);
1357
Sebastian Redl0eb23302009-01-19 00:08:26 +00001358 Input.release();
Ted Kremenek668bf912009-02-09 20:51:47 +00001359 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1360 ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001361 } else {
1362 // We matched a built-in operator. Convert the arguments, then
1363 // break out so that we will build the appropriate built-in
1364 // operator node.
1365 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1366 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001367 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001368
1369 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001370 }
Douglas Gregor74253732008-11-19 15:42:04 +00001371 }
1372
1373 case OR_No_Viable_Function:
1374 // No viable function; fall through to handling this as a
1375 // built-in operator, which will produce an error message for us.
1376 break;
1377
1378 case OR_Ambiguous:
1379 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1380 << UnaryOperator::getOpcodeStr(Opc)
1381 << Arg->getSourceRange();
1382 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001383 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001384
1385 case OR_Deleted:
1386 Diag(OpLoc, diag::err_ovl_deleted_oper)
1387 << Best->Function->isDeleted()
1388 << UnaryOperator::getOpcodeStr(Opc)
1389 << Arg->getSourceRange();
1390 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1391 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001392 }
1393
1394 // Either we found no viable overloaded operator or we matched a
1395 // built-in operator. In either case, fall through to trying to
1396 // build a built-in operation.
1397 }
1398
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001399 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1400 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001402 return ExprError();
1403 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001404 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001405}
1406
Sebastian Redl0eb23302009-01-19 00:08:26 +00001407Action::OwningExprResult
1408Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1409 ExprArg Idx, SourceLocation RLoc) {
1410 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1411 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001412
Douglas Gregor337c6b92008-11-19 17:17:41 +00001413 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001414 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001415 LHSExp->getType()->isEnumeralType() ||
1416 RHSExp->getType()->isRecordType() ||
1417 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001418 // Add the appropriate overloaded operators (C++ [over.match.oper])
1419 // to the candidate set.
1420 OverloadCandidateSet CandidateSet;
1421 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregorf680a0f2009-02-04 16:44:47 +00001422 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1423 SourceRange(LLoc, RLoc)))
1424 return ExprError();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001425
Douglas Gregor337c6b92008-11-19 17:17:41 +00001426 // Perform overload resolution.
1427 OverloadCandidateSet::iterator Best;
1428 switch (BestViableFunction(CandidateSet, Best)) {
1429 case OR_Success: {
1430 // We found a built-in operator or an overloaded operator.
1431 FunctionDecl *FnDecl = Best->Function;
1432
1433 if (FnDecl) {
1434 // We matched an overloaded operator. Build a call to that
1435 // operator.
1436
1437 // Convert the arguments.
1438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1439 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1440 PerformCopyInitialization(RHSExp,
1441 FnDecl->getParamDecl(0)->getType(),
1442 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001443 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001444 } else {
1445 // Convert the arguments.
1446 if (PerformCopyInitialization(LHSExp,
1447 FnDecl->getParamDecl(0)->getType(),
1448 "passing") ||
1449 PerformCopyInitialization(RHSExp,
1450 FnDecl->getParamDecl(1)->getType(),
1451 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001452 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001453 }
1454
1455 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001456 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001457 = FnDecl->getType()->getAsFunctionType()->getResultType();
1458 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001459
Douglas Gregor337c6b92008-11-19 17:17:41 +00001460 // Build the actual expression node.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001461 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1462 SourceLocation());
Douglas Gregor337c6b92008-11-19 17:17:41 +00001463 UsualUnaryConversions(FnExpr);
1464
Sebastian Redl0eb23302009-01-19 00:08:26 +00001465 Base.release();
1466 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001467 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001468 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001469 } else {
1470 // We matched a built-in operator. Convert the arguments, then
1471 // break out so that we will build the appropriate built-in
1472 // operator node.
1473 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1474 "passing") ||
1475 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1476 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001477 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001478
1479 break;
1480 }
1481 }
1482
1483 case OR_No_Viable_Function:
1484 // No viable function; fall through to handling this as a
1485 // built-in operator, which will produce an error message for us.
1486 break;
1487
1488 case OR_Ambiguous:
1489 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1490 << "[]"
1491 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1492 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001493 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001494
1495 case OR_Deleted:
1496 Diag(LLoc, diag::err_ovl_deleted_oper)
1497 << Best->Function->isDeleted()
1498 << "[]"
1499 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1500 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1501 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001502 }
1503
1504 // Either we found no viable overloaded operator or we matched a
1505 // built-in operator. In either case, fall through to trying to
1506 // build a built-in operation.
1507 }
1508
Chris Lattner12d9ff62007-07-16 00:14:47 +00001509 // Perform default conversions.
1510 DefaultFunctionArrayConversion(LHSExp);
1511 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001512
Chris Lattner12d9ff62007-07-16 00:14:47 +00001513 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001516 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001517 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001519 Expr *BaseExpr, *IndexExpr;
1520 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001521 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1522 BaseExpr = LHSExp;
1523 IndexExpr = RHSExp;
1524 ResultType = Context.DependentTy;
1525 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001526 BaseExpr = LHSExp;
1527 IndexExpr = RHSExp;
1528 // FIXME: need to deal with const...
1529 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001530 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001531 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001532 BaseExpr = RHSExp;
1533 IndexExpr = LHSExp;
1534 // FIXME: need to deal with const...
1535 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001536 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1537 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001538 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001539
Chris Lattner12d9ff62007-07-16 00:14:47 +00001540 // FIXME: need to deal with const...
1541 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001543 return ExprError(Diag(LHSExp->getLocStart(),
1544 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1545 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 // C99 6.5.2.1p1
Sebastian Redl28507842009-02-26 14:39:58 +00001547 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001548 return ExprError(Diag(IndexExpr->getLocStart(),
1549 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001550
Chris Lattner12d9ff62007-07-16 00:14:47 +00001551 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1552 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001553 // void (*)(int)) and pointers to incomplete types. Functions are not
1554 // objects in C99.
Sebastian Redl28507842009-02-26 14:39:58 +00001555 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001556 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001557 diag::err_typecheck_subscript_not_object)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001558 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001559
Sebastian Redl0eb23302009-01-19 00:08:26 +00001560 Base.release();
1561 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001562 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001563 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001564}
1565
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001566QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001567CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001568 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001569 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001570
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001571 // The vector accessor can't exceed the number of elements.
1572 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001573
Mike Stumpeed9cac2009-02-19 03:04:26 +00001574 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001575 // special names that indicate a subset of exactly half the elements are
1576 // to be selected.
1577 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001578
Nate Begeman353417a2009-01-18 01:47:54 +00001579 // This flag determines whether or not CompName has an 's' char prefix,
1580 // indicating that it is a string of hex values to be used as vector indices.
1581 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001582
1583 // Check that we've found one of the special components, or that the component
1584 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001585 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001586 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1587 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001588 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001589 do
1590 compStr++;
1591 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001592 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001593 do
1594 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001595 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001596 }
Nate Begeman353417a2009-01-18 01:47:54 +00001597
Mike Stumpeed9cac2009-02-19 03:04:26 +00001598 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001599 // We didn't get to the end of the string. This means the component names
1600 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001601 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1602 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001603 return QualType();
1604 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001605
Nate Begeman353417a2009-01-18 01:47:54 +00001606 // Ensure no component accessor exceeds the width of the vector type it
1607 // operates on.
1608 if (!HalvingSwizzle) {
1609 compStr = CompName.getName();
1610
1611 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001612 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001613
1614 while (*compStr) {
1615 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1616 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1617 << baseType << SourceRange(CompLoc);
1618 return QualType();
1619 }
1620 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001621 }
Nate Begeman8a997642008-05-09 06:41:27 +00001622
Nate Begeman353417a2009-01-18 01:47:54 +00001623 // If this is a halving swizzle, verify that the base type has an even
1624 // number of elements.
1625 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001626 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001627 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001628 return QualType();
1629 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001630
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001631 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001632 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001633 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001634 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001635 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001636 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1637 : CompName.getLength();
1638 if (HexSwizzle)
1639 CompSize--;
1640
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001641 if (CompSize == 1)
1642 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001643
Nate Begeman213541a2008-04-18 23:10:10 +00001644 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001645 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001646 // diagostics look bad. We want extended vector types to appear built-in.
1647 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1648 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1649 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001650 }
1651 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001652}
1653
Chris Lattner76a642f2009-02-15 22:43:40 +00001654
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001655/// constructSetterName - Return the setter name for the given
1656/// identifier, i.e. "set" + Name where the initial character of Name
1657/// has been capitalized.
1658// FIXME: Merge with same routine in Parser. But where should this
1659// live?
1660static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1661 const IdentifierInfo *Name) {
1662 llvm::SmallString<100> SelectorName;
1663 SelectorName = "set";
1664 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1665 SelectorName[3] = toupper(SelectorName[3]);
1666 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1667}
1668
Steve Naroffb06d8752009-03-04 18:34:24 +00001669ObjCImplementationDecl *getCurImplementationDecl(DeclContext *DC) {
1670 while (DC && !isa<ObjCImplementationDecl>(DC))
1671 DC = DC->getParent();
1672 return dyn_cast_or_null<ObjCImplementationDecl>(DC);
1673}
1674
Sebastian Redl0eb23302009-01-19 00:08:26 +00001675Action::OwningExprResult
1676Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1677 tok::TokenKind OpKind, SourceLocation MemberLoc,
1678 IdentifierInfo &Member) {
1679 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001680 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001681
1682 // Perform default conversions.
1683 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001684
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001685 QualType BaseType = BaseExpr->getType();
1686 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001687
Chris Lattner68a057b2008-07-21 04:36:39 +00001688 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1689 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001691 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001692 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001693 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001694 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1695 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001696 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001697 return ExprError(Diag(MemberLoc,
1698 diag::err_typecheck_member_reference_arrow)
1699 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001701
Chris Lattner68a057b2008-07-21 04:36:39 +00001702 // Handle field access to simple records. This also handles access to fields
1703 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001704 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001705 RecordDecl *RDecl = RTy->getDecl();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001706 if (DiagnoseIncompleteType(OpLoc, BaseType,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001707 diag::err_typecheck_incomplete_tag,
1708 BaseExpr->getSourceRange()))
1709 return ExprError();
1710
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001711 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001712 // FIXME: Qualified name lookup for C++ is a bit more complicated
1713 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001714 LookupResult Result
Mike Stumpeed9cac2009-02-19 03:04:26 +00001715 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001716 LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001717
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001718 NamedDecl *MemberDecl = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001719 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001720 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1721 << &Member << BaseExpr->getSourceRange());
1722 else if (Result.isAmbiguous()) {
1723 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1724 MemberLoc, BaseExpr->getSourceRange());
1725 return ExprError();
1726 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001727 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001728
Chris Lattner56cd21b2009-02-13 22:08:30 +00001729 // If the decl being referenced had an error, return an error for this
1730 // sub-expr without emitting another error, in order to avoid cascading
1731 // error cases.
1732 if (MemberDecl->isInvalidDecl())
1733 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001734
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001735 // Check the use of this field
1736 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1737 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00001738
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001739 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001740 // We may have found a field within an anonymous union or struct
1741 // (C++ [class.union]).
1742 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001743 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001744 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001745
Douglas Gregor86f19402008-12-20 23:49:58 +00001746 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1747 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001748 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001749 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1750 MemberType = Ref->getPointeeType();
1751 else {
1752 unsigned combinedQualifiers =
1753 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001754 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001755 combinedQualifiers &= ~QualType::Const;
1756 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1757 }
Eli Friedman51019072008-02-06 22:48:16 +00001758
Steve Naroff6ece14c2009-01-21 00:14:39 +00001759 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1760 MemberLoc, MemberType));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001761 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001762 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001763 Var, MemberLoc,
1764 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001765 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00001766 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001767 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001768 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001769 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001770 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001771 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001772 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00001773 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1774 Enum, MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001775 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001776 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1777 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001778
Douglas Gregor86f19402008-12-20 23:49:58 +00001779 // We found a declaration kind that we didn't expect. This is a
1780 // generic error message that tells the user that she can't refer
1781 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001782 return ExprError(Diag(MemberLoc,
1783 diag::err_typecheck_member_reference_unknown)
1784 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001785 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001786
Chris Lattnera38e6b12008-07-21 04:59:05 +00001787 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1788 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001789 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001790 ObjCInterfaceDecl *ClassDeclared;
1791 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1792 ClassDeclared)) {
Chris Lattner56cd21b2009-02-13 22:08:30 +00001793 // If the decl being referenced had an error, return an error for this
1794 // sub-expr without emitting another error, in order to avoid cascading
1795 // error cases.
1796 if (IV->isInvalidDecl())
1797 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001798
1799 // Check whether we can reference this field.
1800 if (DiagnoseUseOfDecl(IV, MemberLoc))
1801 return ExprError();
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001802 if (IV->getAccessControl() != ObjCIvarDecl::Public) {
1803 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1804 if (ObjCMethodDecl *MD = getCurMethodDecl())
1805 ClassOfMethodDecl = MD->getClassInterface();
Steve Naroffb06d8752009-03-04 18:34:24 +00001806 else if (FunctionDecl *FD = getCurFunctionDecl()) {
1807 // FIXME: This isn't working yet. Will discuss with Fariborz.
1808 // FIXME: Should be ObjCImplDecl, so categories can work.
1809 // Need to fiddle with castToDeclContext/castFromDeclContext.
1810 ObjCImplementationDecl *ImpDecl = getCurImplementationDecl(FD);
1811 if (ImpDecl)
1812 ClassOfMethodDecl = ImpDecl->getClassInterface();
1813 }
1814 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001815 if (ClassDeclared != IFTy->getDecl() ||
Steve Naroffb06d8752009-03-04 18:34:24 +00001816 (ClassOfMethodDecl && (ClassOfMethodDecl != ClassDeclared)))
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001817 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1818 }
1819 // @protected
1820 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1821 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1822 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001823
1824 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff6ece14c2009-01-21 00:14:39 +00001825 MemberLoc, BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001826 OpKind == tok::arrow);
1827 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001828 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001829 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001830 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1831 << IFTy->getDecl()->getDeclName() << &Member
1832 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001833 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001834
Chris Lattnera38e6b12008-07-21 04:59:05 +00001835 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1836 // pointer to a (potentially qualified) interface type.
1837 const PointerType *PTy;
1838 const ObjCInterfaceType *IFTy;
1839 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1840 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1841 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001842
Daniel Dunbar2307d312008-09-03 01:05:41 +00001843 // Search for a declared property first.
Chris Lattner7eba82e2009-02-16 18:35:08 +00001844 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001845 // Check whether we can reference this property.
1846 if (DiagnoseUseOfDecl(PD, MemberLoc))
1847 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00001848
Steve Naroff6ece14c2009-01-21 00:14:39 +00001849 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001850 MemberLoc, BaseExpr));
1851 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001852
Daniel Dunbar2307d312008-09-03 01:05:41 +00001853 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001854 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1855 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner7eba82e2009-02-16 18:35:08 +00001856 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001857 // Check whether we can reference this property.
1858 if (DiagnoseUseOfDecl(PD, MemberLoc))
1859 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00001860
Steve Naroff6ece14c2009-01-21 00:14:39 +00001861 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001862 MemberLoc, BaseExpr));
1863 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001864
1865 // If that failed, look for an "implicit" property by seeing if the nullary
1866 // selector is implemented.
1867
1868 // FIXME: The logic for looking up nullary and unary selectors should be
1869 // shared with the code in ActOnInstanceMessage.
1870
1871 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1872 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001873
Daniel Dunbar2307d312008-09-03 01:05:41 +00001874 // If this reference is in an @implementation, check for 'private' methods.
1875 if (!Getter)
1876 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1877 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stumpeed9cac2009-02-19 03:04:26 +00001878 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar2307d312008-09-03 01:05:41 +00001879 ObjCImplementations[ClassDecl->getIdentifier()])
1880 Getter = ImpDecl->getInstanceMethod(Sel);
1881
Steve Naroff7692ed62008-10-22 19:16:27 +00001882 // Look through local category implementations associated with the class.
1883 if (!Getter) {
1884 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1885 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1886 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1887 }
1888 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001889 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001890 // Check if we can reference this property.
1891 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1892 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001893
Daniel Dunbar2307d312008-09-03 01:05:41 +00001894 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001895 // will look for the matching setter, in case it is needed.
1896 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1897 &Member);
1898 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1899 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1900 if (!Setter) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00001901 // If this reference is in an @implementation, also check for 'private'
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001902 // methods.
1903 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1904 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stumpeed9cac2009-02-19 03:04:26 +00001905 if (ObjCImplementationDecl *ImpDecl =
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001906 ObjCImplementations[ClassDecl->getIdentifier()])
1907 Setter = ImpDecl->getInstanceMethod(SetterSel);
1908 }
1909 // Look through local category implementations associated with the class.
1910 if (!Setter) {
1911 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1912 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1913 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1914 }
1915 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001916
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001917 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1918 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001919
Sebastian Redl0eb23302009-01-19 00:08:26 +00001920 // FIXME: we must check that the setter has property type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001921 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
Steve Naroff6ece14c2009-01-21 00:14:39 +00001922 Setter, MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001923 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001924
1925 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1926 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001927 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001928 // Handle properties on qualified "id" protocols.
1929 const ObjCQualifiedIdType *QIdTy;
1930 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1931 // Check protocols on qualified interfaces.
1932 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001933 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner7eba82e2009-02-16 18:35:08 +00001934 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001935 // Check the use of this declaration
1936 if (DiagnoseUseOfDecl(PD, MemberLoc))
1937 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001938
Steve Naroff6ece14c2009-01-21 00:14:39 +00001939 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001940 MemberLoc, BaseExpr));
1941 }
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001942 // Also must look for a getter name which uses property syntax.
1943 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1944 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001945 // Check the use of this method.
1946 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1947 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001948
1949 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001950 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001951 }
1952 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001953
1954 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1955 << &Member << BaseType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001956 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001957 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00001958 if (BaseType->isExtVectorType()) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001959 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1960 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001961 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001962 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001963 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001964 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001965
1966 return ExprError(Diag(MemberLoc,
1967 diag::err_typecheck_member_reference_struct_union)
1968 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001969}
1970
Douglas Gregor88a35142008-12-22 05:46:06 +00001971/// ConvertArgumentsForCall - Converts the arguments specified in
1972/// Args/NumArgs to the parameter types of the function FDecl with
1973/// function prototype Proto. Call is the call expression itself, and
1974/// Fn is the function expression. For a C++ member function, this
1975/// routine does not attempt to convert the object argument. Returns
1976/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001977bool
1978Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00001979 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00001980 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00001981 Expr **Args, unsigned NumArgs,
1982 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00001983 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00001984 // assignment, to the types of the corresponding parameter, ...
1985 unsigned NumArgsInProto = Proto->getNumArgs();
1986 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001987 bool Invalid = false;
1988
Douglas Gregor88a35142008-12-22 05:46:06 +00001989 // If too few arguments are available (and we don't have default
1990 // arguments for the remaining parameters), don't make the call.
1991 if (NumArgs < NumArgsInProto) {
1992 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1993 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1994 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1995 // Use default arguments for missing arguments
1996 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001997 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00001998 }
1999
2000 // If too many are passed and not variadic, error on the extras and drop
2001 // them.
2002 if (NumArgs > NumArgsInProto) {
2003 if (!Proto->isVariadic()) {
2004 Diag(Args[NumArgsInProto]->getLocStart(),
2005 diag::err_typecheck_call_too_many_args)
2006 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2007 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2008 Args[NumArgs-1]->getLocEnd());
2009 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002010 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002011 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002012 }
2013 NumArgsToCheck = NumArgsInProto;
2014 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002015
Douglas Gregor88a35142008-12-22 05:46:06 +00002016 // Continue to check argument types (even if we have too few/many args).
2017 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2018 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002019
Douglas Gregor88a35142008-12-22 05:46:06 +00002020 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002021 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002022 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002023
2024 // Pass the argument.
2025 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2026 return true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002027 } else
Douglas Gregor61366e92008-12-24 00:01:03 +00002028 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00002029 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00002030 QualType ArgType = Arg->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002031
Douglas Gregor88a35142008-12-22 05:46:06 +00002032 Call->setArg(i, Arg);
2033 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002034
Douglas Gregor88a35142008-12-22 05:46:06 +00002035 // If this is a variadic call, handle args passed through "...".
2036 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002037 VariadicCallType CallType = VariadicFunction;
2038 if (Fn->getType()->isBlockPointerType())
2039 CallType = VariadicBlock; // Block
2040 else if (isa<MemberExpr>(Fn))
2041 CallType = VariadicMethod;
2042
Douglas Gregor88a35142008-12-22 05:46:06 +00002043 // Promote the arguments (C99 6.5.2.2p7).
2044 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2045 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002046 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002047 Call->setArg(i, Arg);
2048 }
2049 }
2050
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002051 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002052}
2053
Steve Narofff69936d2007-09-16 03:34:24 +00002054/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002055/// This provides the location of the left/right parens and a list of comma
2056/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002057Action::OwningExprResult
2058Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2059 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002060 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002061 unsigned NumArgs = args.size();
2062 Expr *Fn = static_cast<Expr *>(fn.release());
2063 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002064 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002065 FunctionDecl *FDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002066 DeclarationName UnqualifiedName;
Douglas Gregor88a35142008-12-22 05:46:06 +00002067
Douglas Gregor88a35142008-12-22 05:46:06 +00002068 if (getLangOptions().CPlusPlus) {
Douglas Gregor17330012009-02-04 15:01:18 +00002069 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002070 // in which case we won't do any semantic analysis now.
Douglas Gregor17330012009-02-04 15:01:18 +00002071 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2072 bool Dependent = false;
2073 if (Fn->isTypeDependent())
2074 Dependent = true;
2075 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2076 Dependent = true;
2077
2078 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002079 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002080 Context.DependentTy, RParenLoc));
2081
2082 // Determine whether this is a call to an object (C++ [over.call.object]).
2083 if (Fn->getType()->isRecordType())
2084 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2085 CommaLocs, RParenLoc));
2086
Douglas Gregorfa047642009-02-04 00:32:51 +00002087 // Determine whether this is a call to a member function.
Douglas Gregor88a35142008-12-22 05:46:06 +00002088 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2089 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2090 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002091 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2092 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00002093 }
2094
Douglas Gregorfa047642009-02-04 00:32:51 +00002095 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00002096 DeclRefExpr *DRExpr = NULL;
Douglas Gregorfa047642009-02-04 00:32:51 +00002097 Expr *FnExpr = Fn;
2098 bool ADL = true;
2099 while (true) {
2100 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2101 FnExpr = IcExpr->getSubExpr();
2102 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002103 // Parentheses around a function disable ADL
Douglas Gregor17330012009-02-04 15:01:18 +00002104 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00002105 ADL = false;
2106 FnExpr = PExpr->getSubExpr();
2107 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stumpeed9cac2009-02-19 03:04:26 +00002108 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregorfa047642009-02-04 00:32:51 +00002109 == UnaryOperator::AddrOf) {
2110 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattner90e150d2009-02-14 07:22:29 +00002111 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2112 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2113 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2114 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002115 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattner90e150d2009-02-14 07:22:29 +00002116 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2117 UnqualifiedName = DepName->getName();
2118 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002119 } else {
Chris Lattner90e150d2009-02-14 07:22:29 +00002120 // Any kind of name that does not refer to a declaration (or
2121 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2122 ADL = false;
Douglas Gregorfa047642009-02-04 00:32:51 +00002123 break;
2124 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002125 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002126
Douglas Gregor17330012009-02-04 15:01:18 +00002127 OverloadedFunctionDecl *Ovl = 0;
2128 if (DRExpr) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002129 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor17330012009-02-04 15:01:18 +00002130 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2131 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002132
Douglas Gregorf9201e02009-02-11 23:02:49 +00002133 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002134 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor3c385e52009-02-14 18:57:46 +00002135 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002136 ADL = false;
2137
Douglas Gregorf9201e02009-02-11 23:02:49 +00002138 // We don't perform ADL in C.
2139 if (!getLangOptions().CPlusPlus)
2140 ADL = false;
2141
Douglas Gregor17330012009-02-04 15:01:18 +00002142 if (Ovl || ADL) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002143 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2144 UnqualifiedName, LParenLoc, Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002145 NumArgs, CommaLocs, RParenLoc, ADL);
2146 if (!FDecl)
2147 return ExprError();
2148
2149 // Update Fn to refer to the actual function selected.
2150 Expr *NewFn = 0;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002151 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor17330012009-02-04 15:01:18 +00002152 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stumpeed9cac2009-02-19 03:04:26 +00002153 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2154 QDRExpr->getLocation(),
Douglas Gregorfa047642009-02-04 00:32:51 +00002155 false, false,
2156 QDRExpr->getSourceRange().getBegin());
2157 else
Mike Stumpeed9cac2009-02-19 03:04:26 +00002158 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00002159 Fn->getSourceRange().getBegin());
2160 Fn->Destroy(Context);
2161 Fn = NewFn;
2162 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002163 }
Chris Lattner04421082008-04-08 04:40:51 +00002164
2165 // Promote the function operand.
2166 UsualUnaryConversions(Fn);
2167
Chris Lattner925e60d2007-12-28 05:29:59 +00002168 // Make the call expr early, before semantic checks. This guarantees cleanup
2169 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002170 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2171 Args, NumArgs,
2172 Context.BoolTy,
2173 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002174
Steve Naroffdd972f22008-09-05 22:11:13 +00002175 const FunctionType *FuncT;
2176 if (!Fn->getType()->isBlockPointerType()) {
2177 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2178 // have type pointer to function".
2179 const PointerType *PT = Fn->getType()->getAsPointerType();
2180 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002181 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2182 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00002183 FuncT = PT->getPointeeType()->getAsFunctionType();
2184 } else { // This is a block call.
2185 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2186 getAsFunctionType();
2187 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002188 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002189 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2190 << Fn->getType() << Fn->getSourceRange());
2191
Chris Lattner925e60d2007-12-28 05:29:59 +00002192 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002193 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002194
Douglas Gregor72564e72009-02-26 23:50:07 +00002195 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002196 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002197 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002198 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002199 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002200 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002201
Steve Naroffb291ab62007-08-28 23:30:39 +00002202 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002203 for (unsigned i = 0; i != NumArgs; i++) {
2204 Expr *Arg = Args[i];
2205 DefaultArgumentPromotion(Arg);
2206 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002207 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002209
Douglas Gregor88a35142008-12-22 05:46:06 +00002210 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2211 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002212 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2213 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002214
Chris Lattner59907c42007-08-10 20:18:51 +00002215 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00002216 if (FDecl)
2217 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00002218
Sebastian Redl0eb23302009-01-19 00:08:26 +00002219 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002220}
2221
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002222Action::OwningExprResult
2223Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2224 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002225 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00002226 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002227 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002228 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002229 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002230
Eli Friedman6223c222008-05-20 05:22:08 +00002231 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002232 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002233 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2234 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002235 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2236 diag::err_typecheck_decl_incomplete_type,
2237 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002238 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002239
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002240 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002241 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002242 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002243
Chris Lattner371f2582008-12-04 23:50:19 +00002244 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002245 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002246 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002247 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002248 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002249 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002250 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002251 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002252}
2253
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002254Action::OwningExprResult
2255Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2256 InitListDesignations &Designators,
2257 SourceLocation RBraceLoc) {
2258 unsigned NumInit = initlist.size();
2259 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002260
Steve Naroff08d92e42007-09-15 18:49:24 +00002261 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00002262 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002263
Mike Stumpeed9cac2009-02-19 03:04:26 +00002264 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002265 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002266 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002267 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002268}
2269
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002270/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00002271bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002272 UsualUnaryConversions(castExpr);
2273
2274 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2275 // type needs to be scalar.
2276 if (castType->isVoidType()) {
2277 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00002278 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2279 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002280 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002281 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2282 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2283 (castType->isStructureType() || castType->isUnionType())) {
2284 // GCC struct/union extension: allow cast to self.
2285 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2286 << castType << castExpr->getSourceRange();
2287 } else if (castType->isUnionType()) {
2288 // GCC cast to union extension
2289 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2290 RecordDecl::field_iterator Field, FieldEnd;
2291 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2292 Field != FieldEnd; ++Field) {
2293 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2294 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2295 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2296 << castExpr->getSourceRange();
2297 break;
2298 }
2299 }
2300 if (Field == FieldEnd)
2301 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2302 << castExpr->getType() << castExpr->getSourceRange();
2303 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002304 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002305 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002306 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002307 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002308 } else if (!castExpr->getType()->isScalarType() &&
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002309 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002310 return Diag(castExpr->getLocStart(),
2311 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002312 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002313 } else if (castExpr->getType()->isVectorType()) {
2314 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2315 return true;
2316 } else if (castType->isVectorType()) {
2317 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2318 return true;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002319 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
2320 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002321 }
2322 return false;
2323}
2324
Chris Lattnerfe23e212007-12-20 00:44:32 +00002325bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002326 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00002327
Anders Carlssona64db8f2007-11-27 05:51:55 +00002328 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002329 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002330 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00002331 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00002332 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002333 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002334 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002335 } else
2336 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002337 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002338 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002339
Anders Carlssona64db8f2007-11-27 05:51:55 +00002340 return false;
2341}
2342
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002343Action::OwningExprResult
2344Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2345 SourceLocation RParenLoc, ExprArg Op) {
2346 assert((Ty != 0) && (Op.get() != 0) &&
2347 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002348
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002349 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002350 QualType castType = QualType::getFromOpaquePtr(Ty);
2351
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002352 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002353 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002354 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002355 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002356}
2357
Sebastian Redl28507842009-02-26 14:39:58 +00002358/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2359/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00002360/// C99 6.5.15
2361QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2362 SourceLocation QuestionLoc) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002363 UsualUnaryConversions(Cond);
2364 UsualUnaryConversions(LHS);
2365 UsualUnaryConversions(RHS);
2366 QualType CondTy = Cond->getType();
2367 QualType LHSTy = LHS->getType();
2368 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002369
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 // first, check the condition.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002371 if (!Cond->isTypeDependent()) {
2372 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2373 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2374 << CondTy;
Douglas Gregor898574e2008-12-05 23:32:09 +00002375 return QualType();
2376 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002377 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002378
Chris Lattner70d67a92008-01-06 22:42:25 +00002379 // Now check the two expressions.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002380 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor898574e2008-12-05 23:32:09 +00002381 return Context.DependentTy;
2382
Chris Lattner70d67a92008-01-06 22:42:25 +00002383 // If both operands have arithmetic type, do the usual arithmetic conversions
2384 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002385 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2386 UsualArithmeticConversions(LHS, RHS);
2387 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00002388 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002389
Chris Lattner70d67a92008-01-06 22:42:25 +00002390 // If both operands are the same structure or union type, the result is that
2391 // type.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002392 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2393 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002394 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00002395 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00002396 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002397 return LHSTy.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002398 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002399
Chris Lattner70d67a92008-01-06 22:42:25 +00002400 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002401 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002402 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2403 if (!LHSTy->isVoidType())
2404 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2405 << RHS->getSourceRange();
2406 if (!RHSTy->isVoidType())
2407 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2408 << LHS->getSourceRange();
2409 ImpCastExprToType(LHS, Context.VoidTy);
2410 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedman0e724012008-06-04 19:47:51 +00002411 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002412 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002413 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2414 // the type of the other operand."
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002415 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2416 Context.isObjCObjectPointerType(LHSTy)) &&
2417 RHS->isNullPointerConstant(Context)) {
2418 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2419 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002420 }
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002421 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2422 Context.isObjCObjectPointerType(RHSTy)) &&
2423 LHS->isNullPointerConstant(Context)) {
2424 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2425 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002426 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002427
Chris Lattnerbd57d362008-01-06 22:50:31 +00002428 // Handle the case where both operands are pointers before we handle null
2429 // pointer constants in case both operands are null pointer constants.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002430 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2431 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002432 // get the "pointed to" types
2433 QualType lhptee = LHSPT->getPointeeType();
2434 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002435
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002436 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2437 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002438 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002439 // Figure out necessary qualifiers (C99 6.5.15p6)
2440 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002441 QualType destType = Context.getPointerType(destPointee);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002442 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2443 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmana541d532008-02-10 22:59:36 +00002444 return destType;
2445 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002446 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002447 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002448 QualType destType = Context.getPointerType(destPointee);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002449 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2450 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmana541d532008-02-10 22:59:36 +00002451 return destType;
2452 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002453
Chris Lattnera119a3b2009-02-18 04:38:20 +00002454 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattnerb4650c12009-02-19 04:44:58 +00002455 // Two identical pointer types are always compatible.
Chris Lattnera119a3b2009-02-18 04:38:20 +00002456 return LHSTy;
2457 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002458
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002459 QualType compositeType = LHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002460
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002461 // If either type is an Objective-C object type then check
2462 // compatibility according to Objective-C.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002463 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002464 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002465 // If both operands are interfaces and either operand can be
2466 // assigned to the other, use that type as the composite
2467 // type. This allows
2468 // xxx ? (A*) a : (B*) b
2469 // where B is a subclass of A.
2470 //
2471 // Additionally, as for assignment, if either type is 'id'
2472 // allow silent coercion. Finally, if the types are
2473 // incompatible then make sure to use 'id' as the composite
2474 // type so the result is acceptable for sending messages to.
2475
Steve Naroff1fd03612009-02-12 19:05:07 +00002476 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002477 // It could return the composite type.
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002478 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2479 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2480 if (LHSIface && RHSIface &&
2481 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002482 compositeType = LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002483 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002484 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002485 compositeType = RHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002486 } else if (Context.isObjCIdStructType(lhptee) ||
2487 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002488 compositeType = Context.getObjCIdType();
2489 } else {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002490 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stumpeed9cac2009-02-19 03:04:26 +00002491 << LHSTy << RHSTy
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002492 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002493 QualType incompatTy = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002494 ImpCastExprToType(LHS, incompatTy);
2495 ImpCastExprToType(RHS, incompatTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002496 return incompatTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002497 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002498 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002499 rhptee.getUnqualifiedType())) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002500 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2501 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002502 // In this situation, we assume void* type. No especially good
2503 // reason, but this is what gcc does, and we do have to pick
2504 // to get a consistent AST.
2505 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002506 ImpCastExprToType(LHS, incompatTy);
2507 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002508 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002509 }
2510 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002511 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2512 // differently qualified versions of compatible types, the result type is
2513 // a pointer to an appropriately qualified version of the *composite*
2514 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002515 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002516 // FIXME: Need to add qualifiers
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002517 ImpCastExprToType(LHS, compositeType);
2518 ImpCastExprToType(RHS, compositeType);
Eli Friedman5835ea22008-05-16 20:37:07 +00002519 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 }
2521 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002522
Chris Lattnera119a3b2009-02-18 04:38:20 +00002523 // Selection between block pointer types is ok as long as they are the same.
2524 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2525 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2526 return LHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002527
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002528 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2529 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stumpeed9cac2009-02-19 03:04:26 +00002530 // id with statically typed objects).
2531 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002532 // GCC allows qualified id and any Objective-C type to devolve to
2533 // id. Currently localizing to here until clear this should be
2534 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002535 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00002536 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002537 Context.isObjCObjectPointerType(RHSTy)) ||
2538 (RHSTy->isObjCQualifiedIdType() &&
2539 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002540 // FIXME: This is not the correct composite type. This only
2541 // happens to work because id can more or less be used anywhere,
2542 // however this may change the type of method sends.
2543 // FIXME: gcc adds some type-checking of the arguments and emits
2544 // (confusing) incompatible comparison warnings in some
2545 // cases. Investigate.
2546 QualType compositeType = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002547 ImpCastExprToType(LHS, compositeType);
2548 ImpCastExprToType(RHS, compositeType);
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002549 return compositeType;
2550 }
2551 }
2552
Chris Lattner70d67a92008-01-06 22:42:25 +00002553 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002554 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2555 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 return QualType();
2557}
2558
Steve Narofff69936d2007-09-16 03:34:24 +00002559/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002560/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002561Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2562 SourceLocation ColonLoc,
2563 ExprArg Cond, ExprArg LHS,
2564 ExprArg RHS) {
2565 Expr *CondExpr = (Expr *) Cond.get();
2566 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002567
2568 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2569 // was the condition.
2570 bool isLHSNull = LHSExpr == 0;
2571 if (isLHSNull)
2572 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002573
2574 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002575 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002576 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002577 return ExprError();
2578
2579 Cond.release();
2580 LHS.release();
2581 RHS.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002582 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002583 isLHSNull ? 0 : LHSExpr,
2584 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002585}
2586
Reid Spencer5f016e22007-07-11 17:01:13 +00002587
2588// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00002589// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00002590// routine is it effectively iqnores the qualifiers on the top level pointee.
2591// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2592// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002593Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002594Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2595 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002596
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002598 lhptee = lhsType->getAsPointerType()->getPointeeType();
2599 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002600
Reid Spencer5f016e22007-07-11 17:01:13 +00002601 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002602 lhptee = Context.getCanonicalType(lhptee);
2603 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002604
Chris Lattner5cf216b2008-01-04 18:04:52 +00002605 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002606
2607 // C99 6.5.16.1p1: This following citation is common to constraints
2608 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2609 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002610 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002611 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002612 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002613
Mike Stumpeed9cac2009-02-19 03:04:26 +00002614 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2615 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002617 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002618 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002619 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002620
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002621 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002622 assert(rhptee->isFunctionType());
2623 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002624 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002625
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002626 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002627 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002628 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002629
2630 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002631 assert(lhptee->isFunctionType());
2632 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002633 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002634 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 // unqualified versions of compatible types, ...
Mike Stumpeed9cac2009-02-19 03:04:26 +00002636 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002637 rhptee.getUnqualifiedType()))
2638 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002639 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002640}
2641
Steve Naroff1c7d0672008-09-04 15:10:53 +00002642/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2643/// block pointer types are compatible or whether a block and normal pointer
2644/// are compatible. It is more restrict than comparing two function pointer
2645// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002646Sema::AssignConvertType
2647Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00002648 QualType rhsType) {
2649 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002650
Steve Naroff1c7d0672008-09-04 15:10:53 +00002651 // get the "pointed to" type (ignoring qualifiers at the top level)
2652 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002653 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2654
Steve Naroff1c7d0672008-09-04 15:10:53 +00002655 // make sure we operate on the canonical type
2656 lhptee = Context.getCanonicalType(lhptee);
2657 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002658
Steve Naroff1c7d0672008-09-04 15:10:53 +00002659 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002660
Steve Naroff1c7d0672008-09-04 15:10:53 +00002661 // For blocks we enforce that qualifiers are identical.
2662 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2663 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002664
Steve Naroff1c7d0672008-09-04 15:10:53 +00002665 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00002666 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002667 return ConvTy;
2668}
2669
Mike Stumpeed9cac2009-02-19 03:04:26 +00002670/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2671/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00002672/// pointers. Here are some objectionable examples that GCC considers warnings:
2673///
2674/// int a, *pint;
2675/// short *pshort;
2676/// struct foo *pfoo;
2677///
2678/// pint = pshort; // warning: assignment from incompatible pointer type
2679/// a = pint; // warning: assignment makes integer from pointer without a cast
2680/// pint = a; // warning: assignment makes pointer from integer without a cast
2681/// pint = pfoo; // warning: assignment from incompatible pointer type
2682///
2683/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00002684/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002685///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002686Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002687Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002688 // Get canonical types. We're not formatting these types, just comparing
2689 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002690 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2691 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002692
2693 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002694 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002695
Douglas Gregor9d293df2008-10-28 00:22:11 +00002696 // If the left-hand side is a reference type, then we are in a
2697 // (rare!) case where we've allowed the use of references in C,
2698 // e.g., as a parameter type in a built-in function. In this case,
2699 // just make sure that the type referenced is compatible with the
2700 // right-hand side type. The caller is responsible for adjusting
2701 // lhsType so that the resulting expression does not have reference
2702 // type.
2703 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2704 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002705 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002706 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002707 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002708
Chris Lattnereca7be62008-04-07 05:30:13 +00002709 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2710 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002711 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002712 // Relax integer conversions like we do for pointers below.
2713 if (rhsType->isIntegerType())
2714 return IntToPointer;
2715 if (lhsType->isIntegerType())
2716 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002717 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002718 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002719
Nate Begemanbe2341d2008-07-14 18:02:46 +00002720 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002721 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002722 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2723 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002724 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002725
Nate Begemanbe2341d2008-07-14 18:02:46 +00002726 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00002727 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00002728 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002729 if (getLangOptions().LaxVectorConversions &&
2730 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002731 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002732 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002733 }
2734 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002735 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002736
Chris Lattnere8b3e962008-01-04 23:32:24 +00002737 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002738 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002739
Chris Lattner78eca282008-04-07 06:49:41 +00002740 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002742 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002743
Chris Lattner78eca282008-04-07 06:49:41 +00002744 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002746
Steve Naroffb4406862008-09-29 18:10:17 +00002747 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002748 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002749 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002750
2751 // Treat block pointers as objects.
2752 if (getLangOptions().ObjC1 &&
2753 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2754 return Compatible;
2755 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002756 return Incompatible;
2757 }
2758
2759 if (isa<BlockPointerType>(lhsType)) {
2760 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00002761 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002762
Steve Naroffb4406862008-09-29 18:10:17 +00002763 // Treat block pointers as objects.
2764 if (getLangOptions().ObjC1 &&
2765 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2766 return Compatible;
2767
Steve Naroff1c7d0672008-09-04 15:10:53 +00002768 if (rhsType->isBlockPointerType())
2769 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002770
Steve Naroff1c7d0672008-09-04 15:10:53 +00002771 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2772 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002773 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002774 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002775 return Incompatible;
2776 }
2777
Chris Lattner78eca282008-04-07 06:49:41 +00002778 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002779 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002780 if (lhsType == Context.BoolTy)
2781 return Compatible;
2782
2783 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002784 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002785
Mike Stumpeed9cac2009-02-19 03:04:26 +00002786 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002788
2789 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff1c7d0672008-09-04 15:10:53 +00002790 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002791 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002792 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002793 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002794
Chris Lattnerfc144e22008-01-04 23:18:45 +00002795 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002796 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 }
2799 return Incompatible;
2800}
2801
Chris Lattner5cf216b2008-01-04 18:04:52 +00002802Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002803Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002804 if (getLangOptions().CPlusPlus) {
2805 if (!lhsType->isRecordType()) {
2806 // C++ 5.17p3: If the left operand is not of class type, the
2807 // expression is implicitly converted (C++ 4) to the
2808 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002809 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2810 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002811 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002812 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002813 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002814 }
2815
2816 // FIXME: Currently, we fall through and treat C++ classes like C
2817 // structures.
2818 }
2819
Steve Naroff529a4ad2007-11-27 17:58:44 +00002820 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2821 // a null pointer constant.
Steve Narofff7f52e72009-02-21 21:17:01 +00002822 if ((lhsType->isPointerType() ||
2823 lhsType->isObjCQualifiedIdType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00002824 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002825 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002826 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002827 return Compatible;
2828 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002829
Chris Lattner943140e2007-10-16 02:55:40 +00002830 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002831 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002832 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002833 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002834 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00002835 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002836 if (!lhsType->isReferenceType())
2837 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002838
Chris Lattner5cf216b2008-01-04 18:04:52 +00002839 Sema::AssignConvertType result =
2840 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00002841
Steve Narofff1120de2007-08-24 22:33:52 +00002842 // C99 6.5.16.1p2: The value of the right operand is converted to the
2843 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002844 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2845 // so that we can use references in built-in functions even in C.
2846 // The getNonReferenceType() call makes sure that the resulting expression
2847 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002848 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002849 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002850 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002851}
2852
Chris Lattner5cf216b2008-01-04 18:04:52 +00002853Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002854Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2855 return CheckAssignmentConstraints(lhsType, rhsType);
2856}
2857
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002858QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002859 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002860 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002861 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002862 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002863}
2864
Mike Stumpeed9cac2009-02-19 03:04:26 +00002865inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002866 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002867 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002868 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002869 QualType lhsType =
2870 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2871 QualType rhsType =
2872 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002873
Nate Begemanbe2341d2008-07-14 18:02:46 +00002874 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002875 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002876 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002877
Nate Begemanbe2341d2008-07-14 18:02:46 +00002878 // Handle the case of a vector & extvector type of the same size and element
2879 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002880 if (getLangOptions().LaxVectorConversions) {
2881 // FIXME: Should we warn here?
2882 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002883 if (const VectorType *RV = rhsType->getAsVectorType())
2884 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002885 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002886 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002887 }
2888 }
2889 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002890
Nate Begemanbe2341d2008-07-14 18:02:46 +00002891 // If the lhs is an extended vector and the rhs is a scalar of the same type
2892 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002893 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002894 QualType eltType = V->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002895
2896 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00002897 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2898 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002899 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002900 return lhsType;
2901 }
2902 }
2903
Nate Begemanbe2341d2008-07-14 18:02:46 +00002904 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002905 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002906 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002907 QualType eltType = V->getElementType();
2908
Mike Stumpeed9cac2009-02-19 03:04:26 +00002909 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00002910 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2911 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002912 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002913 return rhsType;
2914 }
2915 }
2916
Reid Spencer5f016e22007-07-11 17:01:13 +00002917 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002918 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002919 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002920 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002921 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00002922}
2923
Reid Spencer5f016e22007-07-11 17:01:13 +00002924inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00002925 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002926{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002927 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002928 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002929
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002930 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002931
Steve Naroffa4332e22007-07-17 00:58:39 +00002932 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002933 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002934 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002935}
2936
2937inline QualType Sema::CheckRemainderOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00002938 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002939{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002940 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2941 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2942 return CheckVectorOperands(Loc, lex, rex);
2943 return InvalidOperands(Loc, lex, rex);
2944 }
Steve Naroff90045e82007-07-13 23:32:42 +00002945
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002946 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002947
Steve Naroffa4332e22007-07-17 00:58:39 +00002948 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002949 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002950 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002951}
2952
2953inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stumpeed9cac2009-02-19 03:04:26 +00002954 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002955{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002956 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002957 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002958
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002959 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002960
Reid Spencer5f016e22007-07-11 17:01:13 +00002961 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002962 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002963 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002964
Eli Friedmand72d16e2008-05-18 18:08:51 +00002965 // Put any potential pointer into PExp
2966 Expr* PExp = lex, *IExp = rex;
2967 if (IExp->getType()->isPointerType())
2968 std::swap(PExp, IExp);
2969
2970 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2971 if (IExp->getType()->isIntegerType()) {
2972 // Check for arithmetic on pointers to incomplete types
2973 if (!PTy->getPointeeType()->isObjectType()) {
2974 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002975 if (getLangOptions().CPlusPlus) {
2976 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2977 << lex->getSourceRange() << rex->getSourceRange();
2978 return QualType();
2979 }
2980
2981 // GNU extension: arithmetic on pointer to void
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002982 Diag(Loc, diag::ext_gnu_void_ptr)
2983 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002984 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002985 if (getLangOptions().CPlusPlus) {
2986 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2987 << lex->getType() << lex->getSourceRange();
2988 return QualType();
2989 }
2990
2991 // GNU extension: arithmetic on pointer to function
2992 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00002993 << lex->getType() << lex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002994 } else {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002995 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002996 diag::err_typecheck_arithmetic_incomplete_type,
2997 lex->getSourceRange(), SourceRange(),
2998 lex->getType());
2999 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00003000 }
3001 }
3002 return PExp->getType();
3003 }
3004 }
3005
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003006 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003007}
3008
Chris Lattnereca7be62008-04-07 05:30:13 +00003009// C99 6.5.6
3010QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003011 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00003012 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003013 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003014
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003015 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003016
Chris Lattner6e4ab612007-12-09 21:53:25 +00003017 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003018
Chris Lattner6e4ab612007-12-09 21:53:25 +00003019 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00003020 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003021 return compType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003022
Chris Lattner6e4ab612007-12-09 21:53:25 +00003023 // Either ptr - int or ptr - ptr.
3024 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00003025 QualType lpointee = LHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003026
Chris Lattner6e4ab612007-12-09 21:53:25 +00003027 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00003028 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00003029 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00003030 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003031 Diag(Loc, diag::ext_gnu_void_ptr)
3032 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorc983b862009-01-23 00:36:41 +00003033 } else if (lpointee->isFunctionType()) {
3034 if (getLangOptions().CPlusPlus) {
3035 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3036 << lex->getType() << lex->getSourceRange();
3037 return QualType();
3038 }
3039
3040 // GNU extension: arithmetic on pointer to function
3041 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3042 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003043 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003044 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00003045 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003046 return QualType();
3047 }
3048 }
3049
3050 // The result type of a pointer-int computation is the pointer type.
3051 if (rex->getType()->isIntegerType())
3052 return lex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003053
Chris Lattner6e4ab612007-12-09 21:53:25 +00003054 // Handle pointer-pointer subtractions.
3055 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00003056 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003057
Chris Lattner6e4ab612007-12-09 21:53:25 +00003058 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00003059 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00003060 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00003061 if (rpointee->isVoidType()) {
3062 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003063 Diag(Loc, diag::ext_gnu_void_ptr)
3064 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor08048882009-01-23 19:03:35 +00003065 } else if (rpointee->isFunctionType()) {
3066 if (getLangOptions().CPlusPlus) {
3067 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3068 << rex->getType() << rex->getSourceRange();
3069 return QualType();
3070 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003071
Douglas Gregor08048882009-01-23 19:03:35 +00003072 // GNU extension: arithmetic on pointer to function
3073 if (!lpointee->isFunctionType())
3074 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3075 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003076 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003077 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00003078 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003079 return QualType();
3080 }
3081 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003082
Chris Lattner6e4ab612007-12-09 21:53:25 +00003083 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00003084 if (!Context.typesAreCompatible(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003085 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedmanf1c7b482008-09-02 05:09:35 +00003086 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003087 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00003088 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003089 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003090 return QualType();
3091 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003092
Chris Lattner6e4ab612007-12-09 21:53:25 +00003093 return Context.getPointerDiffType();
3094 }
3095 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003096
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003097 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003098}
3099
Chris Lattnereca7be62008-04-07 05:30:13 +00003100// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003101QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00003102 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00003103 // C99 6.5.7p2: Each of the operands shall have integer type.
3104 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003105 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003106
Chris Lattnerca5eede2007-12-12 05:47:28 +00003107 // Shifts don't perform usual arithmetic conversions, they just do integer
3108 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00003109 if (!isCompAssign)
3110 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00003111 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003112
Chris Lattnerca5eede2007-12-12 05:47:28 +00003113 // "The type of the result is that of the promoted left operand."
3114 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003115}
3116
Chris Lattnereca7be62008-04-07 05:30:13 +00003117// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003118QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00003119 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003120 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003121 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003122
Chris Lattnera5937dd2007-08-26 01:18:55 +00003123 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00003124 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3125 UsualArithmeticConversions(lex, rex);
3126 else {
3127 UsualUnaryConversions(lex);
3128 UsualUnaryConversions(rex);
3129 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003130 QualType lType = lex->getType();
3131 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003132
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003133 // For non-floating point types, check for self-comparisons of the form
3134 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3135 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003136 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00003137 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3138 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003139 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003140 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003141 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003142
Douglas Gregor447b69e2008-11-19 03:25:36 +00003143 // The result of comparisons is 'bool' in C++, 'int' in C.
3144 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3145
Chris Lattnera5937dd2007-08-26 01:18:55 +00003146 if (isRelational) {
3147 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003148 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003149 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003150 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003151 if (lType->isFloatingType()) {
3152 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003153 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00003154 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003155
Chris Lattnera5937dd2007-08-26 01:18:55 +00003156 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003157 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003158 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003159
Chris Lattnerd28f8152007-08-26 01:10:14 +00003160 bool LHSIsNull = lex->isNullPointerConstant(Context);
3161 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003162
Chris Lattnera5937dd2007-08-26 01:18:55 +00003163 // All of the following pointer related warnings are GCC extensions, except
3164 // when handling null pointer constants. One day, we can consider making them
3165 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00003166 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003167 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003168 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00003169 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003170 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003171
Steve Naroff66296cb2007-11-13 14:57:38 +00003172 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003173 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3174 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00003175 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff389bf462009-02-12 17:52:19 +00003176 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003177 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003178 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003179 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00003180 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003181 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003182 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003183 // Handle block pointer types.
3184 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3185 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3186 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003187
Steve Naroff1c7d0672008-09-04 15:10:53 +00003188 if (!LHSIsNull && !RHSIsNull &&
3189 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003190 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003191 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00003192 }
3193 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003194 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003195 }
Steve Naroff59f53942008-09-28 01:11:11 +00003196 // Allow block pointers to be compared with null pointer constants.
3197 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3198 (lType->isPointerType() && rType->isBlockPointerType())) {
3199 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003200 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003201 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00003202 }
3203 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003204 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00003205 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003206
Steve Naroff20373222008-06-03 14:04:54 +00003207 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00003208 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00003209 const PointerType *LPT = lType->getAsPointerType();
3210 const PointerType *RPT = rType->getAsPointerType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003211 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00003212 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003213 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00003214 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003215
Steve Naroffa8069f12008-11-17 19:49:16 +00003216 if (!LPtrToVoid && !RPtrToVoid &&
3217 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003218 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003219 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00003220 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003221 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00003222 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003223 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003224 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00003225 }
Steve Naroff20373222008-06-03 14:04:54 +00003226 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3227 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003228 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003229 } else {
3230 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003231 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003232 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003233 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003234 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003235 }
Steve Naroff20373222008-06-03 14:04:54 +00003236 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00003237 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003238 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff20373222008-06-03 14:04:54 +00003239 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003240 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003241 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003242 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003243 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003244 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003245 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003246 if (lType->isIntegerType() &&
Steve Naroff20373222008-06-03 14:04:54 +00003247 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003248 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003249 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003250 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003251 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003252 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003253 }
Steve Naroff39218df2008-09-04 16:56:14 +00003254 // Handle block pointers.
3255 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3256 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003257 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003258 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003259 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003260 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003261 }
3262 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3263 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003264 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003265 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003266 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003267 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003268 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003269 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003270}
3271
Nate Begemanbe2341d2008-07-14 18:02:46 +00003272/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00003273/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003274/// like a scalar comparison, a vector comparison produces a vector of integer
3275/// types.
3276QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003277 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003278 bool isRelational) {
3279 // Check to make sure we're operating on vectors of the same type and width,
3280 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003281 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003282 if (vType.isNull())
3283 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003284
Nate Begemanbe2341d2008-07-14 18:02:46 +00003285 QualType lType = lex->getType();
3286 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003287
Nate Begemanbe2341d2008-07-14 18:02:46 +00003288 // For non-floating point types, check for self-comparisons of the form
3289 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3290 // often indicate logic errors in the program.
3291 if (!lType->isFloatingType()) {
3292 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3293 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3294 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003295 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003296 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003297
Nate Begemanbe2341d2008-07-14 18:02:46 +00003298 // Check for comparisons of floating point operands using != and ==.
3299 if (!isRelational && lType->isFloatingType()) {
3300 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003301 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003302 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003303
Nate Begemanbe2341d2008-07-14 18:02:46 +00003304 // Return the type for the comparison, which is the same as vector type for
3305 // integer vectors, or an integer type of identical size and number of
3306 // elements for floating point vectors.
3307 if (lType->isIntegerType())
3308 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003309
Nate Begemanbe2341d2008-07-14 18:02:46 +00003310 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00003311 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00003312 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00003313 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00003314 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3315 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3316
Mike Stumpeed9cac2009-02-19 03:04:26 +00003317 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00003318 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00003319 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3320}
3321
Reid Spencer5f016e22007-07-11 17:01:13 +00003322inline QualType Sema::CheckBitwiseOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003323 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003324{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003325 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003326 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00003327
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003328 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003329
Steve Naroffa4332e22007-07-17 00:58:39 +00003330 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003331 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003332 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003333}
3334
3335inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stumpeed9cac2009-02-19 03:04:26 +00003336 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003337{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003338 UsualUnaryConversions(lex);
3339 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003340
Eli Friedman5773a6c2008-05-13 20:16:47 +00003341 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003342 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003343 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003344}
3345
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003346/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3347/// is a read-only property; return true if so. A readonly property expression
3348/// depends on various declarations and thus must be treated specially.
3349///
Mike Stumpeed9cac2009-02-19 03:04:26 +00003350static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003351{
3352 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3353 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3354 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3355 QualType BaseType = PropExpr->getBase()->getType();
3356 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003357 if (const ObjCInterfaceType *IFTy =
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003358 PTy->getPointeeType()->getAsObjCInterfaceType())
3359 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3360 if (S.isPropertyReadonly(PDecl, IFace))
3361 return true;
3362 }
3363 }
3364 return false;
3365}
3366
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003367/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3368/// emit an error and return true. If so, return false.
3369static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003370 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3371 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3372 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003373 if (IsLV == Expr::MLV_Valid)
3374 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003375
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003376 unsigned Diag = 0;
3377 bool NeedType = false;
3378 switch (IsLV) { // C99 6.5.16p2
3379 default: assert(0 && "Unknown result from isModifiableLvalue!");
3380 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003381 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003382 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3383 NeedType = true;
3384 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003385 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003386 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3387 NeedType = true;
3388 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003389 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003390 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3391 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003392 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003393 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3394 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003395 case Expr::MLV_IncompleteType:
3396 case Expr::MLV_IncompleteVoidType:
Mike Stumpeed9cac2009-02-19 03:04:26 +00003397 return S.DiagnoseIncompleteType(Loc, E->getType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003398 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3399 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003400 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003401 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3402 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003403 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003404 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3405 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003406 case Expr::MLV_ReadonlyProperty:
3407 Diag = diag::error_readonly_property_assignment;
3408 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003409 case Expr::MLV_NoSetterProperty:
3410 Diag = diag::error_nosetter_property_assignment;
3411 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003412 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003413
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003414 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003415 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003416 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003417 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003418 return true;
3419}
3420
3421
3422
3423// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003424QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3425 SourceLocation Loc,
3426 QualType CompoundType) {
3427 // Verify that LHS is a modifiable lvalue, and emit error if not.
3428 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003429 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003430
3431 QualType LHSType = LHS->getType();
3432 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003433
Chris Lattner5cf216b2008-01-04 18:04:52 +00003434 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003435 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003436 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003437 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003438 // Special case of NSObject attributes on c-style pointer types.
3439 if (ConvTy == IncompatiblePointer &&
3440 ((Context.isObjCNSObjectType(LHSType) &&
3441 Context.isObjCObjectPointerType(RHSType)) ||
3442 (Context.isObjCNSObjectType(RHSType) &&
3443 Context.isObjCObjectPointerType(LHSType))))
3444 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003445
Chris Lattner2c156472008-08-21 18:04:13 +00003446 // If the RHS is a unary plus or minus, check to see if they = and + are
3447 // right next to each other. If so, the user may have typo'd "x =+ 4"
3448 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003449 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003450 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3451 RHSCheck = ICE->getSubExpr();
3452 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3453 if ((UO->getOpcode() == UnaryOperator::Plus ||
3454 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003455 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003456 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003457 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003458 Diag(Loc, diag::warn_not_compound_assign)
3459 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3460 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003461 }
3462 } else {
3463 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003464 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003465 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003466
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003467 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3468 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003469 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003470
Reid Spencer5f016e22007-07-11 17:01:13 +00003471 // C99 6.5.16p3: The type of an assignment expression is the type of the
3472 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00003473 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00003474 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3475 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003476 // C++ 5.17p1: the type of the assignment expression is that of its left
3477 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003478 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003479}
3480
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003481// C99 6.5.17
3482QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3483 // FIXME: what is required for LHS?
Mike Stumpeed9cac2009-02-19 03:04:26 +00003484
Chris Lattner53fcaa92008-07-25 20:54:07 +00003485 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003486 DefaultFunctionArrayConversion(RHS);
3487 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003488}
3489
Steve Naroff49b45262007-07-13 16:58:59 +00003490/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3491/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003492QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3493 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00003494 if (Op->isTypeDependent())
3495 return Context.DependentTy;
3496
Chris Lattner3528d352008-11-21 07:05:48 +00003497 QualType ResType = Op->getType();
3498 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003499
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003500 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3501 // Decrement of bool is not allowed.
3502 if (!isInc) {
3503 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3504 return QualType();
3505 }
3506 // Increment of bool sets it to true, but is deprecated.
3507 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3508 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003509 // OK!
3510 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3511 // C99 6.5.2.4p2, 6.5.6p2
3512 if (PT->getPointeeType()->isObjectType()) {
3513 // Pointer to object is ok!
3514 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003515 if (getLangOptions().CPlusPlus) {
3516 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3517 << Op->getSourceRange();
3518 return QualType();
3519 }
3520
3521 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00003522 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003523 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003524 if (getLangOptions().CPlusPlus) {
3525 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3526 << Op->getType() << Op->getSourceRange();
3527 return QualType();
3528 }
3529
3530 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003531 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003532 return QualType();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003533 } else {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003534 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003535 diag::err_typecheck_arithmetic_incomplete_type,
3536 Op->getSourceRange(), SourceRange(),
3537 ResType);
3538 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003539 }
Chris Lattner3528d352008-11-21 07:05:48 +00003540 } else if (ResType->isComplexType()) {
3541 // C99 does not support ++/-- on complex types, we allow as an extension.
3542 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003543 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003544 } else {
3545 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003546 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003547 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003548 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003549 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00003550 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003551 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003552 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003553 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003554}
3555
Anders Carlsson369dee42008-02-01 07:15:58 +00003556/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003557/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003558/// where the declaration is needed for type checking. We only need to
3559/// handle cases when the expression references a function designator
3560/// or is an lvalue. Here are some examples:
3561/// - &(x) => x
3562/// - &*****f => f for f a function designator.
3563/// - &s.xx => s
3564/// - &s.zz[1].yy -> s, if zz is an array
3565/// - *(x + 1) -> x, if x is an array
3566/// - &"123"[2] -> 0
3567/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003568static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003569 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003570 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003571 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003572 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003573 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003574 // Fields cannot be declared with a 'register' storage class.
3575 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003576 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003577 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003578 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003579 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003580 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003581
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003582 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003583 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003584 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003585 return 0;
3586 else
3587 return VD;
3588 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003589 case Stmt::UnaryOperatorClass: {
3590 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003591
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003592 switch(UO->getOpcode()) {
3593 case UnaryOperator::Deref: {
3594 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003595 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3596 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3597 if (!VD || VD->getType()->isPointerType())
3598 return 0;
3599 return VD;
3600 }
3601 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003602 }
3603 case UnaryOperator::Real:
3604 case UnaryOperator::Imag:
3605 case UnaryOperator::Extension:
3606 return getPrimaryDecl(UO->getSubExpr());
3607 default:
3608 return 0;
3609 }
3610 }
3611 case Stmt::BinaryOperatorClass: {
3612 BinaryOperator *BO = cast<BinaryOperator>(E);
3613
3614 // Handle cases involving pointer arithmetic. The result of an
3615 // Assign or AddAssign is not an lvalue so they can be ignored.
3616
3617 // (x + n) or (n + x) => x
3618 if (BO->getOpcode() == BinaryOperator::Add) {
3619 if (BO->getLHS()->getType()->isPointerType()) {
3620 return getPrimaryDecl(BO->getLHS());
3621 } else if (BO->getRHS()->getType()->isPointerType()) {
3622 return getPrimaryDecl(BO->getRHS());
3623 }
3624 }
3625
3626 return 0;
3627 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003628 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003629 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003630 case Stmt::ImplicitCastExprClass:
3631 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003632 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003633 default:
3634 return 0;
3635 }
3636}
3637
3638/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00003639/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00003640/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003641/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00003642/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003643/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00003644/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003645QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003646 if (op->isTypeDependent())
3647 return Context.DependentTy;
3648
Steve Naroff08f19672008-01-13 17:10:08 +00003649 if (getLangOptions().C99) {
3650 // Implement C99-only parts of addressof rules.
3651 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3652 if (uOp->getOpcode() == UnaryOperator::Deref)
3653 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3654 // (assuming the deref expression is valid).
3655 return uOp->getSubExpr()->getType();
3656 }
3657 // Technically, there should be a check for array subscript
3658 // expressions here, but the result of one is always an lvalue anyway.
3659 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003660 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003661 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003662
Reid Spencer5f016e22007-07-11 17:01:13 +00003663 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003664 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3665 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003666 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3667 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003668 return QualType();
3669 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003670 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003671 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3672 if (Field->isBitField()) {
3673 Diag(OpLoc, diag::err_typecheck_address_of)
3674 << "bit-field" << op->getSourceRange();
3675 return QualType();
3676 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003677 }
3678 // Check for Apple extension for accessing vector components.
Nate Begemanb104b1f2009-02-15 22:45:20 +00003679 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3680 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003681 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00003682 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003683 return QualType();
3684 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00003685 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00003686 // with the register storage-class specifier.
3687 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3688 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003689 Diag(OpLoc, diag::err_typecheck_address_of)
3690 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003691 return QualType();
3692 }
Douglas Gregor29882052008-12-10 21:26:49 +00003693 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003694 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003695 } else if (isa<FieldDecl>(dcl)) {
3696 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00003697 // Could be a pointer to member, though, if there is an explicit
3698 // scope qualifier for the class.
3699 if (isa<QualifiedDeclRefExpr>(op)) {
3700 DeclContext *Ctx = dcl->getDeclContext();
3701 if (Ctx && Ctx->isRecord())
3702 return Context.getMemberPointerType(op->getType(),
3703 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3704 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003705 } else if (isa<FunctionDecl>(dcl)) {
3706 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00003707 // As above.
3708 if (isa<QualifiedDeclRefExpr>(op)) {
3709 DeclContext *Ctx = dcl->getDeclContext();
3710 if (Ctx && Ctx->isRecord())
3711 return Context.getMemberPointerType(op->getType(),
3712 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3713 }
Douglas Gregor29882052008-12-10 21:26:49 +00003714 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003715 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003716 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003717 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00003718
Reid Spencer5f016e22007-07-11 17:01:13 +00003719 // If the operand has type "type", the result has type "pointer to type".
3720 return Context.getPointerType(op->getType());
3721}
3722
Chris Lattner22caddc2008-11-23 09:13:29 +00003723QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00003724 if (Op->isTypeDependent())
3725 return Context.DependentTy;
3726
Chris Lattner22caddc2008-11-23 09:13:29 +00003727 UsualUnaryConversions(Op);
3728 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003729
Chris Lattner22caddc2008-11-23 09:13:29 +00003730 // Note that per both C89 and C99, this is always legal, even if ptype is an
3731 // incomplete type or void. It would be possible to warn about dereferencing
3732 // a void pointer, but it's completely well-defined, and such a warning is
3733 // unlikely to catch any mistakes.
3734 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003735 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003736
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003737 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003738 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003739 return QualType();
3740}
3741
3742static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3743 tok::TokenKind Kind) {
3744 BinaryOperator::Opcode Opc;
3745 switch (Kind) {
3746 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00003747 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3748 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003749 case tok::star: Opc = BinaryOperator::Mul; break;
3750 case tok::slash: Opc = BinaryOperator::Div; break;
3751 case tok::percent: Opc = BinaryOperator::Rem; break;
3752 case tok::plus: Opc = BinaryOperator::Add; break;
3753 case tok::minus: Opc = BinaryOperator::Sub; break;
3754 case tok::lessless: Opc = BinaryOperator::Shl; break;
3755 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3756 case tok::lessequal: Opc = BinaryOperator::LE; break;
3757 case tok::less: Opc = BinaryOperator::LT; break;
3758 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3759 case tok::greater: Opc = BinaryOperator::GT; break;
3760 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3761 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3762 case tok::amp: Opc = BinaryOperator::And; break;
3763 case tok::caret: Opc = BinaryOperator::Xor; break;
3764 case tok::pipe: Opc = BinaryOperator::Or; break;
3765 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3766 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3767 case tok::equal: Opc = BinaryOperator::Assign; break;
3768 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3769 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3770 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3771 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3772 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3773 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3774 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3775 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3776 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3777 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3778 case tok::comma: Opc = BinaryOperator::Comma; break;
3779 }
3780 return Opc;
3781}
3782
3783static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3784 tok::TokenKind Kind) {
3785 UnaryOperator::Opcode Opc;
3786 switch (Kind) {
3787 default: assert(0 && "Unknown unary op!");
3788 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3789 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3790 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3791 case tok::star: Opc = UnaryOperator::Deref; break;
3792 case tok::plus: Opc = UnaryOperator::Plus; break;
3793 case tok::minus: Opc = UnaryOperator::Minus; break;
3794 case tok::tilde: Opc = UnaryOperator::Not; break;
3795 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003796 case tok::kw___real: Opc = UnaryOperator::Real; break;
3797 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3798 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3799 }
3800 return Opc;
3801}
3802
Douglas Gregoreaebc752008-11-06 23:29:22 +00003803/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3804/// operator @p Opc at location @c TokLoc. This routine only supports
3805/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003806Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3807 unsigned Op,
3808 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003809 QualType ResultTy; // Result type of the binary operator.
3810 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3811 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3812
3813 switch (Opc) {
3814 default:
3815 assert(0 && "Unknown binary expr!");
3816 case BinaryOperator::Assign:
3817 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3818 break;
Sebastian Redl22460502009-02-07 00:15:38 +00003819 case BinaryOperator::PtrMemD:
3820 case BinaryOperator::PtrMemI:
3821 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3822 Opc == BinaryOperator::PtrMemI);
3823 break;
3824 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00003825 case BinaryOperator::Div:
3826 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3827 break;
3828 case BinaryOperator::Rem:
3829 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3830 break;
3831 case BinaryOperator::Add:
3832 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3833 break;
3834 case BinaryOperator::Sub:
3835 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3836 break;
Sebastian Redl22460502009-02-07 00:15:38 +00003837 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00003838 case BinaryOperator::Shr:
3839 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3840 break;
3841 case BinaryOperator::LE:
3842 case BinaryOperator::LT:
3843 case BinaryOperator::GE:
3844 case BinaryOperator::GT:
3845 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3846 break;
3847 case BinaryOperator::EQ:
3848 case BinaryOperator::NE:
3849 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3850 break;
3851 case BinaryOperator::And:
3852 case BinaryOperator::Xor:
3853 case BinaryOperator::Or:
3854 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3855 break;
3856 case BinaryOperator::LAnd:
3857 case BinaryOperator::LOr:
3858 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3859 break;
3860 case BinaryOperator::MulAssign:
3861 case BinaryOperator::DivAssign:
3862 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3863 if (!CompTy.isNull())
3864 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3865 break;
3866 case BinaryOperator::RemAssign:
3867 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3868 if (!CompTy.isNull())
3869 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3870 break;
3871 case BinaryOperator::AddAssign:
3872 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3873 if (!CompTy.isNull())
3874 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3875 break;
3876 case BinaryOperator::SubAssign:
3877 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3878 if (!CompTy.isNull())
3879 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3880 break;
3881 case BinaryOperator::ShlAssign:
3882 case BinaryOperator::ShrAssign:
3883 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3884 if (!CompTy.isNull())
3885 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3886 break;
3887 case BinaryOperator::AndAssign:
3888 case BinaryOperator::XorAssign:
3889 case BinaryOperator::OrAssign:
3890 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3891 if (!CompTy.isNull())
3892 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3893 break;
3894 case BinaryOperator::Comma:
3895 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3896 break;
3897 }
3898 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003899 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003900 if (CompTy.isNull())
3901 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3902 else
3903 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003904 CompTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00003905}
3906
Reid Spencer5f016e22007-07-11 17:01:13 +00003907// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003908Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3909 tok::TokenKind Kind,
3910 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003911 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003912 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00003913
Steve Narofff69936d2007-09-16 03:34:24 +00003914 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3915 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003916
Douglas Gregor898574e2008-12-05 23:32:09 +00003917 // If either expression is type-dependent, just build the AST.
3918 // FIXME: We'll need to perform some caching of the result of name
3919 // lookup for operator+.
3920 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00003921 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3922 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003923 Context.DependentTy,
3924 Context.DependentTy, TokLoc));
Steve Naroff6ece14c2009-01-21 00:14:39 +00003925 else
Sebastian Redl22460502009-02-07 00:15:38 +00003926 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3927 Context.DependentTy, TokLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00003928 }
3929
Sebastian Redl22460502009-02-07 00:15:38 +00003930 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregoreaebc752008-11-06 23:29:22 +00003931 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3932 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003933 // If this is one of the assignment operators, we only perform
3934 // overload resolution if the left-hand side is a class or
3935 // enumeration type (C++ [expr.ass]p3).
3936 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3937 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3938 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3939 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003940
Douglas Gregoreaebc752008-11-06 23:29:22 +00003941 // Determine which overloaded operator we're dealing with.
3942 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl22460502009-02-07 00:15:38 +00003943 // Overloading .* is not possible.
3944 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregoreaebc752008-11-06 23:29:22 +00003945 OO_Star, OO_Slash, OO_Percent,
3946 OO_Plus, OO_Minus,
3947 OO_LessLess, OO_GreaterGreater,
3948 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3949 OO_EqualEqual, OO_ExclaimEqual,
3950 OO_Amp,
3951 OO_Caret,
3952 OO_Pipe,
3953 OO_AmpAmp,
3954 OO_PipePipe,
3955 OO_Equal, OO_StarEqual,
3956 OO_SlashEqual, OO_PercentEqual,
3957 OO_PlusEqual, OO_MinusEqual,
3958 OO_LessLessEqual, OO_GreaterGreaterEqual,
3959 OO_AmpEqual, OO_CaretEqual,
3960 OO_PipeEqual,
3961 OO_Comma
3962 };
3963 OverloadedOperatorKind OverOp = OverOps[Opc];
3964
Mike Stumpeed9cac2009-02-19 03:04:26 +00003965 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor96176b32008-11-18 23:14:02 +00003966 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003967 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003968 Expr *Args[2] = { lhs, rhs };
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003969 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3970 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003971
3972 // Perform overload resolution.
3973 OverloadCandidateSet::iterator Best;
3974 switch (BestViableFunction(CandidateSet, Best)) {
3975 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003976 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003977 FunctionDecl *FnDecl = Best->Function;
3978
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003979 if (FnDecl) {
3980 // We matched an overloaded operator. Build a call to that
3981 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003982
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003983 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003984 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3985 if (PerformObjectArgumentInitialization(lhs, Method) ||
3986 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3987 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003988 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003989 } else {
3990 // Convert the arguments.
3991 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3992 "passing") ||
3993 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3994 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003995 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003996 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003997
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003998 // Determine the result type
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003999 QualType ResultTy
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004000 = FnDecl->getType()->getAsFunctionType()->getResultType();
4001 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004002
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004003 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004004 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4005 SourceLocation());
Douglas Gregorb4609802008-11-14 16:09:21 +00004006 UsualUnaryConversions(FnExpr);
4007
Mike Stumpeed9cac2009-02-19 03:04:26 +00004008 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004009 ResultTy, TokLoc));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004010 } else {
4011 // We matched a built-in operator. Convert the arguments, then
4012 // break out so that we will build the appropriate built-in
4013 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004014 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
4015 Best->Conversions[0], "passing") ||
4016 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
4017 Best->Conversions[1], "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004018 return ExprError();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004019
4020 break;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004021 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00004022 }
4023
4024 case OR_No_Viable_Function:
4025 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004026 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00004027 break;
4028
4029 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004030 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
4031 << BinaryOperator::getOpcodeStr(Opc)
4032 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00004033 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004034 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004035
4036 case OR_Deleted:
4037 Diag(TokLoc, diag::err_ovl_deleted_oper)
4038 << Best->Function->isDeleted()
4039 << BinaryOperator::getOpcodeStr(Opc)
4040 << lhs->getSourceRange() << rhs->getSourceRange();
4041 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4042 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00004043 }
4044
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004045 // Either we found no viable overloaded operator or we matched a
4046 // built-in operator. In either case, fall through to trying to
4047 // build a built-in operation.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004048 }
4049
Douglas Gregoreaebc752008-11-06 23:29:22 +00004050 // Build a built-in binary operation.
4051 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00004052}
4053
4054// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl0eb23302009-01-19 00:08:26 +00004055Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4056 tok::TokenKind Op, ExprArg input) {
4057 // FIXME: Input is modified later, but smart pointer not reassigned.
4058 Expr *Input = (Expr*)input.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00004059 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00004060
4061 if (getLangOptions().CPlusPlus &&
Mike Stumpeed9cac2009-02-19 03:04:26 +00004062 (Input->getType()->isRecordType()
Douglas Gregor74253732008-11-19 15:42:04 +00004063 || Input->getType()->isEnumeralType())) {
4064 // Determine which overloaded operator we're dealing with.
4065 static const OverloadedOperatorKind OverOps[] = {
4066 OO_None, OO_None,
4067 OO_PlusPlus, OO_MinusMinus,
4068 OO_Amp, OO_Star,
4069 OO_Plus, OO_Minus,
4070 OO_Tilde, OO_Exclaim,
4071 OO_None, OO_None,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004072 OO_None,
Douglas Gregor74253732008-11-19 15:42:04 +00004073 OO_None
4074 };
4075 OverloadedOperatorKind OverOp = OverOps[Opc];
4076
Mike Stumpeed9cac2009-02-19 03:04:26 +00004077 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor74253732008-11-19 15:42:04 +00004078 // to the candidate set.
4079 OverloadCandidateSet CandidateSet;
Douglas Gregorf680a0f2009-02-04 16:44:47 +00004080 if (OverOp != OO_None &&
4081 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4082 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00004083
4084 // Perform overload resolution.
4085 OverloadCandidateSet::iterator Best;
4086 switch (BestViableFunction(CandidateSet, Best)) {
4087 case OR_Success: {
4088 // We found a built-in operator or an overloaded operator.
4089 FunctionDecl *FnDecl = Best->Function;
4090
4091 if (FnDecl) {
4092 // We matched an overloaded operator. Build a call to that
4093 // operator.
4094
4095 // Convert the arguments.
4096 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4097 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004098 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00004099 } else {
4100 // Convert the arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004101 if (PerformCopyInitialization(Input,
Douglas Gregor74253732008-11-19 15:42:04 +00004102 FnDecl->getParamDecl(0)->getType(),
4103 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004104 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00004105 }
4106
4107 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00004108 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00004109 = FnDecl->getType()->getAsFunctionType()->getResultType();
4110 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00004111
Douglas Gregor74253732008-11-19 15:42:04 +00004112 // Build the actual expression node.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004113 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff6ece14c2009-01-21 00:14:39 +00004114 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00004115 UsualUnaryConversions(FnExpr);
4116
Sebastian Redl0eb23302009-01-19 00:08:26 +00004117 input.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004118 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4119 1, ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00004120 } else {
4121 // We matched a built-in operator. Convert the arguments, then
4122 // break out so that we will build the appropriate built-in
4123 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004124 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4125 Best->Conversions[0], "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004126 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00004127
4128 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00004129 }
Douglas Gregor74253732008-11-19 15:42:04 +00004130 }
4131
4132 case OR_No_Viable_Function:
4133 // No viable function; fall through to handling this as a
4134 // built-in operator, which will produce an error message for us.
4135 break;
4136
4137 case OR_Ambiguous:
4138 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4139 << UnaryOperator::getOpcodeStr(Opc)
4140 << Input->getSourceRange();
4141 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004142 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004143
4144 case OR_Deleted:
4145 Diag(OpLoc, diag::err_ovl_deleted_oper)
4146 << Best->Function->isDeleted()
4147 << UnaryOperator::getOpcodeStr(Opc)
4148 << Input->getSourceRange();
4149 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4150 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00004151 }
4152
4153 // Either we found no viable overloaded operator or we matched a
4154 // built-in operator. In either case, fall through to trying to
Sebastian Redl0eb23302009-01-19 00:08:26 +00004155 // build a built-in operation.
Douglas Gregor74253732008-11-19 15:42:04 +00004156 }
4157
Reid Spencer5f016e22007-07-11 17:01:13 +00004158 QualType resultType;
4159 switch (Opc) {
4160 default:
4161 assert(0 && "Unimplemented unary expr!");
4162 case UnaryOperator::PreInc:
4163 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004164 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4165 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004166 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004167 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00004168 resultType = CheckAddressOfOperand(Input, OpLoc);
4169 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004170 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00004171 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00004172 resultType = CheckIndirectionOperand(Input, OpLoc);
4173 break;
4174 case UnaryOperator::Plus:
4175 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004176 UsualUnaryConversions(Input);
4177 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004178 if (resultType->isDependentType())
4179 break;
Douglas Gregor74253732008-11-19 15:42:04 +00004180 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4181 break;
4182 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4183 resultType->isEnumeralType())
4184 break;
4185 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4186 Opc == UnaryOperator::Plus &&
4187 resultType->isPointerType())
4188 break;
4189
Sebastian Redl0eb23302009-01-19 00:08:26 +00004190 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4191 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004192 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004193 UsualUnaryConversions(Input);
4194 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004195 if (resultType->isDependentType())
4196 break;
Chris Lattner02a65142008-07-25 23:52:49 +00004197 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4198 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4199 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004200 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004201 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00004202 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004203 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4204 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004205 break;
4206 case UnaryOperator::LNot: // logical negation
4207 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004208 DefaultFunctionArrayConversion(Input);
4209 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004210 if (resultType->isDependentType())
4211 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004212 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00004213 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4214 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004215 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00004216 // In C++, it's bool. C++ 5.3.1p8
4217 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004218 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00004219 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00004220 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00004221 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00004222 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004223 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00004224 resultType = Input->getType();
4225 break;
4226 }
4227 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004228 return ExprError();
4229 input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004230 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004231}
4232
Steve Naroff1b273c42007-09-16 14:56:35 +00004233/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stumpeed9cac2009-02-19 03:04:26 +00004234Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00004235 SourceLocation LabLoc,
4236 IdentifierInfo *LabelII) {
4237 // Look up the record for this label identifier.
Steve Narofff3cf8972009-02-28 16:48:43 +00004238 llvm::DenseMap<IdentifierInfo*, Action::StmtTy*>::iterator I =
4239 ActiveScope->LabelMap.find(LabelII);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004240
Steve Narofff3cf8972009-02-28 16:48:43 +00004241 LabelStmt *LabelDecl;
4242
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00004243 // If we haven't seen this label yet, create a forward reference. It
4244 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Narofff3cf8972009-02-28 16:48:43 +00004245 if (I == ActiveScope->LabelMap.end()) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00004246 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004247
Steve Narofff3cf8972009-02-28 16:48:43 +00004248 ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl));
4249 } else
4250 LabelDecl = static_cast<LabelStmt *>(I->second);
4251
Reid Spencer5f016e22007-07-11 17:01:13 +00004252 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004253 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4254 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00004255}
4256
Steve Naroff1b273c42007-09-16 14:56:35 +00004257Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004258 SourceLocation RPLoc) { // "({..})"
4259 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4260 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4261 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4262
Eli Friedmandca2b732009-01-24 23:09:00 +00004263 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4264 if (isFileScope) {
4265 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4266 }
4267
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004268 // FIXME: there are a variety of strange constraints to enforce here, for
4269 // example, it is not possible to goto into a stmt expression apparently.
4270 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004271
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004272 // FIXME: the last statement in the compount stmt has its value used. We
4273 // should not warn about it being unused.
4274
4275 // If there are sub stmts in the compound stmt, take the type of the last one
4276 // as the type of the stmtexpr.
4277 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004278
Chris Lattner611b2ec2008-07-26 19:51:01 +00004279 if (!Compound->body_empty()) {
4280 Stmt *LastStmt = Compound->body_back();
4281 // If LastStmt is a label, skip down through into the body.
4282 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4283 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004284
Chris Lattner611b2ec2008-07-26 19:51:01 +00004285 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004286 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00004287 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004288
Steve Naroff6ece14c2009-01-21 00:14:39 +00004289 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004290}
Steve Naroffd34e9152007-08-01 22:05:33 +00004291
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004292Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4293 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004294 SourceLocation TypeLoc,
4295 TypeTy *argty,
4296 OffsetOfComponent *CompPtr,
4297 unsigned NumComponents,
4298 SourceLocation RPLoc) {
4299 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4300 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004301
Sebastian Redl28507842009-02-26 14:39:58 +00004302 bool Dependent = ArgTy->isDependentType();
4303
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004304 // We must have at least one component that refers to the type, and the first
4305 // one is known to be a field designator. Verify that the ArgTy represents
4306 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00004307 if (!Dependent && !ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00004308 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004309
Eli Friedman35183ac2009-02-27 06:44:11 +00004310 // Otherwise, create a null pointer as the base, and iteratively process
4311 // the offsetof designators.
4312 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4313 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
4314 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
4315 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00004316
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004317 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4318 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00004319 // FIXME: This diagnostic isn't actually visible because the location is in
4320 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004321 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004322 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4323 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004324
Sebastian Redl28507842009-02-26 14:39:58 +00004325 if (!Dependent) {
4326 // FIXME: Dependent case loses a lot of information here. And probably
4327 // leaks like a sieve.
4328 for (unsigned i = 0; i != NumComponents; ++i) {
4329 const OffsetOfComponent &OC = CompPtr[i];
4330 if (OC.isBrackets) {
4331 // Offset of an array sub-field. TODO: Should we allow vector elements?
4332 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4333 if (!AT) {
4334 Res->Destroy(Context);
4335 return Diag(OC.LocEnd, diag::err_offsetof_array_type)
4336 << Res->getType();
4337 }
4338
4339 // FIXME: C++: Verify that operator[] isn't overloaded.
4340
Eli Friedman35183ac2009-02-27 06:44:11 +00004341 // Promote the array so it looks more like a normal array subscript
4342 // expression.
4343 DefaultFunctionArrayConversion(Res);
4344
Sebastian Redl28507842009-02-26 14:39:58 +00004345 // C99 6.5.2.1p1
4346 Expr *Idx = static_cast<Expr*>(OC.U.E);
4347 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4348 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4349 << Idx->getSourceRange();
4350
4351 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4352 OC.LocEnd);
4353 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004354 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004355
Sebastian Redl28507842009-02-26 14:39:58 +00004356 const RecordType *RC = Res->getType()->getAsRecordType();
4357 if (!RC) {
4358 Res->Destroy(Context);
4359 return Diag(OC.LocEnd, diag::err_offsetof_record_type)
4360 << Res->getType();
4361 }
Chris Lattner704fe352007-08-30 17:59:59 +00004362
Sebastian Redl28507842009-02-26 14:39:58 +00004363 // Get the decl corresponding to this.
4364 RecordDecl *RD = RC->getDecl();
4365 FieldDecl *MemberDecl
4366 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4367 LookupMemberName)
4368 .getAsDecl());
4369 if (!MemberDecl)
4370 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4371 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004372
Sebastian Redl28507842009-02-26 14:39:58 +00004373 // FIXME: C++: Verify that MemberDecl isn't a static field.
4374 // FIXME: Verify that MemberDecl isn't a bitfield.
4375 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4376 // matter here.
4377 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004378 MemberDecl->getType().getNonReferenceType());
Sebastian Redl28507842009-02-26 14:39:58 +00004379 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004380 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004381
4382 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004383 Context.getSizeType(), BuiltinLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004384}
4385
4386
Mike Stumpeed9cac2009-02-19 03:04:26 +00004387Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00004388 TypeTy *arg1, TypeTy *arg2,
4389 SourceLocation RPLoc) {
4390 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4391 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004392
Steve Naroffd34e9152007-08-01 22:05:33 +00004393 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004394
4395 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004396 argT2, RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00004397}
4398
Mike Stumpeed9cac2009-02-19 03:04:26 +00004399Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00004400 ExprTy *expr1, ExprTy *expr2,
4401 SourceLocation RPLoc) {
4402 Expr *CondExpr = static_cast<Expr*>(cond);
4403 Expr *LHSExpr = static_cast<Expr*>(expr1);
4404 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004405
Steve Naroffd04fdd52007-08-03 21:21:27 +00004406 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4407
Sebastian Redl28507842009-02-26 14:39:58 +00004408 QualType resType;
4409 if (CondExpr->isValueDependent()) {
4410 resType = Context.DependentTy;
4411 } else {
4412 // The conditional expression is required to be a constant expression.
4413 llvm::APSInt condEval(32);
4414 SourceLocation ExpLoc;
4415 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4416 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4417 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00004418
Sebastian Redl28507842009-02-26 14:39:58 +00004419 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4420 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4421 }
4422
Mike Stumpeed9cac2009-02-19 03:04:26 +00004423 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004424 resType, RPLoc);
Steve Naroffd04fdd52007-08-03 21:21:27 +00004425}
4426
Steve Naroff4eb206b2008-09-03 18:15:37 +00004427//===----------------------------------------------------------------------===//
4428// Clang Extensions.
4429//===----------------------------------------------------------------------===//
4430
4431/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004432void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004433 // Analyze block parameters.
4434 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004435
Steve Naroff4eb206b2008-09-03 18:15:37 +00004436 // Add BSI to CurBlock.
4437 BSI->PrevBlockInfo = CurBlock;
4438 CurBlock = BSI;
Steve Narofff3cf8972009-02-28 16:48:43 +00004439 ActiveScope = BlockScope;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004440
Steve Naroff4eb206b2008-09-03 18:15:37 +00004441 BSI->ReturnType = 0;
4442 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00004443 BSI->hasBlockDeclRefExprs = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004444
Steve Naroff090276f2008-10-10 01:28:17 +00004445 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004446 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004447}
4448
Mike Stump98eb8a72009-02-04 22:31:32 +00004449void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4450 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4451
4452 if (ParamInfo.getNumTypeObjects() == 0
4453 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4454 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4455
4456 // The type is entirely optional as well, if none, use DependentTy.
4457 if (T.isNull())
4458 T = Context.DependentTy;
4459
4460 // The parameter list is optional, if there was none, assume ().
4461 if (!T->isFunctionType())
4462 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4463
4464 CurBlock->hasPrototype = true;
4465 CurBlock->isVariadic = false;
4466 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4467 .getTypePtr();
4468
4469 if (!RetTy->isDependentType())
4470 CurBlock->ReturnType = RetTy;
4471 return;
4472 }
4473
Steve Naroff4eb206b2008-09-03 18:15:37 +00004474 // Analyze arguments to block.
4475 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4476 "Not a function declarator!");
4477 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004478
Steve Naroff090276f2008-10-10 01:28:17 +00004479 CurBlock->hasPrototype = FTI.hasPrototype;
4480 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004481
Steve Naroff4eb206b2008-09-03 18:15:37 +00004482 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4483 // no arguments, not a function that takes a single void argument.
4484 if (FTI.hasPrototype &&
4485 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4486 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4487 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4488 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004489 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004490 } else if (FTI.hasPrototype) {
4491 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004492 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4493 CurBlock->isVariadic = FTI.isVariadic;
Mike Stump98eb8a72009-02-04 22:31:32 +00004494 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4495
4496 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4497 .getTypePtr();
4498
4499 if (!RetTy->isDependentType())
4500 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004501 }
Steve Naroff090276f2008-10-10 01:28:17 +00004502 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004503
Steve Naroff090276f2008-10-10 01:28:17 +00004504 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4505 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4506 // If this has an identifier, add it to the scope stack.
4507 if ((*AI)->getIdentifier())
4508 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004509}
4510
4511/// ActOnBlockError - If there is an error parsing a block, this callback
4512/// is invoked to pop the information about the block from the action impl.
4513void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4514 // Ensure that CurBlock is deleted.
4515 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004516
Steve Naroff4eb206b2008-09-03 18:15:37 +00004517 // Pop off CurBlock, handle nested blocks.
4518 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004519
Steve Naroff4eb206b2008-09-03 18:15:37 +00004520 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stumpeed9cac2009-02-19 03:04:26 +00004521
Steve Naroff4eb206b2008-09-03 18:15:37 +00004522}
4523
4524/// ActOnBlockStmtExpr - This is called when the body of a block statement
4525/// literal was successfully completed. ^(int x){...}
4526Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4527 Scope *CurScope) {
4528 // Ensure that CurBlock is deleted.
4529 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004530 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff4eb206b2008-09-03 18:15:37 +00004531
Steve Naroff090276f2008-10-10 01:28:17 +00004532 PopDeclContext();
4533
Steve Naroffb098c142009-02-28 21:01:15 +00004534 // Before poping CurBlock, set ActiveScope to this scopes parent.
4535 ActiveScope = CurBlock->TheScope->getParent();
4536
Steve Naroff4eb206b2008-09-03 18:15:37 +00004537 // Pop off CurBlock, handle nested blocks.
4538 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004539
Steve Naroff4eb206b2008-09-03 18:15:37 +00004540 QualType RetTy = Context.VoidTy;
4541 if (BSI->ReturnType)
4542 RetTy = QualType(BSI->ReturnType, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004543
Steve Naroff4eb206b2008-09-03 18:15:37 +00004544 llvm::SmallVector<QualType, 8> ArgTypes;
4545 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4546 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004547
Steve Naroff4eb206b2008-09-03 18:15:37 +00004548 QualType BlockTy;
4549 if (!BSI->hasPrototype)
Douglas Gregor72564e72009-02-26 23:50:07 +00004550 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004551 else
4552 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004553 BSI->isVariadic, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004554
Steve Naroff4eb206b2008-09-03 18:15:37 +00004555 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004556
Steve Naroff1c90bfc2008-10-08 18:44:00 +00004557 BSI->TheDecl->setBody(Body.take());
Mike Stumpb83d2872009-02-19 22:01:56 +00004558 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004559}
4560
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004561Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4562 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004563 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004564 Expr *E = static_cast<Expr*>(expr);
4565 QualType T = QualType::getFromOpaquePtr(type);
4566
4567 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004568
4569 // Get the va_list type
4570 QualType VaListType = Context.getBuiltinVaListType();
4571 // Deal with implicit array decay; for example, on x86-64,
4572 // va_list is an array, but it's supposed to decay to
4573 // a pointer for va_arg.
4574 if (VaListType->isArrayType())
4575 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004576 // Make sure the input expression also decays appropriately.
4577 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004578
4579 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004580 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004581 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004582 << E->getType() << E->getSourceRange();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004583
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004584 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004585
Steve Naroff6ece14c2009-01-21 00:14:39 +00004586 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004587}
4588
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004589Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4590 // The type of __null will be int or long, depending on the size of
4591 // pointers on the target.
4592 QualType Ty;
4593 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4594 Ty = Context.IntTy;
4595 else
4596 Ty = Context.LongTy;
4597
Steve Naroff6ece14c2009-01-21 00:14:39 +00004598 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004599}
4600
Chris Lattner5cf216b2008-01-04 18:04:52 +00004601bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4602 SourceLocation Loc,
4603 QualType DstType, QualType SrcType,
4604 Expr *SrcExpr, const char *Flavor) {
4605 // Decode the result (notice that AST's are still created for extensions).
4606 bool isInvalid = false;
4607 unsigned DiagKind;
4608 switch (ConvTy) {
4609 default: assert(0 && "Unknown conversion type");
4610 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004611 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004612 DiagKind = diag::ext_typecheck_convert_pointer_int;
4613 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004614 case IntToPointer:
4615 DiagKind = diag::ext_typecheck_convert_int_pointer;
4616 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004617 case IncompatiblePointer:
4618 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4619 break;
4620 case FunctionVoidPointer:
4621 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4622 break;
4623 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004624 // If the qualifiers lost were because we were applying the
4625 // (deprecated) C++ conversion from a string literal to a char*
4626 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4627 // Ideally, this check would be performed in
4628 // CheckPointerTypesForAssignment. However, that would require a
4629 // bit of refactoring (so that the second argument is an
4630 // expression, rather than a type), which should be done as part
4631 // of a larger effort to fix CheckPointerTypesForAssignment for
4632 // C++ semantics.
4633 if (getLangOptions().CPlusPlus &&
4634 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4635 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004636 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4637 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004638 case IntToBlockPointer:
4639 DiagKind = diag::err_int_to_block_pointer;
4640 break;
4641 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004642 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004643 break;
Steve Naroff39579072008-10-14 22:18:38 +00004644 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00004645 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00004646 // it can give a more specific diagnostic.
4647 DiagKind = diag::warn_incompatible_qualified_id;
4648 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004649 case IncompatibleVectors:
4650 DiagKind = diag::warn_incompatible_vectors;
4651 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004652 case Incompatible:
4653 DiagKind = diag::err_typecheck_convert_incompatible;
4654 isInvalid = true;
4655 break;
4656 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004657
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004658 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4659 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004660 return isInvalid;
4661}
Anders Carlssone21555e2008-11-30 19:50:32 +00004662
4663bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4664{
4665 Expr::EvalResult EvalResult;
4666
Mike Stumpeed9cac2009-02-19 03:04:26 +00004667 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00004668 EvalResult.HasSideEffects) {
4669 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4670
4671 if (EvalResult.Diag) {
4672 // We only show the note if it's not the usual "invalid subexpression"
4673 // or if it's actually in a subexpression.
4674 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4675 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4676 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4677 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004678
Anders Carlssone21555e2008-11-30 19:50:32 +00004679 return true;
4680 }
4681
4682 if (EvalResult.Diag) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004683 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssone21555e2008-11-30 19:50:32 +00004684 E->getSourceRange();
4685
4686 // Print the reason it's not a constant.
4687 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4688 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4689 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004690
Anders Carlssone21555e2008-11-30 19:50:32 +00004691 if (Result)
4692 *Result = EvalResult.Val.getInt();
4693 return false;
4694}