blob: 8b646e9943f325c96ee2fca6cecc50c627b3aa61 [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) {
Douglas Gregorbad35182009-03-19 03:51:16 +0000442 if (SS && !SS->isEmpty()) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000443 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
444 ValueDependent, SS->getRange(),
Douglas Gregor35073692009-03-26 23:56:24 +0000445 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregorbad35182009-03-19 03:51:16 +0000446 } else
Steve Naroff6ece14c2009-01-21 00:14:39 +0000447 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 Gregor5953d8b2009-03-19 17:26:29 +0000612
613 // C++ [temp.dep.expr]p3:
614 // An id-expression is type-dependent if it contains:
615 // -- a nested-name-specifier that contains a class-name that
616 // names a dependent type.
617 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000618 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
619 Loc, SS->getRange(),
Douglas Gregor35073692009-03-26 23:56:24 +0000620 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000621 }
622
Douglas Gregor3e41d602009-02-13 23:20:09 +0000623 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
624 false, true, Loc);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000625
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000626 NamedDecl *D = 0;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000627 if (Lookup.isAmbiguous()) {
628 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
629 SS && SS->isSet() ? SS->getRange()
630 : SourceRange());
631 return ExprError();
632 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +0000633 D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000634
Chris Lattner8a934232008-03-31 00:36:02 +0000635 // If this reference is in an Objective-C method, then ivar lookup happens as
636 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000637 IdentifierInfo *II = Name.getAsIdentifierInfo();
638 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000639 // There are two cases to handle here. 1) scoped lookup could have failed,
640 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000641 // found a decl, but that decl is outside the current instance method (i.e.
642 // a global variable). In these two cases, we do a lookup for an ivar with
643 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000644 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000645 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000646 ObjCInterfaceDecl *ClassDeclared;
647 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000648 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000649 if (DiagnoseUseOfDecl(IV, Loc))
650 return ExprError();
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000651 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
652 // If a class method attemps to use a free standing ivar, this is
653 // an error.
654 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
655 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
656 << IV->getDeclName());
657 // If a class method uses a global variable, even if an ivar with
658 // same name exists, use the global.
659 if (!IsClsMethod) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000660 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
661 ClassDeclared != IFace)
662 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000663 // FIXME: This should use a new expr for a direct reference, don't turn
664 // this into Self->ivar, just return a BareIVarExpr or something.
665 IdentifierInfo &II = Context.Idents.get("self");
666 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
667 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
668 Loc, static_cast<Expr*>(SelfExpr.release()),
669 true, true);
670 Context.setFieldDecl(IFace, IV, MRef);
671 return Owned(MRef);
672 }
Chris Lattner8a934232008-03-31 00:36:02 +0000673 }
674 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000675 else if (getCurMethodDecl()->isInstanceMethod()) {
676 // We should warn if a local variable hides an ivar.
677 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000678 ObjCInterfaceDecl *ClassDeclared;
679 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
680 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
681 IFace == ClassDeclared)
682 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
683 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000684 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000685 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000686 if (D == 0 && II->isStr("super")) {
Steve Naroffdd53eb52009-03-05 20:12:00 +0000687 QualType T;
688
689 if (getCurMethodDecl()->isInstanceMethod())
690 T = Context.getPointerType(Context.getObjCInterfaceType(
691 getCurMethodDecl()->getClassInterface()));
692 else
693 T = Context.getObjCClassType();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000694 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000695 }
Chris Lattner8a934232008-03-31 00:36:02 +0000696 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000697
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000698 // Determine whether this name might be a candidate for
699 // argument-dependent lookup.
700 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
701 HasTrailingLParen;
702
703 if (ADL && D == 0) {
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000704 // We've seen something of the form
705 //
706 // identifier(
707 //
708 // and we did not find any entity by the name
709 // "identifier". However, this identifier is still subject to
710 // argument-dependent lookup, so keep track of the name.
711 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
712 Context.OverloadTy,
713 Loc));
714 }
715
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 if (D == 0) {
717 // Otherwise, this could be an implicitly declared function reference (legal
718 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000719 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000720 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000721 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 else {
723 // If this name wasn't predeclared and if this is not a function call,
724 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000725 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000726 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
727 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000728 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
729 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000730 return ExprError(Diag(Loc, diag::err_undeclared_use)
731 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000732 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000733 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 }
735 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000736
Sebastian Redlebc07d52009-02-03 20:19:35 +0000737 // If this is an expression of the form &Class::member, don't build an
738 // implicit member ref, because we want a pointer to the member in general,
739 // not any specific instance's member.
740 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000741 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000742 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000743 QualType DType;
744 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
745 DType = FD->getType().getNonReferenceType();
746 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
747 DType = Method->getType();
748 } else if (isa<OverloadedFunctionDecl>(D)) {
749 DType = Context.OverloadTy;
750 }
751 // Could be an inner type. That's diagnosed below, so ignore it here.
752 if (!DType.isNull()) {
753 // The pointer is type- and value-dependent if it points into something
754 // dependent.
755 bool Dependent = false;
756 for (; DC; DC = DC->getParent()) {
757 // FIXME: could stop early at namespace scope.
758 if (DC->isRecord()) {
759 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
760 if (Context.getTypeDeclType(Record)->isDependentType()) {
761 Dependent = true;
762 break;
763 }
764 }
765 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000766 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redlebc07d52009-02-03 20:19:35 +0000767 }
768 }
769 }
770
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000771 // We may have found a field within an anonymous union or struct
772 // (C++ [class.union]).
773 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
774 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
775 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000776
Douglas Gregor88a35142008-12-22 05:46:06 +0000777 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
778 if (!MD->isStatic()) {
779 // C++ [class.mfct.nonstatic]p2:
780 // [...] if name lookup (3.4.1) resolves the name in the
781 // id-expression to a nonstatic nontype member of class X or of
782 // a base class of X, the id-expression is transformed into a
783 // class member access expression (5.2.5) using (*this) (9.3.2)
784 // as the postfix-expression to the left of the '.' operator.
785 DeclContext *Ctx = 0;
786 QualType MemberType;
787 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
788 Ctx = FD->getDeclContext();
789 MemberType = FD->getType();
790
791 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
792 MemberType = RefType->getPointeeType();
793 else if (!FD->isMutable()) {
794 unsigned combinedQualifiers
795 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
796 MemberType = MemberType.getQualifiedType(combinedQualifiers);
797 }
798 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
799 if (!Method->isStatic()) {
800 Ctx = Method->getParent();
801 MemberType = Method->getType();
802 }
803 } else if (OverloadedFunctionDecl *Ovl
804 = dyn_cast<OverloadedFunctionDecl>(D)) {
805 for (OverloadedFunctionDecl::function_iterator
806 Func = Ovl->function_begin(),
807 FuncEnd = Ovl->function_end();
808 Func != FuncEnd; ++Func) {
809 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
810 if (!DMethod->isStatic()) {
811 Ctx = Ovl->getDeclContext();
812 MemberType = Context.OverloadTy;
813 break;
814 }
815 }
816 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000817
818 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000819 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
820 QualType ThisType = Context.getTagDeclType(MD->getParent());
821 if ((Context.getCanonicalType(CtxType)
822 == Context.getCanonicalType(ThisType)) ||
823 IsDerivedFrom(ThisType, CtxType)) {
824 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000825 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000826 MD->getThisType(Context));
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000827 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stumpeed9cac2009-02-19 03:04:26 +0000828 SourceLocation(), MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000829 }
830 }
831 }
832 }
833
Douglas Gregor44b43212008-12-11 16:49:14 +0000834 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000835 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
836 if (MD->isStatic())
837 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000838 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
839 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000840 }
841
Douglas Gregor88a35142008-12-22 05:46:06 +0000842 // Any other ways we could have found the field in a well-formed
843 // program would have been turned into implicit member expressions
844 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000845 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
846 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000847 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000848
Reid Spencer5f016e22007-07-11 17:01:13 +0000849 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000850 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000851 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000852 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000853 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000854 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000855
Steve Naroffdd972f22008-09-05 22:11:13 +0000856 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000857 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000858 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
859 false, false, SS));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000860 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
861 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
862 false, false, SS));
Steve Naroffdd972f22008-09-05 22:11:13 +0000863 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000864
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000865 // Check whether this declaration can be used. Note that we suppress
866 // this check when we're going to perform argument-dependent lookup
867 // on this function name, because this might not be the function
868 // that overload resolution actually selects.
869 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
870 return ExprError();
871
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000872 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000873 // Warn about constructs like:
874 // if (void *X = foo()) { ... } else { X }.
875 // In the else block, the pointer is always false.
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000876 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
877 Scope *CheckS = S;
878 while (CheckS) {
879 if (CheckS->isWithinElse() &&
880 CheckS->getControlParent()->isDeclScope(Var)) {
881 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000882 ExprError(Diag(Loc, diag::warn_value_always_false)
883 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000884 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000885 ExprError(Diag(Loc, diag::warn_value_always_zero)
886 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000887 break;
888 }
889
890 // Move up one more control parent to check again.
891 CheckS = CheckS->getControlParent();
892 if (CheckS)
893 CheckS = CheckS->getParent();
894 }
895 }
Douglas Gregor2224f842009-02-25 16:33:18 +0000896 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
897 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
898 // C99 DR 316 says that, if a function type comes from a
899 // function definition (without a prototype), that type is only
900 // used for checking compatibility. Therefore, when referencing
901 // the function, we pretend that we don't have the full function
902 // type.
903 QualType T = Func->getType();
904 QualType NoProtoType = T;
Douglas Gregor72564e72009-02-26 23:50:07 +0000905 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
906 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor2224f842009-02-25 16:33:18 +0000907 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
908 }
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000909 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000910
911 // Only create DeclRefExpr's for valid Decl's.
912 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000913 return ExprError();
914
Chris Lattner639e2d32008-10-20 05:16:36 +0000915 // If the identifier reference is inside a block, and it refers to a value
916 // that is outside the block, create a BlockDeclRefExpr instead of a
917 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
918 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000919 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000920 // We do not do this for things like enum constants, global variables, etc,
921 // as they do not get snapshotted.
922 //
923 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpb83d2872009-02-19 22:01:56 +0000924 // Blocks that have these can't be constant.
925 CurBlock->hasBlockDeclRefExprs = true;
926
Eli Friedman5fdeae12009-03-22 23:00:19 +0000927 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +0000928 // The BlocksAttr indicates the variable is bound by-reference.
929 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +0000930 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000931
Steve Naroff090276f2008-10-10 01:28:17 +0000932 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman5fdeae12009-03-22 23:00:19 +0000933 ExprTy.addConst();
934 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +0000935 }
936 // If this reference is not in a block or if the referenced variable is
937 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000938
Douglas Gregor898574e2008-12-05 23:32:09 +0000939 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000940 bool ValueDependent = false;
941 if (getLangOptions().CPlusPlus) {
942 // C++ [temp.dep.expr]p3:
943 // An id-expression is type-dependent if it contains:
944 // - an identifier that was declared with a dependent type,
945 if (VD->getType()->isDependentType())
946 TypeDependent = true;
947 // - FIXME: a template-id that is dependent,
948 // - a conversion-function-id that specifies a dependent type,
949 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
950 Name.getCXXNameType()->isDependentType())
951 TypeDependent = true;
952 // - a nested-name-specifier that contains a class-name that
953 // names a dependent type.
954 else if (SS && !SS->isEmpty()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000955 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor83f96f62008-12-10 20:57:37 +0000956 DC; DC = DC->getParent()) {
957 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000958 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000959 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
960 if (Context.getTypeDeclType(Record)->isDependentType()) {
961 TypeDependent = true;
962 break;
963 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000964 }
965 }
966 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000967
Douglas Gregor83f96f62008-12-10 20:57:37 +0000968 // C++ [temp.dep.constexpr]p2:
969 //
970 // An identifier is value-dependent if it is:
971 // - a name declared with a dependent type,
972 if (TypeDependent)
973 ValueDependent = true;
974 // - the name of a non-type template parameter,
975 else if (isa<NonTypeTemplateParmDecl>(VD))
976 ValueDependent = true;
977 // - a constant with integral or enumeration type and is
978 // initialized with an expression that is value-dependent
979 // (FIXME!).
980 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000981
Sebastian Redlcd965b92009-01-18 18:53:16 +0000982 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
983 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000984}
985
Sebastian Redlcd965b92009-01-18 18:53:16 +0000986Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
987 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000988 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000989
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000991 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000992 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
993 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
994 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000995 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000996
Chris Lattnerfa28b302008-01-12 08:14:25 +0000997 // Pre-defined identifiers are of type char[x], where x is the length of the
998 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000999 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +00001000 if (FunctionDecl *FD = getCurFunctionDecl())
1001 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001002 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1003 Length = MD->getSynthesizedMethodSize();
1004 else {
1005 Diag(Loc, diag::ext_predef_outside_function);
1006 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1007 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1008 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001009
1010
Chris Lattner8f978d52008-01-12 19:32:28 +00001011 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +00001012 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +00001013 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +00001014 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001015}
1016
Sebastian Redlcd965b92009-01-18 18:53:16 +00001017Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 llvm::SmallString<16> CharBuffer;
1019 CharBuffer.resize(Tok.getLength());
1020 const char *ThisTokBegin = &CharBuffer[0];
1021 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001022
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1024 Tok.getLocation(), PP);
1025 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001026 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001027
1028 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1029
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001030 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1031 Literal.isWide(),
1032 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001033}
1034
Sebastian Redlcd965b92009-01-18 18:53:16 +00001035Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1036 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001037 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1038 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001039 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001040 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001041 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001042 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001043 }
Ted Kremenek28396602009-01-13 23:19:12 +00001044
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001046 // Add padding so that NumericLiteralParser can overread by one character.
1047 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001049
Reid Spencer5f016e22007-07-11 17:01:13 +00001050 // Get the spelling of the token, which eliminates trigraphs, etc.
1051 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001052
Reid Spencer5f016e22007-07-11 17:01:13 +00001053 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1054 Tok.getLocation(), PP);
1055 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001056 return ExprError();
1057
Chris Lattner5d661452007-08-26 03:42:43 +00001058 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001059
Chris Lattner5d661452007-08-26 03:42:43 +00001060 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001061 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001062 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001063 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001064 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001065 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001066 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001067 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001068
1069 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1070
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001071 // isExact will be set by GetFloatValue().
1072 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001073 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1074 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001075
Chris Lattner5d661452007-08-26 03:42:43 +00001076 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001077 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001078 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001079 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001080
Neil Boothb9449512007-08-29 22:00:19 +00001081 // long long is a C99 feature.
1082 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001083 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001084 Diag(Tok.getLocation(), diag::ext_longlong);
1085
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001087 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001088
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 if (Literal.GetIntegerValue(ResultVal)) {
1090 // If this value didn't fit into uintmax_t, warn and force to ull.
1091 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001092 Ty = Context.UnsignedLongLongTy;
1093 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001094 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 } else {
1096 // If this value fits into a ULL, try to figure out what else it fits into
1097 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001098
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1100 // be an unsigned int.
1101 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1102
1103 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001104 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001105 if (!Literal.isLong && !Literal.isLongLong) {
1106 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001107 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001108
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 // Does it fit in a unsigned int?
1110 if (ResultVal.isIntN(IntSize)) {
1111 // Does it fit in a signed int?
1112 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001113 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001115 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001116 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001121 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001122 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001123
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 // Does it fit in a unsigned long?
1125 if (ResultVal.isIntN(LongSize)) {
1126 // Does it fit in a signed long?
1127 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001128 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001130 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001131 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001133 }
1134
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001136 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001137 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001138
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 // Does it fit in a unsigned long long?
1140 if (ResultVal.isIntN(LongLongSize)) {
1141 // Does it fit in a signed long long?
1142 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001143 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001145 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001146 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 }
1148 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001149
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 // If we still couldn't decide a type, we probably have something that
1151 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001152 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001154 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001155 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001157
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001158 if (ResultVal.getBitWidth() != Width)
1159 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001161 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001163
Chris Lattner5d661452007-08-26 03:42:43 +00001164 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1165 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001166 Res = new (Context) ImaginaryLiteral(Res,
1167 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001168
1169 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001170}
1171
Sebastian Redlcd965b92009-01-18 18:53:16 +00001172Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1173 SourceLocation R, ExprArg Val) {
1174 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001175 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001176 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001177}
1178
1179/// The UsualUnaryConversions() function is *not* called by this routine.
1180/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001181bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001182 SourceLocation OpLoc,
1183 const SourceRange &ExprRange,
1184 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001185 if (exprType->isDependentType())
1186 return false;
1187
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001189 if (isa<FunctionType>(exprType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 // alignof(function) is allowed.
Chris Lattner01072922009-01-24 19:46:37 +00001191 if (isSizeof)
1192 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1193 return false;
1194 }
1195
1196 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001197 Diag(OpLoc, diag::ext_sizeof_void_type)
1198 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001199 return false;
1200 }
Sebastian Redl05189992008-11-11 17:56:53 +00001201
Douglas Gregor86447ec2009-03-09 16:13:40 +00001202 return RequireCompleteType(OpLoc, exprType,
Chris Lattner01072922009-01-24 19:46:37 +00001203 isSizeof ? diag::err_sizeof_incomplete_type :
1204 diag::err_alignof_incomplete_type,
1205 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +00001206}
1207
Chris Lattner31e21e02009-01-24 20:17:12 +00001208bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1209 const SourceRange &ExprRange) {
1210 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001211
Chris Lattner31e21e02009-01-24 20:17:12 +00001212 // alignof decl is always ok.
1213 if (isa<DeclRefExpr>(E))
1214 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001215
1216 // Cannot know anything else if the expression is dependent.
1217 if (E->isTypeDependent())
1218 return false;
1219
Chris Lattner31e21e02009-01-24 20:17:12 +00001220 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1221 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1222 if (FD->isBitField()) {
Chris Lattnerda027472009-01-24 21:29:22 +00001223 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner31e21e02009-01-24 20:17:12 +00001224 return true;
1225 }
1226 // Other fields are ok.
1227 return false;
1228 }
1229 }
1230 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1231}
1232
Douglas Gregorba498172009-03-13 21:01:28 +00001233/// \brief Build a sizeof or alignof expression given a type operand.
1234Action::OwningExprResult
1235Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1236 bool isSizeOf, SourceRange R) {
1237 if (T.isNull())
1238 return ExprError();
1239
1240 if (!T->isDependentType() &&
1241 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1242 return ExprError();
1243
1244 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1245 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1246 Context.getSizeType(), OpLoc,
1247 R.getEnd()));
1248}
1249
1250/// \brief Build a sizeof or alignof expression given an expression
1251/// operand.
1252Action::OwningExprResult
1253Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1254 bool isSizeOf, SourceRange R) {
1255 // Verify that the operand is valid.
1256 bool isInvalid = false;
1257 if (E->isTypeDependent()) {
1258 // Delay type-checking for type-dependent expressions.
1259 } else if (!isSizeOf) {
1260 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1261 } else if (E->isBitField()) { // C99 6.5.3.4p1.
1262 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1263 isInvalid = true;
1264 } else {
1265 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1266 }
1267
1268 if (isInvalid)
1269 return ExprError();
1270
1271 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1272 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1273 Context.getSizeType(), OpLoc,
1274 R.getEnd()));
1275}
1276
Sebastian Redl05189992008-11-11 17:56:53 +00001277/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1278/// the same for @c alignof and @c __alignof
1279/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001280Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001281Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1282 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001284 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001285
Sebastian Redl05189992008-11-11 17:56:53 +00001286 if (isType) {
Douglas Gregorba498172009-03-13 21:01:28 +00001287 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1288 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1289 }
Sebastian Redl05189992008-11-11 17:56:53 +00001290
Douglas Gregorba498172009-03-13 21:01:28 +00001291 // Get the end location.
1292 Expr *ArgEx = (Expr *)TyOrEx;
1293 Action::OwningExprResult Result
1294 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1295
1296 if (Result.isInvalid())
1297 DeleteExpr(ArgEx);
1298
1299 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001300}
1301
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001302QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001303 if (V->isTypeDependent())
1304 return Context.DependentTy;
1305
Chris Lattnerdbb36972007-08-24 21:16:53 +00001306 DefaultFunctionArrayConversion(V);
1307
Chris Lattnercc26ed72007-08-26 05:39:26 +00001308 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001309 if (const ComplexType *CT = V->getType()->getAsComplexType())
1310 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001311
1312 // Otherwise they pass through real integer and floating point types here.
1313 if (V->getType()->isArithmeticType())
1314 return V->getType();
1315
1316 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001317 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1318 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001319 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001320}
1321
1322
Reid Spencer5f016e22007-07-11 17:01:13 +00001323
Sebastian Redl0eb23302009-01-19 00:08:26 +00001324Action::OwningExprResult
1325Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1326 tok::TokenKind Kind, ExprArg Input) {
1327 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001328
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 UnaryOperator::Opcode Opc;
1330 switch (Kind) {
1331 default: assert(0 && "Unknown unary op!");
1332 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1333 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1334 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001335
Douglas Gregor74253732008-11-19 15:42:04 +00001336 if (getLangOptions().CPlusPlus &&
1337 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1338 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001339 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001340 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1341
1342 // C++ [over.inc]p1:
1343 //
1344 // [...] If the function is a member function with one
1345 // parameter (which shall be of type int) or a non-member
1346 // function with two parameters (the second of which shall be
1347 // of type int), it defines the postfix increment operator ++
1348 // for objects of that type. When the postfix increment is
1349 // called as a result of using the ++ operator, the int
1350 // argument will have value zero.
1351 Expr *Args[2] = {
1352 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001353 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1354 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001355 };
1356
1357 // Build the candidate set for overloading
1358 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00001359 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor74253732008-11-19 15:42:04 +00001360
1361 // Perform overload resolution.
1362 OverloadCandidateSet::iterator Best;
1363 switch (BestViableFunction(CandidateSet, Best)) {
1364 case OR_Success: {
1365 // We found a built-in operator or an overloaded operator.
1366 FunctionDecl *FnDecl = Best->Function;
1367
1368 if (FnDecl) {
1369 // We matched an overloaded operator. Build a call to that
1370 // operator.
1371
1372 // Convert the arguments.
1373 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1374 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001375 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001376 } else {
1377 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001378 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001379 FnDecl->getParamDecl(0)->getType(),
1380 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001381 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001382 }
1383
1384 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001385 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001386 = FnDecl->getType()->getAsFunctionType()->getResultType();
1387 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001388
Douglas Gregor74253732008-11-19 15:42:04 +00001389 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001390 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump488e25b2009-02-19 02:54:59 +00001391 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00001392 UsualUnaryConversions(FnExpr);
1393
Sebastian Redl0eb23302009-01-19 00:08:26 +00001394 Input.release();
Douglas Gregor063daf62009-03-13 18:40:31 +00001395 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1396 Args, 2, ResultTy,
1397 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001398 } else {
1399 // We matched a built-in operator. Convert the arguments, then
1400 // break out so that we will build the appropriate built-in
1401 // operator node.
1402 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1403 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001404 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001405
1406 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001407 }
Douglas Gregor74253732008-11-19 15:42:04 +00001408 }
1409
1410 case OR_No_Viable_Function:
1411 // No viable function; fall through to handling this as a
1412 // built-in operator, which will produce an error message for us.
1413 break;
1414
1415 case OR_Ambiguous:
1416 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1417 << UnaryOperator::getOpcodeStr(Opc)
1418 << Arg->getSourceRange();
1419 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001420 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001421
1422 case OR_Deleted:
1423 Diag(OpLoc, diag::err_ovl_deleted_oper)
1424 << Best->Function->isDeleted()
1425 << UnaryOperator::getOpcodeStr(Opc)
1426 << Arg->getSourceRange();
1427 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1428 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001429 }
1430
1431 // Either we found no viable overloaded operator or we matched a
1432 // built-in operator. In either case, fall through to trying to
1433 // build a built-in operation.
1434 }
1435
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001436 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1437 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001439 return ExprError();
1440 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001441 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001442}
1443
Sebastian Redl0eb23302009-01-19 00:08:26 +00001444Action::OwningExprResult
1445Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1446 ExprArg Idx, SourceLocation RLoc) {
1447 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1448 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001449
Douglas Gregor337c6b92008-11-19 17:17:41 +00001450 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001451 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001452 LHSExp->getType()->isEnumeralType() ||
1453 RHSExp->getType()->isRecordType() ||
1454 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001455 // Add the appropriate overloaded operators (C++ [over.match.oper])
1456 // to the candidate set.
1457 OverloadCandidateSet CandidateSet;
1458 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor063daf62009-03-13 18:40:31 +00001459 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1460 SourceRange(LLoc, RLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001461
Douglas Gregor337c6b92008-11-19 17:17:41 +00001462 // Perform overload resolution.
1463 OverloadCandidateSet::iterator Best;
1464 switch (BestViableFunction(CandidateSet, Best)) {
1465 case OR_Success: {
1466 // We found a built-in operator or an overloaded operator.
1467 FunctionDecl *FnDecl = Best->Function;
1468
1469 if (FnDecl) {
1470 // We matched an overloaded operator. Build a call to that
1471 // operator.
1472
1473 // Convert the arguments.
1474 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1475 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1476 PerformCopyInitialization(RHSExp,
1477 FnDecl->getParamDecl(0)->getType(),
1478 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001479 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001480 } else {
1481 // Convert the arguments.
1482 if (PerformCopyInitialization(LHSExp,
1483 FnDecl->getParamDecl(0)->getType(),
1484 "passing") ||
1485 PerformCopyInitialization(RHSExp,
1486 FnDecl->getParamDecl(1)->getType(),
1487 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001488 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001489 }
1490
1491 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001492 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001493 = FnDecl->getType()->getAsFunctionType()->getResultType();
1494 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001495
Douglas Gregor337c6b92008-11-19 17:17:41 +00001496 // Build the actual expression node.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001497 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1498 SourceLocation());
Douglas Gregor337c6b92008-11-19 17:17:41 +00001499 UsualUnaryConversions(FnExpr);
1500
Sebastian Redl0eb23302009-01-19 00:08:26 +00001501 Base.release();
1502 Idx.release();
Douglas Gregor063daf62009-03-13 18:40:31 +00001503 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1504 FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001505 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001506 } else {
1507 // We matched a built-in operator. Convert the arguments, then
1508 // break out so that we will build the appropriate built-in
1509 // operator node.
1510 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1511 "passing") ||
1512 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1513 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001514 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001515
1516 break;
1517 }
1518 }
1519
1520 case OR_No_Viable_Function:
1521 // No viable function; fall through to handling this as a
1522 // built-in operator, which will produce an error message for us.
1523 break;
1524
1525 case OR_Ambiguous:
1526 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1527 << "[]"
1528 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1529 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001530 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001531
1532 case OR_Deleted:
1533 Diag(LLoc, diag::err_ovl_deleted_oper)
1534 << Best->Function->isDeleted()
1535 << "[]"
1536 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1537 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1538 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001539 }
1540
1541 // Either we found no viable overloaded operator or we matched a
1542 // built-in operator. In either case, fall through to trying to
1543 // build a built-in operation.
1544 }
1545
Chris Lattner12d9ff62007-07-16 00:14:47 +00001546 // Perform default conversions.
1547 DefaultFunctionArrayConversion(LHSExp);
1548 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001549
Chris Lattner12d9ff62007-07-16 00:14:47 +00001550 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001551
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001553 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001554 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001556 Expr *BaseExpr, *IndexExpr;
1557 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001558 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1559 BaseExpr = LHSExp;
1560 IndexExpr = RHSExp;
1561 ResultType = Context.DependentTy;
1562 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001563 BaseExpr = LHSExp;
1564 IndexExpr = RHSExp;
1565 // FIXME: need to deal with const...
1566 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001567 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001568 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001569 BaseExpr = RHSExp;
1570 IndexExpr = LHSExp;
1571 // FIXME: need to deal with const...
1572 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001573 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1574 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001575 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001576
Chris Lattner12d9ff62007-07-16 00:14:47 +00001577 // FIXME: need to deal with const...
1578 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001580 return ExprError(Diag(LHSExp->getLocStart(),
1581 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1582 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 // C99 6.5.2.1p1
Sebastian Redl28507842009-02-26 14:39:58 +00001584 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001585 return ExprError(Diag(IndexExpr->getLocStart(),
1586 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001587
Douglas Gregore7450f52009-03-24 19:52:54 +00001588 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1589 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1590 // type. Note that Functions are not objects, and that (in C99 parlance)
1591 // incomplete types are not object types.
1592 if (ResultType->isFunctionType()) {
1593 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1594 << ResultType << BaseExpr->getSourceRange();
1595 return ExprError();
1596 }
1597 if (!ResultType->isDependentType() &&
1598 RequireCompleteType(BaseExpr->getLocStart(), ResultType,
1599 diag::err_subscript_incomplete_type,
1600 BaseExpr->getSourceRange()))
1601 return ExprError();
Chris Lattner12d9ff62007-07-16 00:14:47 +00001602
Sebastian Redl0eb23302009-01-19 00:08:26 +00001603 Base.release();
1604 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001605 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001606 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001607}
1608
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001609QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001610CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001611 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001612 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001613
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001614 // The vector accessor can't exceed the number of elements.
1615 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001616
Mike Stumpeed9cac2009-02-19 03:04:26 +00001617 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001618 // special names that indicate a subset of exactly half the elements are
1619 // to be selected.
1620 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001621
Nate Begeman353417a2009-01-18 01:47:54 +00001622 // This flag determines whether or not CompName has an 's' char prefix,
1623 // indicating that it is a string of hex values to be used as vector indices.
1624 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001625
1626 // Check that we've found one of the special components, or that the component
1627 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001628 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001629 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1630 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001631 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001632 do
1633 compStr++;
1634 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001635 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001636 do
1637 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001638 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001639 }
Nate Begeman353417a2009-01-18 01:47:54 +00001640
Mike Stumpeed9cac2009-02-19 03:04:26 +00001641 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001642 // We didn't get to the end of the string. This means the component names
1643 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001644 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1645 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001646 return QualType();
1647 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001648
Nate Begeman353417a2009-01-18 01:47:54 +00001649 // Ensure no component accessor exceeds the width of the vector type it
1650 // operates on.
1651 if (!HalvingSwizzle) {
1652 compStr = CompName.getName();
1653
1654 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001655 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001656
1657 while (*compStr) {
1658 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1659 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1660 << baseType << SourceRange(CompLoc);
1661 return QualType();
1662 }
1663 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001664 }
Nate Begeman8a997642008-05-09 06:41:27 +00001665
Nate Begeman353417a2009-01-18 01:47:54 +00001666 // If this is a halving swizzle, verify that the base type has an even
1667 // number of elements.
1668 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001669 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001670 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001671 return QualType();
1672 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001673
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001674 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001675 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001676 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001677 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001678 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001679 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1680 : CompName.getLength();
1681 if (HexSwizzle)
1682 CompSize--;
1683
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001684 if (CompSize == 1)
1685 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001686
Nate Begeman213541a2008-04-18 23:10:10 +00001687 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001688 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001689 // diagostics look bad. We want extended vector types to appear built-in.
1690 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1691 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1692 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001693 }
1694 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001695}
1696
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001697static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1698 IdentifierInfo &Member,
1699 const Selector &Sel) {
1700
1701 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
1702 return PD;
1703 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1704 return OMD;
1705
1706 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1707 E = PDecl->protocol_end(); I != E; ++I) {
1708 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel))
1709 return D;
1710 }
1711 return 0;
1712}
1713
1714static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1715 IdentifierInfo &Member,
1716 const Selector &Sel) {
1717 // Check protocols on qualified interfaces.
1718 Decl *GDecl = 0;
1719 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1720 E = QIdTy->qual_end(); I != E; ++I) {
1721 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1722 GDecl = PD;
1723 break;
1724 }
1725 // Also must look for a getter name which uses property syntax.
1726 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1727 GDecl = OMD;
1728 break;
1729 }
1730 }
1731 if (!GDecl) {
1732 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1733 E = QIdTy->qual_end(); I != E; ++I) {
1734 // Search in the protocol-qualifier list of current protocol.
1735 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel);
1736 if (GDecl)
1737 return GDecl;
1738 }
1739 }
1740 return GDecl;
1741}
Chris Lattner76a642f2009-02-15 22:43:40 +00001742
Sebastian Redl0eb23302009-01-19 00:08:26 +00001743Action::OwningExprResult
1744Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1745 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001746 IdentifierInfo &Member,
1747 DeclTy *ObjCImpDecl) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001748 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001749 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001750
1751 // Perform default conversions.
1752 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001753
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001754 QualType BaseType = BaseExpr->getType();
1755 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001756
Chris Lattner68a057b2008-07-21 04:36:39 +00001757 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1758 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001760 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001761 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001762 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001763 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1764 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001765 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001766 return ExprError(Diag(MemberLoc,
1767 diag::err_typecheck_member_reference_arrow)
1768 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001770
Chris Lattner68a057b2008-07-21 04:36:39 +00001771 // Handle field access to simple records. This also handles access to fields
1772 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001773 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001774 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00001775 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001776 diag::err_typecheck_incomplete_tag,
1777 BaseExpr->getSourceRange()))
1778 return ExprError();
1779
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001780 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001781 // FIXME: Qualified name lookup for C++ is a bit more complicated
1782 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001783 LookupResult Result
Mike Stumpeed9cac2009-02-19 03:04:26 +00001784 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001785 LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001786
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001787 NamedDecl *MemberDecl = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001788 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001789 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1790 << &Member << BaseExpr->getSourceRange());
1791 else if (Result.isAmbiguous()) {
1792 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1793 MemberLoc, BaseExpr->getSourceRange());
1794 return ExprError();
1795 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001796 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001797
Chris Lattner56cd21b2009-02-13 22:08:30 +00001798 // If the decl being referenced had an error, return an error for this
1799 // sub-expr without emitting another error, in order to avoid cascading
1800 // error cases.
1801 if (MemberDecl->isInvalidDecl())
1802 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001803
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001804 // Check the use of this field
1805 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1806 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00001807
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001808 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001809 // We may have found a field within an anonymous union or struct
1810 // (C++ [class.union]).
1811 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001812 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001813 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001814
Douglas Gregor86f19402008-12-20 23:49:58 +00001815 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1816 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001817 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001818 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1819 MemberType = Ref->getPointeeType();
1820 else {
1821 unsigned combinedQualifiers =
1822 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001823 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001824 combinedQualifiers &= ~QualType::Const;
1825 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1826 }
Eli Friedman51019072008-02-06 22:48:16 +00001827
Steve Naroff6ece14c2009-01-21 00:14:39 +00001828 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1829 MemberLoc, MemberType));
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001830 } else if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001831 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001832 Var, MemberLoc,
1833 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001834 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00001835 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001836 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001837 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001838 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001839 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001840 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001841 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00001842 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1843 Enum, MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001844 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001845 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1846 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001847
Douglas Gregor86f19402008-12-20 23:49:58 +00001848 // We found a declaration kind that we didn't expect. This is a
1849 // generic error message that tells the user that she can't refer
1850 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001851 return ExprError(Diag(MemberLoc,
1852 diag::err_typecheck_member_reference_unknown)
1853 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001854 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001855
Chris Lattnera38e6b12008-07-21 04:59:05 +00001856 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1857 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001858 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001859 ObjCInterfaceDecl *ClassDeclared;
1860 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1861 ClassDeclared)) {
Chris Lattner56cd21b2009-02-13 22:08:30 +00001862 // If the decl being referenced had an error, return an error for this
1863 // sub-expr without emitting another error, in order to avoid cascading
1864 // error cases.
1865 if (IV->isInvalidDecl())
1866 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001867
1868 // Check whether we can reference this field.
1869 if (DiagnoseUseOfDecl(IV, MemberLoc))
1870 return ExprError();
Steve Naroff8bfd1b82009-03-26 16:01:08 +00001871 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1872 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001873 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1874 if (ObjCMethodDecl *MD = getCurMethodDecl())
1875 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001876 else if (ObjCImpDecl && getCurFunctionDecl()) {
1877 // Case of a c-function declared inside an objc implementation.
1878 // FIXME: For a c-style function nested inside an objc implementation
1879 // class, there is no implementation context available, so we pass down
1880 // the context as argument to this routine. Ideally, this context need
1881 // be passed down in the AST node and somehow calculated from the AST
1882 // for a function decl.
1883 Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl);
1884 if (ObjCImplementationDecl *IMPD =
1885 dyn_cast<ObjCImplementationDecl>(ImplDecl))
1886 ClassOfMethodDecl = IMPD->getClassInterface();
1887 else if (ObjCCategoryImplDecl* CatImplClass =
1888 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1889 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Naroffb06d8752009-03-04 18:34:24 +00001890 }
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001891 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001892 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001893 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001894 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1895 }
1896 // @protected
1897 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1898 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1899 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001900
1901 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff6ece14c2009-01-21 00:14:39 +00001902 MemberLoc, BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001903 OpKind == tok::arrow);
1904 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001905 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001906 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001907 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1908 << IFTy->getDecl()->getDeclName() << &Member
1909 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001910 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001911
Chris Lattnera38e6b12008-07-21 04:59:05 +00001912 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1913 // pointer to a (potentially qualified) interface type.
1914 const PointerType *PTy;
1915 const ObjCInterfaceType *IFTy;
1916 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1917 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1918 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001919
Daniel Dunbar2307d312008-09-03 01:05:41 +00001920 // Search for a declared property first.
Chris Lattner7eba82e2009-02-16 18:35:08 +00001921 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001922 // Check whether we can reference this property.
1923 if (DiagnoseUseOfDecl(PD, MemberLoc))
1924 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00001925
Steve Naroff6ece14c2009-01-21 00:14:39 +00001926 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001927 MemberLoc, BaseExpr));
1928 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001929
Daniel Dunbar2307d312008-09-03 01:05:41 +00001930 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001931 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1932 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner7eba82e2009-02-16 18:35:08 +00001933 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001934 // Check whether we can reference this property.
1935 if (DiagnoseUseOfDecl(PD, MemberLoc))
1936 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00001937
Steve Naroff6ece14c2009-01-21 00:14:39 +00001938 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001939 MemberLoc, BaseExpr));
1940 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001941
1942 // If that failed, look for an "implicit" property by seeing if the nullary
1943 // selector is implemented.
1944
1945 // FIXME: The logic for looking up nullary and unary selectors should be
1946 // shared with the code in ActOnInstanceMessage.
1947
1948 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1949 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001950
Daniel Dunbar2307d312008-09-03 01:05:41 +00001951 // If this reference is in an @implementation, check for 'private' methods.
1952 if (!Getter)
Steve Narofff1787282009-03-11 15:15:01 +00001953 if (ObjCImplementationDecl *ImpDecl =
1954 ObjCImplementations[IFace->getIdentifier()])
1955 Getter = ImpDecl->getInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001956
Steve Naroff7692ed62008-10-22 19:16:27 +00001957 // Look through local category implementations associated with the class.
1958 if (!Getter) {
1959 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1960 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1961 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1962 }
1963 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001964 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001965 // Check if we can reference this property.
1966 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1967 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00001968 }
1969 // If we found a getter then this may be a valid dot-reference, we
1970 // will look for the matching setter, in case it is needed.
1971 Selector SetterSel =
1972 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1973 PP.getSelectorTable(), &Member);
1974 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1975 if (!Setter) {
1976 // If this reference is in an @implementation, also check for 'private'
1977 // methods.
Steve Narofff1787282009-03-11 15:15:01 +00001978 if (ObjCImplementationDecl *ImpDecl =
1979 ObjCImplementations[IFace->getIdentifier()])
1980 Setter = ImpDecl->getInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00001981 }
1982 // Look through local category implementations associated with the class.
1983 if (!Setter) {
1984 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1985 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1986 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001987 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001988 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001989
Steve Naroff1ca66942009-03-11 13:48:17 +00001990 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1991 return ExprError();
1992
1993 if (Getter || Setter) {
1994 QualType PType;
1995
1996 if (Getter)
1997 PType = Getter->getResultType();
1998 else {
1999 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2000 E = Setter->param_end(); PI != E; ++PI)
2001 PType = (*PI)->getType();
2002 }
2003 // FIXME: we must check that the setter has property type.
2004 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2005 Setter, MemberLoc, BaseExpr));
2006 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002007 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2008 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002009 }
Steve Naroff18bc1642008-10-20 22:53:06 +00002010 // Handle properties on qualified "id" protocols.
2011 const ObjCQualifiedIdType *QIdTy;
2012 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2013 // Check protocols on qualified interfaces.
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002014 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2015 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel)) {
2016 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002017 // Check the use of this declaration
2018 if (DiagnoseUseOfDecl(PD, MemberLoc))
2019 return ExprError();
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002020
Steve Naroff6ece14c2009-01-21 00:14:39 +00002021 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002022 MemberLoc, BaseExpr));
2023 }
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002024 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002025 // Check the use of this method.
2026 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2027 return ExprError();
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002028
Mike Stumpeed9cac2009-02-19 03:04:26 +00002029 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002030 OMD->getResultType(),
2031 OMD, OpLoc, MemberLoc,
2032 NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00002033 }
2034 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002035
2036 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2037 << &Member << BaseType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002038 }
Steve Naroffdd53eb52009-03-05 20:12:00 +00002039 // Handle properties on ObjC 'Class' types.
2040 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2041 // Also must look for a getter name which uses property syntax.
2042 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2043 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff335c6802009-03-11 20:12:18 +00002044 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2045 ObjCMethodDecl *Getter;
Steve Naroffdd53eb52009-03-05 20:12:00 +00002046 // FIXME: need to also look locally in the implementation.
Steve Naroff335c6802009-03-11 20:12:18 +00002047 if ((Getter = IFace->lookupClassMethod(Sel))) {
Steve Naroffdd53eb52009-03-05 20:12:00 +00002048 // Check the use of this method.
Steve Naroff335c6802009-03-11 20:12:18 +00002049 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffdd53eb52009-03-05 20:12:00 +00002050 return ExprError();
Steve Naroffdd53eb52009-03-05 20:12:00 +00002051 }
Steve Naroff335c6802009-03-11 20:12:18 +00002052 // If we found a getter then this may be a valid dot-reference, we
2053 // will look for the matching setter, in case it is needed.
2054 Selector SetterSel =
2055 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2056 PP.getSelectorTable(), &Member);
2057 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2058 if (!Setter) {
2059 // If this reference is in an @implementation, also check for 'private'
2060 // methods.
2061 if (ObjCImplementationDecl *ImpDecl =
2062 ObjCImplementations[IFace->getIdentifier()])
2063 Setter = ImpDecl->getInstanceMethod(SetterSel);
2064 }
2065 // Look through local category implementations associated with the class.
2066 if (!Setter) {
2067 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2068 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2069 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2070 }
2071 }
2072
2073 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2074 return ExprError();
2075
2076 if (Getter || Setter) {
2077 QualType PType;
2078
2079 if (Getter)
2080 PType = Getter->getResultType();
2081 else {
2082 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2083 E = Setter->param_end(); PI != E; ++PI)
2084 PType = (*PI)->getType();
2085 }
2086 // FIXME: we must check that the setter has property type.
2087 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2088 Setter, MemberLoc, BaseExpr));
2089 }
2090 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2091 << &Member << BaseType);
Steve Naroffdd53eb52009-03-05 20:12:00 +00002092 }
2093 }
2094
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002095 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002096 if (BaseType->isExtVectorType()) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002097 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2098 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002099 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002100 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002101 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002102 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002103
Douglas Gregor214f31a2009-03-27 06:00:30 +00002104 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2105 << BaseType << BaseExpr->getSourceRange();
2106
2107 // If the user is trying to apply -> or . to a function or function
2108 // pointer, it's probably because they forgot parentheses to call
2109 // the function. Suggest the addition of those parentheses.
2110 if (BaseType == Context.OverloadTy ||
2111 BaseType->isFunctionType() ||
2112 (BaseType->isPointerType() &&
2113 BaseType->getAsPointerType()->isFunctionType())) {
2114 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2115 Diag(Loc, diag::note_member_reference_needs_call)
2116 << CodeModificationHint::CreateInsertion(Loc, "()");
2117 }
2118
2119 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002120}
2121
Douglas Gregor88a35142008-12-22 05:46:06 +00002122/// ConvertArgumentsForCall - Converts the arguments specified in
2123/// Args/NumArgs to the parameter types of the function FDecl with
2124/// function prototype Proto. Call is the call expression itself, and
2125/// Fn is the function expression. For a C++ member function, this
2126/// routine does not attempt to convert the object argument. Returns
2127/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002128bool
2129Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002130 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002131 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002132 Expr **Args, unsigned NumArgs,
2133 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002134 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002135 // assignment, to the types of the corresponding parameter, ...
2136 unsigned NumArgsInProto = Proto->getNumArgs();
2137 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002138 bool Invalid = false;
2139
Douglas Gregor88a35142008-12-22 05:46:06 +00002140 // If too few arguments are available (and we don't have default
2141 // arguments for the remaining parameters), don't make the call.
2142 if (NumArgs < NumArgsInProto) {
2143 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2144 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2145 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2146 // Use default arguments for missing arguments
2147 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002148 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002149 }
2150
2151 // If too many are passed and not variadic, error on the extras and drop
2152 // them.
2153 if (NumArgs > NumArgsInProto) {
2154 if (!Proto->isVariadic()) {
2155 Diag(Args[NumArgsInProto]->getLocStart(),
2156 diag::err_typecheck_call_too_many_args)
2157 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2158 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2159 Args[NumArgs-1]->getLocEnd());
2160 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002161 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002162 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002163 }
2164 NumArgsToCheck = NumArgsInProto;
2165 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002166
Douglas Gregor88a35142008-12-22 05:46:06 +00002167 // Continue to check argument types (even if we have too few/many args).
2168 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2169 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002170
Douglas Gregor88a35142008-12-22 05:46:06 +00002171 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002172 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002173 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002174
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002175 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2176 ProtoArgType,
2177 diag::err_call_incomplete_argument,
2178 Arg->getSourceRange()))
2179 return true;
2180
Douglas Gregor61366e92008-12-24 00:01:03 +00002181 // Pass the argument.
2182 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2183 return true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002184 } else
Douglas Gregor61366e92008-12-24 00:01:03 +00002185 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00002186 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00002187 QualType ArgType = Arg->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002188
Douglas Gregor88a35142008-12-22 05:46:06 +00002189 Call->setArg(i, Arg);
2190 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002191
Douglas Gregor88a35142008-12-22 05:46:06 +00002192 // If this is a variadic call, handle args passed through "...".
2193 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002194 VariadicCallType CallType = VariadicFunction;
2195 if (Fn->getType()->isBlockPointerType())
2196 CallType = VariadicBlock; // Block
2197 else if (isa<MemberExpr>(Fn))
2198 CallType = VariadicMethod;
2199
Douglas Gregor88a35142008-12-22 05:46:06 +00002200 // Promote the arguments (C99 6.5.2.2p7).
2201 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2202 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002203 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002204 Call->setArg(i, Arg);
2205 }
2206 }
2207
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002208 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002209}
2210
Steve Narofff69936d2007-09-16 03:34:24 +00002211/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002212/// This provides the location of the left/right parens and a list of comma
2213/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002214Action::OwningExprResult
2215Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2216 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002217 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002218 unsigned NumArgs = args.size();
2219 Expr *Fn = static_cast<Expr *>(fn.release());
2220 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002221 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002222 FunctionDecl *FDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002223 DeclarationName UnqualifiedName;
Douglas Gregor88a35142008-12-22 05:46:06 +00002224
Douglas Gregor88a35142008-12-22 05:46:06 +00002225 if (getLangOptions().CPlusPlus) {
Douglas Gregor17330012009-02-04 15:01:18 +00002226 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002227 // in which case we won't do any semantic analysis now.
Douglas Gregor17330012009-02-04 15:01:18 +00002228 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2229 bool Dependent = false;
2230 if (Fn->isTypeDependent())
2231 Dependent = true;
2232 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2233 Dependent = true;
2234
2235 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002236 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002237 Context.DependentTy, RParenLoc));
2238
2239 // Determine whether this is a call to an object (C++ [over.call.object]).
2240 if (Fn->getType()->isRecordType())
2241 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2242 CommaLocs, RParenLoc));
2243
Douglas Gregorfa047642009-02-04 00:32:51 +00002244 // Determine whether this is a call to a member function.
Douglas Gregor88a35142008-12-22 05:46:06 +00002245 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2246 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2247 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002248 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2249 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00002250 }
2251
Douglas Gregorfa047642009-02-04 00:32:51 +00002252 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00002253 DeclRefExpr *DRExpr = NULL;
Douglas Gregorfa047642009-02-04 00:32:51 +00002254 Expr *FnExpr = Fn;
2255 bool ADL = true;
2256 while (true) {
2257 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2258 FnExpr = IcExpr->getSubExpr();
2259 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002260 // Parentheses around a function disable ADL
Douglas Gregor17330012009-02-04 15:01:18 +00002261 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00002262 ADL = false;
2263 FnExpr = PExpr->getSubExpr();
2264 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stumpeed9cac2009-02-19 03:04:26 +00002265 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregorfa047642009-02-04 00:32:51 +00002266 == UnaryOperator::AddrOf) {
2267 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattner90e150d2009-02-14 07:22:29 +00002268 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2269 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2270 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2271 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002272 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattner90e150d2009-02-14 07:22:29 +00002273 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2274 UnqualifiedName = DepName->getName();
2275 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002276 } else {
Chris Lattner90e150d2009-02-14 07:22:29 +00002277 // Any kind of name that does not refer to a declaration (or
2278 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2279 ADL = false;
Douglas Gregorfa047642009-02-04 00:32:51 +00002280 break;
2281 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002282 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002283
Douglas Gregor17330012009-02-04 15:01:18 +00002284 OverloadedFunctionDecl *Ovl = 0;
2285 if (DRExpr) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002286 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor17330012009-02-04 15:01:18 +00002287 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2288 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002289
Douglas Gregorf9201e02009-02-11 23:02:49 +00002290 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002291 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor3c385e52009-02-14 18:57:46 +00002292 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002293 ADL = false;
2294
Douglas Gregorf9201e02009-02-11 23:02:49 +00002295 // We don't perform ADL in C.
2296 if (!getLangOptions().CPlusPlus)
2297 ADL = false;
2298
Douglas Gregor17330012009-02-04 15:01:18 +00002299 if (Ovl || ADL) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002300 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2301 UnqualifiedName, LParenLoc, Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002302 NumArgs, CommaLocs, RParenLoc, ADL);
2303 if (!FDecl)
2304 return ExprError();
2305
2306 // Update Fn to refer to the actual function selected.
2307 Expr *NewFn = 0;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002308 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor17330012009-02-04 15:01:18 +00002309 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregorab452ba2009-03-26 23:50:42 +00002310 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2311 QDRExpr->getLocation(),
2312 false, false,
2313 QDRExpr->getQualifierRange(),
2314 QDRExpr->getQualifier());
Douglas Gregorfa047642009-02-04 00:32:51 +00002315 else
Mike Stumpeed9cac2009-02-19 03:04:26 +00002316 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00002317 Fn->getSourceRange().getBegin());
2318 Fn->Destroy(Context);
2319 Fn = NewFn;
2320 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002321 }
Chris Lattner04421082008-04-08 04:40:51 +00002322
2323 // Promote the function operand.
2324 UsualUnaryConversions(Fn);
2325
Chris Lattner925e60d2007-12-28 05:29:59 +00002326 // Make the call expr early, before semantic checks. This guarantees cleanup
2327 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002328 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2329 Args, NumArgs,
2330 Context.BoolTy,
2331 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002332
Steve Naroffdd972f22008-09-05 22:11:13 +00002333 const FunctionType *FuncT;
2334 if (!Fn->getType()->isBlockPointerType()) {
2335 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2336 // have type pointer to function".
2337 const PointerType *PT = Fn->getType()->getAsPointerType();
2338 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002339 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2340 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00002341 FuncT = PT->getPointeeType()->getAsFunctionType();
2342 } else { // This is a block call.
2343 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2344 getAsFunctionType();
2345 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002346 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002347 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2348 << Fn->getType() << Fn->getSourceRange());
2349
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002350 // Check for a valid return type
2351 if (!FuncT->getResultType()->isVoidType() &&
2352 RequireCompleteType(Fn->getSourceRange().getBegin(),
2353 FuncT->getResultType(),
2354 diag::err_call_incomplete_return,
2355 TheCall->getSourceRange()))
2356 return ExprError();
2357
Chris Lattner925e60d2007-12-28 05:29:59 +00002358 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002359 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002360
Douglas Gregor72564e72009-02-26 23:50:07 +00002361 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002362 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002363 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002364 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002365 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002366 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002367
Steve Naroffb291ab62007-08-28 23:30:39 +00002368 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002369 for (unsigned i = 0; i != NumArgs; i++) {
2370 Expr *Arg = Args[i];
2371 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002372 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2373 Arg->getType(),
2374 diag::err_call_incomplete_argument,
2375 Arg->getSourceRange()))
2376 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002377 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002378 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002380
Douglas Gregor88a35142008-12-22 05:46:06 +00002381 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2382 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002383 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2384 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002385
Chris Lattner59907c42007-08-10 20:18:51 +00002386 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00002387 if (FDecl)
2388 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00002389
Sebastian Redl0eb23302009-01-19 00:08:26 +00002390 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002391}
2392
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002393Action::OwningExprResult
2394Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2395 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002396 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00002397 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002398 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002399 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002400 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002401
Eli Friedman6223c222008-05-20 05:22:08 +00002402 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002403 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002404 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2405 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor86447ec2009-03-09 16:13:40 +00002406 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002407 diag::err_typecheck_decl_incomplete_type,
2408 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002409 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002410
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002411 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002412 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002413 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002414
Chris Lattner371f2582008-12-04 23:50:19 +00002415 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002416 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002417 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002418 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002419 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002420 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002421 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002422 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002423}
2424
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002425Action::OwningExprResult
2426Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002427 SourceLocation RBraceLoc) {
2428 unsigned NumInit = initlist.size();
2429 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002430
Steve Naroff08d92e42007-09-15 18:49:24 +00002431 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00002432 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002433
Mike Stumpeed9cac2009-02-19 03:04:26 +00002434 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002435 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002436 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002437 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002438}
2439
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002440/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00002441bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002442 UsualUnaryConversions(castExpr);
2443
2444 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2445 // type needs to be scalar.
2446 if (castType->isVoidType()) {
2447 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00002448 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2449 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002450 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002451 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2452 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2453 (castType->isStructureType() || castType->isUnionType())) {
2454 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00002455 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002456 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2457 << castType << castExpr->getSourceRange();
2458 } else if (castType->isUnionType()) {
2459 // GCC cast to union extension
2460 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2461 RecordDecl::field_iterator Field, FieldEnd;
2462 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2463 Field != FieldEnd; ++Field) {
2464 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2465 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2466 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2467 << castExpr->getSourceRange();
2468 break;
2469 }
2470 }
2471 if (Field == FieldEnd)
2472 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2473 << castExpr->getType() << castExpr->getSourceRange();
2474 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002475 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002476 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002477 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002478 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002479 } else if (!castExpr->getType()->isScalarType() &&
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002480 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002481 return Diag(castExpr->getLocStart(),
2482 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002483 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002484 } else if (castExpr->getType()->isVectorType()) {
2485 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2486 return true;
2487 } else if (castType->isVectorType()) {
2488 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2489 return true;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002490 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Chris Lattnere6ee6ba2009-03-05 23:09:00 +00002491 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002492 }
2493 return false;
2494}
2495
Chris Lattnerfe23e212007-12-20 00:44:32 +00002496bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002497 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00002498
Anders Carlssona64db8f2007-11-27 05:51:55 +00002499 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002500 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002501 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00002502 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00002503 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002504 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002505 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002506 } else
2507 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002508 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002509 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002510
Anders Carlssona64db8f2007-11-27 05:51:55 +00002511 return false;
2512}
2513
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002514Action::OwningExprResult
2515Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2516 SourceLocation RParenLoc, ExprArg Op) {
2517 assert((Ty != 0) && (Op.get() != 0) &&
2518 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002519
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002520 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002521 QualType castType = QualType::getFromOpaquePtr(Ty);
2522
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002523 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002524 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002525 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002526 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002527}
2528
Sebastian Redl28507842009-02-26 14:39:58 +00002529/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2530/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00002531/// C99 6.5.15
2532QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2533 SourceLocation QuestionLoc) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002534 UsualUnaryConversions(Cond);
2535 UsualUnaryConversions(LHS);
2536 UsualUnaryConversions(RHS);
2537 QualType CondTy = Cond->getType();
2538 QualType LHSTy = LHS->getType();
2539 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002540
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 // first, check the condition.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002542 if (!Cond->isTypeDependent()) {
2543 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2544 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2545 << CondTy;
Douglas Gregor898574e2008-12-05 23:32:09 +00002546 return QualType();
2547 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002548 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002549
Chris Lattner70d67a92008-01-06 22:42:25 +00002550 // Now check the two expressions.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002551 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor898574e2008-12-05 23:32:09 +00002552 return Context.DependentTy;
2553
Chris Lattner70d67a92008-01-06 22:42:25 +00002554 // If both operands have arithmetic type, do the usual arithmetic conversions
2555 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002556 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2557 UsualArithmeticConversions(LHS, RHS);
2558 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00002559 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002560
Chris Lattner70d67a92008-01-06 22:42:25 +00002561 // If both operands are the same structure or union type, the result is that
2562 // type.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002563 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2564 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002565 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00002566 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00002567 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002568 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00002569 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002571
Chris Lattner70d67a92008-01-06 22:42:25 +00002572 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002573 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002574 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2575 if (!LHSTy->isVoidType())
2576 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2577 << RHS->getSourceRange();
2578 if (!RHSTy->isVoidType())
2579 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2580 << LHS->getSourceRange();
2581 ImpCastExprToType(LHS, Context.VoidTy);
2582 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedman0e724012008-06-04 19:47:51 +00002583 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002584 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002585 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2586 // the type of the other operand."
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002587 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2588 Context.isObjCObjectPointerType(LHSTy)) &&
2589 RHS->isNullPointerConstant(Context)) {
2590 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2591 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002592 }
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002593 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2594 Context.isObjCObjectPointerType(RHSTy)) &&
2595 LHS->isNullPointerConstant(Context)) {
2596 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2597 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002598 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002599
Chris Lattnerbd57d362008-01-06 22:50:31 +00002600 // Handle the case where both operands are pointers before we handle null
2601 // pointer constants in case both operands are null pointer constants.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002602 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2603 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002604 // get the "pointed to" types
2605 QualType lhptee = LHSPT->getPointeeType();
2606 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002607
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002608 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2609 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002610 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002611 // Figure out necessary qualifiers (C99 6.5.15p6)
2612 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002613 QualType destType = Context.getPointerType(destPointee);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002614 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2615 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmana541d532008-02-10 22:59:36 +00002616 return destType;
2617 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002618 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002619 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002620 QualType destType = Context.getPointerType(destPointee);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002621 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2622 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmana541d532008-02-10 22:59:36 +00002623 return destType;
2624 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002625
Chris Lattnera119a3b2009-02-18 04:38:20 +00002626 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattnerb4650c12009-02-19 04:44:58 +00002627 // Two identical pointer types are always compatible.
Chris Lattnera119a3b2009-02-18 04:38:20 +00002628 return LHSTy;
2629 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002630
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002631 QualType compositeType = LHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002632
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002633 // If either type is an Objective-C object type then check
2634 // compatibility according to Objective-C.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002635 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002636 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002637 // If both operands are interfaces and either operand can be
2638 // assigned to the other, use that type as the composite
2639 // type. This allows
2640 // xxx ? (A*) a : (B*) b
2641 // where B is a subclass of A.
2642 //
2643 // Additionally, as for assignment, if either type is 'id'
2644 // allow silent coercion. Finally, if the types are
2645 // incompatible then make sure to use 'id' as the composite
2646 // type so the result is acceptable for sending messages to.
2647
Steve Naroff1fd03612009-02-12 19:05:07 +00002648 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002649 // It could return the composite type.
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002650 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2651 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2652 if (LHSIface && RHSIface &&
2653 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002654 compositeType = LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002655 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002656 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002657 compositeType = RHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002658 } else if (Context.isObjCIdStructType(lhptee) ||
2659 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002660 compositeType = Context.getObjCIdType();
2661 } else {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002662 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stumpeed9cac2009-02-19 03:04:26 +00002663 << LHSTy << RHSTy
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002664 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002665 QualType incompatTy = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002666 ImpCastExprToType(LHS, incompatTy);
2667 ImpCastExprToType(RHS, incompatTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002668 return incompatTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002669 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002670 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002671 rhptee.getUnqualifiedType())) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002672 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2673 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002674 // In this situation, we assume void* type. No especially good
2675 // reason, but this is what gcc does, and we do have to pick
2676 // to get a consistent AST.
2677 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002678 ImpCastExprToType(LHS, incompatTy);
2679 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002680 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002681 }
2682 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002683 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2684 // differently qualified versions of compatible types, the result type is
2685 // a pointer to an appropriately qualified version of the *composite*
2686 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002687 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002688 // FIXME: Need to add qualifiers
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002689 ImpCastExprToType(LHS, compositeType);
2690 ImpCastExprToType(RHS, compositeType);
Eli Friedman5835ea22008-05-16 20:37:07 +00002691 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 }
2693 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002694
Chris Lattnera119a3b2009-02-18 04:38:20 +00002695 // Selection between block pointer types is ok as long as they are the same.
2696 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2697 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2698 return LHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002699
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002700 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2701 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stumpeed9cac2009-02-19 03:04:26 +00002702 // id with statically typed objects).
2703 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002704 // GCC allows qualified id and any Objective-C type to devolve to
2705 // id. Currently localizing to here until clear this should be
2706 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002707 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00002708 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002709 Context.isObjCObjectPointerType(RHSTy)) ||
2710 (RHSTy->isObjCQualifiedIdType() &&
2711 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002712 // FIXME: This is not the correct composite type. This only
2713 // happens to work because id can more or less be used anywhere,
2714 // however this may change the type of method sends.
2715 // FIXME: gcc adds some type-checking of the arguments and emits
2716 // (confusing) incompatible comparison warnings in some
2717 // cases. Investigate.
2718 QualType compositeType = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002719 ImpCastExprToType(LHS, compositeType);
2720 ImpCastExprToType(RHS, compositeType);
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002721 return compositeType;
2722 }
2723 }
2724
Chris Lattner70d67a92008-01-06 22:42:25 +00002725 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002726 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2727 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 return QualType();
2729}
2730
Steve Narofff69936d2007-09-16 03:34:24 +00002731/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002732/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002733Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2734 SourceLocation ColonLoc,
2735 ExprArg Cond, ExprArg LHS,
2736 ExprArg RHS) {
2737 Expr *CondExpr = (Expr *) Cond.get();
2738 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002739
2740 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2741 // was the condition.
2742 bool isLHSNull = LHSExpr == 0;
2743 if (isLHSNull)
2744 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002745
2746 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002747 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002749 return ExprError();
2750
2751 Cond.release();
2752 LHS.release();
2753 RHS.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002754 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002755 isLHSNull ? 0 : LHSExpr,
2756 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002757}
2758
Reid Spencer5f016e22007-07-11 17:01:13 +00002759
2760// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00002761// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00002762// routine is it effectively iqnores the qualifiers on the top level pointee.
2763// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2764// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002765Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002766Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2767 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002768
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002770 lhptee = lhsType->getAsPointerType()->getPointeeType();
2771 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002772
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002774 lhptee = Context.getCanonicalType(lhptee);
2775 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002776
Chris Lattner5cf216b2008-01-04 18:04:52 +00002777 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002778
2779 // C99 6.5.16.1p1: This following citation is common to constraints
2780 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2781 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002782 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002783 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002784 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002785
Mike Stumpeed9cac2009-02-19 03:04:26 +00002786 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2787 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002789 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002790 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002791 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002792
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002793 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002794 assert(rhptee->isFunctionType());
2795 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002796 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002797
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002798 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002799 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002800 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002801
2802 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002803 assert(lhptee->isFunctionType());
2804 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002805 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002806 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00002808 lhptee = lhptee.getUnqualifiedType();
2809 rhptee = rhptee.getUnqualifiedType();
2810 if (!Context.typesAreCompatible(lhptee, rhptee)) {
2811 // Check if the pointee types are compatible ignoring the sign.
2812 // We explicitly check for char so that we catch "char" vs
2813 // "unsigned char" on systems where "char" is unsigned.
2814 if (lhptee->isCharType()) {
2815 lhptee = Context.UnsignedCharTy;
2816 } else if (lhptee->isSignedIntegerType()) {
2817 lhptee = Context.getCorrespondingUnsignedType(lhptee);
2818 }
2819 if (rhptee->isCharType()) {
2820 rhptee = Context.UnsignedCharTy;
2821 } else if (rhptee->isSignedIntegerType()) {
2822 rhptee = Context.getCorrespondingUnsignedType(rhptee);
2823 }
2824 if (lhptee == rhptee) {
2825 // Types are compatible ignoring the sign. Qualifier incompatibility
2826 // takes priority over sign incompatibility because the sign
2827 // warning can be disabled.
2828 if (ConvTy != Compatible)
2829 return ConvTy;
2830 return IncompatiblePointerSign;
2831 }
2832 // General pointer incompatibility takes priority over qualifiers.
2833 return IncompatiblePointer;
2834 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002835 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002836}
2837
Steve Naroff1c7d0672008-09-04 15:10:53 +00002838/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2839/// block pointer types are compatible or whether a block and normal pointer
2840/// are compatible. It is more restrict than comparing two function pointer
2841// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002842Sema::AssignConvertType
2843Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00002844 QualType rhsType) {
2845 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002846
Steve Naroff1c7d0672008-09-04 15:10:53 +00002847 // get the "pointed to" type (ignoring qualifiers at the top level)
2848 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002849 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2850
Steve Naroff1c7d0672008-09-04 15:10:53 +00002851 // make sure we operate on the canonical type
2852 lhptee = Context.getCanonicalType(lhptee);
2853 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002854
Steve Naroff1c7d0672008-09-04 15:10:53 +00002855 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002856
Steve Naroff1c7d0672008-09-04 15:10:53 +00002857 // For blocks we enforce that qualifiers are identical.
2858 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2859 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002860
Steve Naroff1c7d0672008-09-04 15:10:53 +00002861 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00002862 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002863 return ConvTy;
2864}
2865
Mike Stumpeed9cac2009-02-19 03:04:26 +00002866/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2867/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00002868/// pointers. Here are some objectionable examples that GCC considers warnings:
2869///
2870/// int a, *pint;
2871/// short *pshort;
2872/// struct foo *pfoo;
2873///
2874/// pint = pshort; // warning: assignment from incompatible pointer type
2875/// a = pint; // warning: assignment makes integer from pointer without a cast
2876/// pint = a; // warning: assignment makes pointer from integer without a cast
2877/// pint = pfoo; // warning: assignment from incompatible pointer type
2878///
2879/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00002880/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002881///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002882Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002883Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002884 // Get canonical types. We're not formatting these types, just comparing
2885 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002886 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2887 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002888
2889 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002890 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002891
Douglas Gregor9d293df2008-10-28 00:22:11 +00002892 // If the left-hand side is a reference type, then we are in a
2893 // (rare!) case where we've allowed the use of references in C,
2894 // e.g., as a parameter type in a built-in function. In this case,
2895 // just make sure that the type referenced is compatible with the
2896 // right-hand side type. The caller is responsible for adjusting
2897 // lhsType so that the resulting expression does not have reference
2898 // type.
2899 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2900 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002901 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002902 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002903 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002904
Chris Lattnereca7be62008-04-07 05:30:13 +00002905 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2906 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002907 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002908 // Relax integer conversions like we do for pointers below.
2909 if (rhsType->isIntegerType())
2910 return IntToPointer;
2911 if (lhsType->isIntegerType())
2912 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002913 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002914 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002915
Nate Begemanbe2341d2008-07-14 18:02:46 +00002916 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002917 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002918 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2919 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002920 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002921
Nate Begemanbe2341d2008-07-14 18:02:46 +00002922 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00002923 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00002924 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002925 if (getLangOptions().LaxVectorConversions &&
2926 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002927 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002928 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002929 }
2930 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002931 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002932
Chris Lattnere8b3e962008-01-04 23:32:24 +00002933 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002935
Chris Lattner78eca282008-04-07 06:49:41 +00002936 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002938 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002939
Chris Lattner78eca282008-04-07 06:49:41 +00002940 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002941 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002942
Steve Naroffb4406862008-09-29 18:10:17 +00002943 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002944 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002945 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002946
2947 // Treat block pointers as objects.
2948 if (getLangOptions().ObjC1 &&
2949 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2950 return Compatible;
2951 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002952 return Incompatible;
2953 }
2954
2955 if (isa<BlockPointerType>(lhsType)) {
2956 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00002957 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002958
Steve Naroffb4406862008-09-29 18:10:17 +00002959 // Treat block pointers as objects.
2960 if (getLangOptions().ObjC1 &&
2961 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2962 return Compatible;
2963
Steve Naroff1c7d0672008-09-04 15:10:53 +00002964 if (rhsType->isBlockPointerType())
2965 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002966
Steve Naroff1c7d0672008-09-04 15:10:53 +00002967 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2968 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002969 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002970 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002971 return Incompatible;
2972 }
2973
Chris Lattner78eca282008-04-07 06:49:41 +00002974 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002976 if (lhsType == Context.BoolTy)
2977 return Compatible;
2978
2979 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002980 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002981
Mike Stumpeed9cac2009-02-19 03:04:26 +00002982 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002983 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002984
2985 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff1c7d0672008-09-04 15:10:53 +00002986 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002987 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002988 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002989 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002990
Chris Lattnerfc144e22008-01-04 23:18:45 +00002991 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002992 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002993 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002994 }
2995 return Incompatible;
2996}
2997
Chris Lattner5cf216b2008-01-04 18:04:52 +00002998Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002999Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00003000 if (getLangOptions().CPlusPlus) {
3001 if (!lhsType->isRecordType()) {
3002 // C++ 5.17p3: If the left operand is not of class type, the
3003 // expression is implicitly converted (C++ 4) to the
3004 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00003005 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3006 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00003007 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00003008 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00003009 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00003010 }
3011
3012 // FIXME: Currently, we fall through and treat C++ classes like C
3013 // structures.
3014 }
3015
Steve Naroff529a4ad2007-11-27 17:58:44 +00003016 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3017 // a null pointer constant.
Steve Narofff7f52e72009-02-21 21:17:01 +00003018 if ((lhsType->isPointerType() ||
3019 lhsType->isObjCQualifiedIdType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00003020 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00003021 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003022 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00003023 return Compatible;
3024 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003025
Chris Lattner943140e2007-10-16 02:55:40 +00003026 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00003027 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00003028 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00003029 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00003030 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00003031 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00003032 if (!lhsType->isReferenceType())
3033 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00003034
Chris Lattner5cf216b2008-01-04 18:04:52 +00003035 Sema::AssignConvertType result =
3036 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003037
Steve Narofff1120de2007-08-24 22:33:52 +00003038 // C99 6.5.16.1p2: The value of the right operand is converted to the
3039 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003040 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3041 // so that we can use references in built-in functions even in C.
3042 // The getNonReferenceType() call makes sure that the resulting expression
3043 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00003044 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00003045 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00003046 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00003047}
3048
Chris Lattner5cf216b2008-01-04 18:04:52 +00003049Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00003050Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
3051 return CheckAssignmentConstraints(lhsType, rhsType);
3052}
3053
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003054QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003055 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00003056 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003057 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00003058 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003059}
3060
Mike Stumpeed9cac2009-02-19 03:04:26 +00003061inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00003062 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003063 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003064 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003065 QualType lhsType =
3066 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3067 QualType rhsType =
3068 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003069
Nate Begemanbe2341d2008-07-14 18:02:46 +00003070 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003071 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00003072 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00003073
Nate Begemanbe2341d2008-07-14 18:02:46 +00003074 // Handle the case of a vector & extvector type of the same size and element
3075 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003076 if (getLangOptions().LaxVectorConversions) {
3077 // FIXME: Should we warn here?
3078 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003079 if (const VectorType *RV = rhsType->getAsVectorType())
3080 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003081 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003082 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003083 }
3084 }
3085 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003086
Nate Begemanbe2341d2008-07-14 18:02:46 +00003087 // If the lhs is an extended vector and the rhs is a scalar of the same type
3088 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00003089 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003090 QualType eltType = V->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003091
3092 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00003093 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3094 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003095 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00003096 return lhsType;
3097 }
3098 }
3099
Nate Begemanbe2341d2008-07-14 18:02:46 +00003100 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00003101 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00003102 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003103 QualType eltType = V->getElementType();
3104
Mike Stumpeed9cac2009-02-19 03:04:26 +00003105 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00003106 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3107 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003108 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00003109 return rhsType;
3110 }
3111 }
3112
Reid Spencer5f016e22007-07-11 17:01:13 +00003113 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003114 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00003115 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003116 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003117 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00003118}
3119
Reid Spencer5f016e22007-07-11 17:01:13 +00003120inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003121 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003122{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00003123 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003124 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003125
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003126 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003127
Steve Naroffa4332e22007-07-17 00:58:39 +00003128 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003129 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003130 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003131}
3132
3133inline QualType Sema::CheckRemainderOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003134 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003135{
Daniel Dunbar523aa602009-01-05 22:55:36 +00003136 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3137 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3138 return CheckVectorOperands(Loc, lex, rex);
3139 return InvalidOperands(Loc, lex, rex);
3140 }
Steve Naroff90045e82007-07-13 23:32:42 +00003141
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003142 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003143
Steve Naroffa4332e22007-07-17 00:58:39 +00003144 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003145 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003146 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003147}
3148
3149inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stumpeed9cac2009-02-19 03:04:26 +00003150 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003151{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003152 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003153 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00003154
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003155 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00003156
Reid Spencer5f016e22007-07-11 17:01:13 +00003157 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00003158 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003159 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003160
Eli Friedmand72d16e2008-05-18 18:08:51 +00003161 // Put any potential pointer into PExp
3162 Expr* PExp = lex, *IExp = rex;
3163 if (IExp->getType()->isPointerType())
3164 std::swap(PExp, IExp);
3165
3166 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3167 if (IExp->getType()->isIntegerType()) {
3168 // Check for arithmetic on pointers to incomplete types
Douglas Gregore7450f52009-03-24 19:52:54 +00003169 if (PTy->getPointeeType()->isVoidType()) {
3170 if (getLangOptions().CPlusPlus) {
3171 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003172 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003173 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00003174 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003175
3176 // GNU extension: arithmetic on pointer to void
3177 Diag(Loc, diag::ext_gnu_void_ptr)
3178 << lex->getSourceRange() << rex->getSourceRange();
3179 } else if (PTy->getPointeeType()->isFunctionType()) {
3180 if (getLangOptions().CPlusPlus) {
3181 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3182 << lex->getType() << lex->getSourceRange();
3183 return QualType();
3184 }
3185
3186 // GNU extension: arithmetic on pointer to function
3187 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3188 << lex->getType() << lex->getSourceRange();
3189 } else if (!PTy->isDependentType() &&
3190 RequireCompleteType(Loc, PTy->getPointeeType(),
3191 diag::err_typecheck_arithmetic_incomplete_type,
3192 lex->getSourceRange(), SourceRange(),
3193 lex->getType()))
3194 return QualType();
3195
Eli Friedmand72d16e2008-05-18 18:08:51 +00003196 return PExp->getType();
3197 }
3198 }
3199
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003200 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003201}
3202
Chris Lattnereca7be62008-04-07 05:30:13 +00003203// C99 6.5.6
3204QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003205 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00003206 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003207 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003208
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003209 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003210
Chris Lattner6e4ab612007-12-09 21:53:25 +00003211 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003212
Chris Lattner6e4ab612007-12-09 21:53:25 +00003213 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00003214 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003215 return compType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003216
Chris Lattner6e4ab612007-12-09 21:53:25 +00003217 // Either ptr - int or ptr - ptr.
3218 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00003219 QualType lpointee = LHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003220
Douglas Gregore7450f52009-03-24 19:52:54 +00003221 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00003222
Douglas Gregore7450f52009-03-24 19:52:54 +00003223 bool ComplainAboutVoid = false;
3224 Expr *ComplainAboutFunc = 0;
3225 if (lpointee->isVoidType()) {
3226 if (getLangOptions().CPlusPlus) {
3227 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3228 << lex->getSourceRange() << rex->getSourceRange();
3229 return QualType();
3230 }
3231
3232 // GNU C extension: arithmetic on pointer to void
3233 ComplainAboutVoid = true;
3234 } else if (lpointee->isFunctionType()) {
3235 if (getLangOptions().CPlusPlus) {
3236 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00003237 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003238 return QualType();
3239 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003240
3241 // GNU C extension: arithmetic on pointer to function
3242 ComplainAboutFunc = lex;
3243 } else if (!lpointee->isDependentType() &&
3244 RequireCompleteType(Loc, lpointee,
3245 diag::err_typecheck_sub_ptr_object,
3246 lex->getSourceRange(),
3247 SourceRange(),
3248 lex->getType()))
3249 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003250
3251 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00003252 if (rex->getType()->isIntegerType()) {
3253 if (ComplainAboutVoid)
3254 Diag(Loc, diag::ext_gnu_void_ptr)
3255 << lex->getSourceRange() << rex->getSourceRange();
3256 if (ComplainAboutFunc)
3257 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3258 << ComplainAboutFunc->getType()
3259 << ComplainAboutFunc->getSourceRange();
3260
Chris Lattner6e4ab612007-12-09 21:53:25 +00003261 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00003262 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003263
Chris Lattner6e4ab612007-12-09 21:53:25 +00003264 // Handle pointer-pointer subtractions.
3265 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00003266 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003267
Douglas Gregore7450f52009-03-24 19:52:54 +00003268 // RHS must be a completely-type object type.
3269 // Handle the GNU void* extension.
3270 if (rpointee->isVoidType()) {
3271 if (getLangOptions().CPlusPlus) {
3272 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3273 << lex->getSourceRange() << rex->getSourceRange();
3274 return QualType();
3275 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003276
Douglas Gregore7450f52009-03-24 19:52:54 +00003277 ComplainAboutVoid = true;
3278 } else if (rpointee->isFunctionType()) {
3279 if (getLangOptions().CPlusPlus) {
3280 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00003281 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003282 return QualType();
3283 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003284
3285 // GNU extension: arithmetic on pointer to function
3286 if (!ComplainAboutFunc)
3287 ComplainAboutFunc = rex;
3288 } else if (!rpointee->isDependentType() &&
3289 RequireCompleteType(Loc, rpointee,
3290 diag::err_typecheck_sub_ptr_object,
3291 rex->getSourceRange(),
3292 SourceRange(),
3293 rex->getType()))
3294 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003295
Chris Lattner6e4ab612007-12-09 21:53:25 +00003296 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00003297 if (!Context.typesAreCompatible(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003298 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedmanf1c7b482008-09-02 05:09:35 +00003299 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003300 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00003301 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003302 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003303 return QualType();
3304 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003305
Douglas Gregore7450f52009-03-24 19:52:54 +00003306 if (ComplainAboutVoid)
3307 Diag(Loc, diag::ext_gnu_void_ptr)
3308 << lex->getSourceRange() << rex->getSourceRange();
3309 if (ComplainAboutFunc)
3310 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3311 << ComplainAboutFunc->getType()
3312 << ComplainAboutFunc->getSourceRange();
3313
Chris Lattner6e4ab612007-12-09 21:53:25 +00003314 return Context.getPointerDiffType();
3315 }
3316 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003317
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003318 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003319}
3320
Chris Lattnereca7be62008-04-07 05:30:13 +00003321// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003322QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00003323 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00003324 // C99 6.5.7p2: Each of the operands shall have integer type.
3325 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003326 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003327
Chris Lattnerca5eede2007-12-12 05:47:28 +00003328 // Shifts don't perform usual arithmetic conversions, they just do integer
3329 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00003330 if (!isCompAssign)
3331 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00003332 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003333
Chris Lattnerca5eede2007-12-12 05:47:28 +00003334 // "The type of the result is that of the promoted left operand."
3335 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003336}
3337
Chris Lattnereca7be62008-04-07 05:30:13 +00003338// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003339QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00003340 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003341 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003342 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003343
Chris Lattnera5937dd2007-08-26 01:18:55 +00003344 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00003345 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3346 UsualArithmeticConversions(lex, rex);
3347 else {
3348 UsualUnaryConversions(lex);
3349 UsualUnaryConversions(rex);
3350 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003351 QualType lType = lex->getType();
3352 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003353
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003354 if (!lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00003355 // For non-floating point types, check for self-comparisons of the form
3356 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3357 // often indicate logic errors in the program.
Ted Kremenek9ecede72009-03-20 19:57:37 +00003358 // NOTE: Don't warn about comparisons of enum constants. These can arise
3359 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00003360 Expr *LHSStripped = lex->IgnoreParens();
3361 Expr *RHSStripped = rex->IgnoreParens();
3362 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3363 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00003364 if (DRL->getDecl() == DRR->getDecl() &&
3365 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003366 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner55660a72009-03-08 19:39:53 +00003367
3368 if (isa<CastExpr>(LHSStripped))
3369 LHSStripped = LHSStripped->IgnoreParenCasts();
3370 if (isa<CastExpr>(RHSStripped))
3371 RHSStripped = RHSStripped->IgnoreParenCasts();
3372
3373 // Warn about comparisons against a string constant (unless the other
3374 // operand is null), the user probably wants strcmp.
3375 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
3376 !RHSStripped->isNullPointerConstant(Context))
3377 Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange();
3378 else if ((isa<StringLiteral>(RHSStripped) ||
3379 isa<ObjCEncodeExpr>(RHSStripped)) &&
3380 !LHSStripped->isNullPointerConstant(Context))
3381 Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange();
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003382 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003383
Douglas Gregor447b69e2008-11-19 03:25:36 +00003384 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00003385 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00003386
Chris Lattnera5937dd2007-08-26 01:18:55 +00003387 if (isRelational) {
3388 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003389 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003390 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003391 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003392 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00003393 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003394 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00003395 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003396
Chris Lattnera5937dd2007-08-26 01:18:55 +00003397 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003398 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003399 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003400
Chris Lattnerd28f8152007-08-26 01:10:14 +00003401 bool LHSIsNull = lex->isNullPointerConstant(Context);
3402 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003403
Chris Lattnera5937dd2007-08-26 01:18:55 +00003404 // All of the following pointer related warnings are GCC extensions, except
3405 // when handling null pointer constants. One day, we can consider making them
3406 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00003407 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003408 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003409 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00003410 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003411 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003412
Steve Naroff66296cb2007-11-13 14:57:38 +00003413 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003414 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3415 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00003416 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff389bf462009-02-12 17:52:19 +00003417 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003418 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003419 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003420 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00003421 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003422 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003423 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003424 // Handle block pointer types.
3425 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3426 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3427 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003428
Steve Naroff1c7d0672008-09-04 15:10:53 +00003429 if (!LHSIsNull && !RHSIsNull &&
3430 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003431 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003432 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00003433 }
3434 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003435 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003436 }
Steve Naroff59f53942008-09-28 01:11:11 +00003437 // Allow block pointers to be compared with null pointer constants.
3438 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3439 (lType->isPointerType() && rType->isBlockPointerType())) {
3440 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003441 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003442 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00003443 }
3444 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003445 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00003446 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003447
Steve Naroff20373222008-06-03 14:04:54 +00003448 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00003449 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00003450 const PointerType *LPT = lType->getAsPointerType();
3451 const PointerType *RPT = rType->getAsPointerType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003452 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00003453 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003454 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00003455 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003456
Steve Naroffa8069f12008-11-17 19:49:16 +00003457 if (!LPtrToVoid && !RPtrToVoid &&
3458 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003459 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003460 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00003461 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003462 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00003463 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003464 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003465 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00003466 }
Steve Naroff20373222008-06-03 14:04:54 +00003467 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3468 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003469 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003470 } else {
3471 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003472 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003473 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003474 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003475 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003476 }
Steve Naroff20373222008-06-03 14:04:54 +00003477 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00003478 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003479 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff20373222008-06-03 14:04:54 +00003480 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003481 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003482 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003483 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003484 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003485 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003486 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003487 if (lType->isIntegerType() &&
Steve Naroff20373222008-06-03 14:04:54 +00003488 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003489 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003490 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003491 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003492 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003493 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003494 }
Steve Naroff39218df2008-09-04 16:56:14 +00003495 // Handle block pointers.
3496 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3497 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003498 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003499 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003500 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003501 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003502 }
3503 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3504 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003505 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003506 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003507 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003508 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003509 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003510 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003511}
3512
Nate Begemanbe2341d2008-07-14 18:02:46 +00003513/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00003514/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003515/// like a scalar comparison, a vector comparison produces a vector of integer
3516/// types.
3517QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003518 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003519 bool isRelational) {
3520 // Check to make sure we're operating on vectors of the same type and width,
3521 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003522 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003523 if (vType.isNull())
3524 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003525
Nate Begemanbe2341d2008-07-14 18:02:46 +00003526 QualType lType = lex->getType();
3527 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003528
Nate Begemanbe2341d2008-07-14 18:02:46 +00003529 // For non-floating point types, check for self-comparisons of the form
3530 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3531 // often indicate logic errors in the program.
3532 if (!lType->isFloatingType()) {
3533 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3534 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3535 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003536 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003537 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003538
Nate Begemanbe2341d2008-07-14 18:02:46 +00003539 // Check for comparisons of floating point operands using != and ==.
3540 if (!isRelational && lType->isFloatingType()) {
3541 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003542 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003543 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003544
Nate Begemanbe2341d2008-07-14 18:02:46 +00003545 // Return the type for the comparison, which is the same as vector type for
3546 // integer vectors, or an integer type of identical size and number of
3547 // elements for floating point vectors.
3548 if (lType->isIntegerType())
3549 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003550
Nate Begemanbe2341d2008-07-14 18:02:46 +00003551 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00003552 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00003553 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00003554 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00003555 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3556 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3557
Mike Stumpeed9cac2009-02-19 03:04:26 +00003558 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00003559 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00003560 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3561}
3562
Reid Spencer5f016e22007-07-11 17:01:13 +00003563inline QualType Sema::CheckBitwiseOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003564 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003565{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003566 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003567 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00003568
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003569 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003570
Steve Naroffa4332e22007-07-17 00:58:39 +00003571 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003572 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003573 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003574}
3575
3576inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stumpeed9cac2009-02-19 03:04:26 +00003577 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003578{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003579 UsualUnaryConversions(lex);
3580 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003581
Eli Friedman5773a6c2008-05-13 20:16:47 +00003582 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003583 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003584 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003585}
3586
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003587/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3588/// is a read-only property; return true if so. A readonly property expression
3589/// depends on various declarations and thus must be treated specially.
3590///
Mike Stumpeed9cac2009-02-19 03:04:26 +00003591static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003592{
3593 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3594 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3595 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3596 QualType BaseType = PropExpr->getBase()->getType();
3597 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003598 if (const ObjCInterfaceType *IFTy =
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003599 PTy->getPointeeType()->getAsObjCInterfaceType())
3600 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3601 if (S.isPropertyReadonly(PDecl, IFace))
3602 return true;
3603 }
3604 }
3605 return false;
3606}
3607
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003608/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3609/// emit an error and return true. If so, return false.
3610static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003611 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3612 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3613 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003614 if (IsLV == Expr::MLV_Valid)
3615 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003616
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003617 unsigned Diag = 0;
3618 bool NeedType = false;
3619 switch (IsLV) { // C99 6.5.16p2
3620 default: assert(0 && "Unknown result from isModifiableLvalue!");
3621 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003622 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003623 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3624 NeedType = true;
3625 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003626 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003627 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3628 NeedType = true;
3629 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003630 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003631 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3632 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003633 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003634 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3635 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003636 case Expr::MLV_IncompleteType:
3637 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00003638 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003639 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3640 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003641 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003642 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3643 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003644 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003645 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3646 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003647 case Expr::MLV_ReadonlyProperty:
3648 Diag = diag::error_readonly_property_assignment;
3649 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003650 case Expr::MLV_NoSetterProperty:
3651 Diag = diag::error_nosetter_property_assignment;
3652 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003653 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003654
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003655 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003656 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003657 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003658 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003659 return true;
3660}
3661
3662
3663
3664// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003665QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3666 SourceLocation Loc,
3667 QualType CompoundType) {
3668 // Verify that LHS is a modifiable lvalue, and emit error if not.
3669 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003670 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003671
3672 QualType LHSType = LHS->getType();
3673 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003674
Chris Lattner5cf216b2008-01-04 18:04:52 +00003675 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003676 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003677 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003678 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003679 // Special case of NSObject attributes on c-style pointer types.
3680 if (ConvTy == IncompatiblePointer &&
3681 ((Context.isObjCNSObjectType(LHSType) &&
3682 Context.isObjCObjectPointerType(RHSType)) ||
3683 (Context.isObjCNSObjectType(RHSType) &&
3684 Context.isObjCObjectPointerType(LHSType))))
3685 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003686
Chris Lattner2c156472008-08-21 18:04:13 +00003687 // If the RHS is a unary plus or minus, check to see if they = and + are
3688 // right next to each other. If so, the user may have typo'd "x =+ 4"
3689 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003690 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003691 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3692 RHSCheck = ICE->getSubExpr();
3693 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3694 if ((UO->getOpcode() == UnaryOperator::Plus ||
3695 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003696 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003697 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00003698 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3699 // And there is a space or other character before the subexpr of the
3700 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00003701 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3702 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003703 Diag(Loc, diag::warn_not_compound_assign)
3704 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3705 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00003706 }
Chris Lattner2c156472008-08-21 18:04:13 +00003707 }
3708 } else {
3709 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003710 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003711 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003712
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003713 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3714 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003715 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003716
Reid Spencer5f016e22007-07-11 17:01:13 +00003717 // C99 6.5.16p3: The type of an assignment expression is the type of the
3718 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00003719 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00003720 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3721 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003722 // C++ 5.17p1: the type of the assignment expression is that of its left
3723 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003724 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003725}
3726
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003727// C99 6.5.17
3728QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00003729 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003730 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003731
3732 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
3733 // incomplete in C++).
3734
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003735 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003736}
3737
Steve Naroff49b45262007-07-13 16:58:59 +00003738/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3739/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003740QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3741 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00003742 if (Op->isTypeDependent())
3743 return Context.DependentTy;
3744
Chris Lattner3528d352008-11-21 07:05:48 +00003745 QualType ResType = Op->getType();
3746 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003747
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003748 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3749 // Decrement of bool is not allowed.
3750 if (!isInc) {
3751 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3752 return QualType();
3753 }
3754 // Increment of bool sets it to true, but is deprecated.
3755 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3756 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003757 // OK!
3758 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3759 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00003760 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003761 if (getLangOptions().CPlusPlus) {
3762 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3763 << Op->getSourceRange();
3764 return QualType();
3765 }
3766
3767 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00003768 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003769 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003770 if (getLangOptions().CPlusPlus) {
3771 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3772 << Op->getType() << Op->getSourceRange();
3773 return QualType();
3774 }
3775
3776 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003777 << ResType << Op->getSourceRange();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00003778 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
3779 diag::err_typecheck_arithmetic_incomplete_type,
3780 Op->getSourceRange(), SourceRange(),
3781 ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003782 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003783 } else if (ResType->isComplexType()) {
3784 // C99 does not support ++/-- on complex types, we allow as an extension.
3785 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003786 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003787 } else {
3788 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003789 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003790 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003791 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003792 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00003793 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003794 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003795 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003796 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003797}
3798
Anders Carlsson369dee42008-02-01 07:15:58 +00003799/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003800/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003801/// where the declaration is needed for type checking. We only need to
3802/// handle cases when the expression references a function designator
3803/// or is an lvalue. Here are some examples:
3804/// - &(x) => x
3805/// - &*****f => f for f a function designator.
3806/// - &s.xx => s
3807/// - &s.zz[1].yy -> s, if zz is an array
3808/// - *(x + 1) -> x, if x is an array
3809/// - &"123"[2] -> 0
3810/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003811static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003812 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003813 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003814 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003815 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003816 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003817 // Fields cannot be declared with a 'register' storage class.
3818 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003819 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003820 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003821 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003822 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003823 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003824
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003825 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003826 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003827 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003828 return 0;
3829 else
3830 return VD;
3831 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003832 case Stmt::UnaryOperatorClass: {
3833 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003834
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003835 switch(UO->getOpcode()) {
3836 case UnaryOperator::Deref: {
3837 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003838 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3839 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3840 if (!VD || VD->getType()->isPointerType())
3841 return 0;
3842 return VD;
3843 }
3844 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003845 }
3846 case UnaryOperator::Real:
3847 case UnaryOperator::Imag:
3848 case UnaryOperator::Extension:
3849 return getPrimaryDecl(UO->getSubExpr());
3850 default:
3851 return 0;
3852 }
3853 }
3854 case Stmt::BinaryOperatorClass: {
3855 BinaryOperator *BO = cast<BinaryOperator>(E);
3856
3857 // Handle cases involving pointer arithmetic. The result of an
3858 // Assign or AddAssign is not an lvalue so they can be ignored.
3859
3860 // (x + n) or (n + x) => x
3861 if (BO->getOpcode() == BinaryOperator::Add) {
3862 if (BO->getLHS()->getType()->isPointerType()) {
3863 return getPrimaryDecl(BO->getLHS());
3864 } else if (BO->getRHS()->getType()->isPointerType()) {
3865 return getPrimaryDecl(BO->getRHS());
3866 }
3867 }
3868
3869 return 0;
3870 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003871 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003872 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003873 case Stmt::ImplicitCastExprClass:
3874 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003875 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003876 default:
3877 return 0;
3878 }
3879}
3880
3881/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00003882/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00003883/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003884/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00003885/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003886/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00003887/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003888QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003889 if (op->isTypeDependent())
3890 return Context.DependentTy;
3891
Steve Naroff08f19672008-01-13 17:10:08 +00003892 if (getLangOptions().C99) {
3893 // Implement C99-only parts of addressof rules.
3894 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3895 if (uOp->getOpcode() == UnaryOperator::Deref)
3896 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3897 // (assuming the deref expression is valid).
3898 return uOp->getSubExpr()->getType();
3899 }
3900 // Technically, there should be a check for array subscript
3901 // expressions here, but the result of one is always an lvalue anyway.
3902 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003903 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003904 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003905
Reid Spencer5f016e22007-07-11 17:01:13 +00003906 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003907 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3908 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003909 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3910 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003911 return QualType();
3912 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003913 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003914 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3915 if (Field->isBitField()) {
3916 Diag(OpLoc, diag::err_typecheck_address_of)
3917 << "bit-field" << op->getSourceRange();
3918 return QualType();
3919 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003920 }
3921 // Check for Apple extension for accessing vector components.
Nate Begemanb104b1f2009-02-15 22:45:20 +00003922 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3923 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003924 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00003925 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003926 return QualType();
3927 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00003928 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00003929 // with the register storage-class specifier.
3930 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3931 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003932 Diag(OpLoc, diag::err_typecheck_address_of)
3933 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003934 return QualType();
3935 }
Douglas Gregor29882052008-12-10 21:26:49 +00003936 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003937 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003938 } else if (isa<FieldDecl>(dcl)) {
3939 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00003940 // Could be a pointer to member, though, if there is an explicit
3941 // scope qualifier for the class.
3942 if (isa<QualifiedDeclRefExpr>(op)) {
3943 DeclContext *Ctx = dcl->getDeclContext();
3944 if (Ctx && Ctx->isRecord())
3945 return Context.getMemberPointerType(op->getType(),
3946 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3947 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003948 } else if (isa<FunctionDecl>(dcl)) {
3949 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00003950 // As above.
3951 if (isa<QualifiedDeclRefExpr>(op)) {
3952 DeclContext *Ctx = dcl->getDeclContext();
3953 if (Ctx && Ctx->isRecord())
3954 return Context.getMemberPointerType(op->getType(),
3955 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3956 }
Douglas Gregor29882052008-12-10 21:26:49 +00003957 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003958 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003959 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003960 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00003961
Reid Spencer5f016e22007-07-11 17:01:13 +00003962 // If the operand has type "type", the result has type "pointer to type".
3963 return Context.getPointerType(op->getType());
3964}
3965
Chris Lattner22caddc2008-11-23 09:13:29 +00003966QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00003967 if (Op->isTypeDependent())
3968 return Context.DependentTy;
3969
Chris Lattner22caddc2008-11-23 09:13:29 +00003970 UsualUnaryConversions(Op);
3971 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003972
Chris Lattner22caddc2008-11-23 09:13:29 +00003973 // Note that per both C89 and C99, this is always legal, even if ptype is an
3974 // incomplete type or void. It would be possible to warn about dereferencing
3975 // a void pointer, but it's completely well-defined, and such a warning is
3976 // unlikely to catch any mistakes.
3977 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003978 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003979
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003980 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003981 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003982 return QualType();
3983}
3984
3985static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3986 tok::TokenKind Kind) {
3987 BinaryOperator::Opcode Opc;
3988 switch (Kind) {
3989 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00003990 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3991 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003992 case tok::star: Opc = BinaryOperator::Mul; break;
3993 case tok::slash: Opc = BinaryOperator::Div; break;
3994 case tok::percent: Opc = BinaryOperator::Rem; break;
3995 case tok::plus: Opc = BinaryOperator::Add; break;
3996 case tok::minus: Opc = BinaryOperator::Sub; break;
3997 case tok::lessless: Opc = BinaryOperator::Shl; break;
3998 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3999 case tok::lessequal: Opc = BinaryOperator::LE; break;
4000 case tok::less: Opc = BinaryOperator::LT; break;
4001 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4002 case tok::greater: Opc = BinaryOperator::GT; break;
4003 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4004 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4005 case tok::amp: Opc = BinaryOperator::And; break;
4006 case tok::caret: Opc = BinaryOperator::Xor; break;
4007 case tok::pipe: Opc = BinaryOperator::Or; break;
4008 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4009 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4010 case tok::equal: Opc = BinaryOperator::Assign; break;
4011 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4012 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4013 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4014 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4015 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4016 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4017 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4018 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4019 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4020 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4021 case tok::comma: Opc = BinaryOperator::Comma; break;
4022 }
4023 return Opc;
4024}
4025
4026static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4027 tok::TokenKind Kind) {
4028 UnaryOperator::Opcode Opc;
4029 switch (Kind) {
4030 default: assert(0 && "Unknown unary op!");
4031 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4032 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4033 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4034 case tok::star: Opc = UnaryOperator::Deref; break;
4035 case tok::plus: Opc = UnaryOperator::Plus; break;
4036 case tok::minus: Opc = UnaryOperator::Minus; break;
4037 case tok::tilde: Opc = UnaryOperator::Not; break;
4038 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004039 case tok::kw___real: Opc = UnaryOperator::Real; break;
4040 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4041 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4042 }
4043 return Opc;
4044}
4045
Douglas Gregoreaebc752008-11-06 23:29:22 +00004046/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4047/// operator @p Opc at location @c TokLoc. This routine only supports
4048/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004049Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4050 unsigned Op,
4051 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00004052 QualType ResultTy; // Result type of the binary operator.
4053 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
4054 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
4055
4056 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00004057 case BinaryOperator::Assign:
4058 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4059 break;
Sebastian Redl22460502009-02-07 00:15:38 +00004060 case BinaryOperator::PtrMemD:
4061 case BinaryOperator::PtrMemI:
4062 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4063 Opc == BinaryOperator::PtrMemI);
4064 break;
4065 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00004066 case BinaryOperator::Div:
4067 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4068 break;
4069 case BinaryOperator::Rem:
4070 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4071 break;
4072 case BinaryOperator::Add:
4073 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4074 break;
4075 case BinaryOperator::Sub:
4076 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4077 break;
Sebastian Redl22460502009-02-07 00:15:38 +00004078 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00004079 case BinaryOperator::Shr:
4080 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4081 break;
4082 case BinaryOperator::LE:
4083 case BinaryOperator::LT:
4084 case BinaryOperator::GE:
4085 case BinaryOperator::GT:
4086 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
4087 break;
4088 case BinaryOperator::EQ:
4089 case BinaryOperator::NE:
4090 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
4091 break;
4092 case BinaryOperator::And:
4093 case BinaryOperator::Xor:
4094 case BinaryOperator::Or:
4095 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4096 break;
4097 case BinaryOperator::LAnd:
4098 case BinaryOperator::LOr:
4099 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4100 break;
4101 case BinaryOperator::MulAssign:
4102 case BinaryOperator::DivAssign:
4103 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4104 if (!CompTy.isNull())
4105 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4106 break;
4107 case BinaryOperator::RemAssign:
4108 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4109 if (!CompTy.isNull())
4110 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4111 break;
4112 case BinaryOperator::AddAssign:
4113 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
4114 if (!CompTy.isNull())
4115 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4116 break;
4117 case BinaryOperator::SubAssign:
4118 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
4119 if (!CompTy.isNull())
4120 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4121 break;
4122 case BinaryOperator::ShlAssign:
4123 case BinaryOperator::ShrAssign:
4124 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4125 if (!CompTy.isNull())
4126 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4127 break;
4128 case BinaryOperator::AndAssign:
4129 case BinaryOperator::XorAssign:
4130 case BinaryOperator::OrAssign:
4131 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4132 if (!CompTy.isNull())
4133 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4134 break;
4135 case BinaryOperator::Comma:
4136 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4137 break;
4138 }
4139 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004140 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004141 if (CompTy.isNull())
4142 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4143 else
4144 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004145 CompTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00004146}
4147
Reid Spencer5f016e22007-07-11 17:01:13 +00004148// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004149Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4150 tok::TokenKind Kind,
4151 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004152 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004153 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00004154
Steve Narofff69936d2007-09-16 03:34:24 +00004155 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4156 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00004157
Douglas Gregor063daf62009-03-13 18:40:31 +00004158 if (getLangOptions().CPlusPlus &&
4159 (lhs->getType()->isOverloadableType() ||
4160 rhs->getType()->isOverloadableType())) {
4161 // Find all of the overloaded operators visible from this
4162 // point. We perform both an operator-name lookup from the local
4163 // scope and an argument-dependent lookup based on the types of
4164 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004165 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00004166 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4167 if (OverOp != OO_None) {
4168 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4169 Functions);
4170 Expr *Args[2] = { lhs, rhs };
4171 DeclarationName OpName
4172 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4173 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004174 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004175
Douglas Gregor063daf62009-03-13 18:40:31 +00004176 // Build the (potentially-overloaded, potentially-dependent)
4177 // binary operation.
4178 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004179 }
4180
Douglas Gregoreaebc752008-11-06 23:29:22 +00004181 // Build a built-in binary operation.
4182 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00004183}
4184
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004185Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4186 unsigned OpcIn,
4187 ExprArg InputArg) {
4188 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00004189
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004190 // FIXME: Input is modified below, but InputArg is not updated
4191 // appropriately.
4192 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00004193 QualType resultType;
4194 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004195 case UnaryOperator::PostInc:
4196 case UnaryOperator::PostDec:
4197 case UnaryOperator::OffsetOf:
4198 assert(false && "Invalid unary operator");
4199 break;
4200
Reid Spencer5f016e22007-07-11 17:01:13 +00004201 case UnaryOperator::PreInc:
4202 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004203 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4204 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004205 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004206 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00004207 resultType = CheckAddressOfOperand(Input, OpLoc);
4208 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004209 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00004210 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00004211 resultType = CheckIndirectionOperand(Input, OpLoc);
4212 break;
4213 case UnaryOperator::Plus:
4214 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004215 UsualUnaryConversions(Input);
4216 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004217 if (resultType->isDependentType())
4218 break;
Douglas Gregor74253732008-11-19 15:42:04 +00004219 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4220 break;
4221 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4222 resultType->isEnumeralType())
4223 break;
4224 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4225 Opc == UnaryOperator::Plus &&
4226 resultType->isPointerType())
4227 break;
4228
Sebastian Redl0eb23302009-01-19 00:08:26 +00004229 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4230 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004231 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004232 UsualUnaryConversions(Input);
4233 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004234 if (resultType->isDependentType())
4235 break;
Chris Lattner02a65142008-07-25 23:52:49 +00004236 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4237 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4238 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004239 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004240 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00004241 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004242 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4243 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004244 break;
4245 case UnaryOperator::LNot: // logical negation
4246 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004247 DefaultFunctionArrayConversion(Input);
4248 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004249 if (resultType->isDependentType())
4250 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004251 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00004252 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4253 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004254 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00004255 // In C++, it's bool. C++ 5.3.1p8
4256 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004257 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00004258 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00004259 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00004260 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00004261 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004262 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00004263 resultType = Input->getType();
4264 break;
4265 }
4266 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004267 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004268
4269 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004270 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004271}
4272
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004273// Unary Operators. 'Tok' is the token for the operator.
4274Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4275 tok::TokenKind Op, ExprArg input) {
4276 Expr *Input = (Expr*)input.get();
4277 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4278
4279 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4280 // Find all of the overloaded operators visible from this
4281 // point. We perform both an operator-name lookup from the local
4282 // scope and an argument-dependent lookup based on the types of
4283 // the arguments.
4284 FunctionSet Functions;
4285 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4286 if (OverOp != OO_None) {
4287 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4288 Functions);
4289 DeclarationName OpName
4290 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4291 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4292 }
4293
4294 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4295 }
4296
4297 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4298}
4299
Steve Naroff1b273c42007-09-16 14:56:35 +00004300/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00004301Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4302 SourceLocation LabLoc,
4303 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004304 // Look up the record for this label identifier.
Steve Naroffd8eb4562009-03-13 16:03:38 +00004305 LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4306 LabelMap[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00004307
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00004308 // If we haven't seen this label yet, create a forward reference. It
4309 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00004310 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00004311 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004312
Reid Spencer5f016e22007-07-11 17:01:13 +00004313 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00004314 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4315 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00004316}
4317
Sebastian Redlf53597f2009-03-15 17:47:39 +00004318Sema::OwningExprResult
4319Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4320 SourceLocation RPLoc) { // "({..})"
4321 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004322 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4323 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4324
Eli Friedmandca2b732009-01-24 23:09:00 +00004325 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4326 if (isFileScope) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00004327 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00004328 }
4329
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004330 // FIXME: there are a variety of strange constraints to enforce here, for
4331 // example, it is not possible to goto into a stmt expression apparently.
4332 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004333
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004334 // FIXME: the last statement in the compount stmt has its value used. We
4335 // should not warn about it being unused.
4336
4337 // If there are sub stmts in the compound stmt, take the type of the last one
4338 // as the type of the stmtexpr.
4339 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004340
Chris Lattner611b2ec2008-07-26 19:51:01 +00004341 if (!Compound->body_empty()) {
4342 Stmt *LastStmt = Compound->body_back();
4343 // If LastStmt is a label, skip down through into the body.
4344 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4345 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004346
Chris Lattner611b2ec2008-07-26 19:51:01 +00004347 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004348 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00004349 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004350
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004351 // FIXME: Check that expression type is complete/non-abstract; statement
4352 // expressions are not lvalues.
4353
Sebastian Redlf53597f2009-03-15 17:47:39 +00004354 substmt.release();
4355 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004356}
Steve Naroffd34e9152007-08-01 22:05:33 +00004357
Sebastian Redlf53597f2009-03-15 17:47:39 +00004358Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4359 SourceLocation BuiltinLoc,
4360 SourceLocation TypeLoc,
4361 TypeTy *argty,
4362 OffsetOfComponent *CompPtr,
4363 unsigned NumComponents,
4364 SourceLocation RPLoc) {
4365 // FIXME: This function leaks all expressions in the offset components on
4366 // error.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004367 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4368 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004369
Sebastian Redl28507842009-02-26 14:39:58 +00004370 bool Dependent = ArgTy->isDependentType();
4371
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004372 // We must have at least one component that refers to the type, and the first
4373 // one is known to be a field designator. Verify that the ArgTy represents
4374 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00004375 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00004376 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004377
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004378 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4379 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00004380
Eli Friedman35183ac2009-02-27 06:44:11 +00004381 // Otherwise, create a null pointer as the base, and iteratively process
4382 // the offsetof designators.
4383 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4384 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004385 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00004386 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00004387
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004388 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4389 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00004390 // FIXME: This diagnostic isn't actually visible because the location is in
4391 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004392 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004393 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4394 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004395
Sebastian Redl28507842009-02-26 14:39:58 +00004396 if (!Dependent) {
4397 // FIXME: Dependent case loses a lot of information here. And probably
4398 // leaks like a sieve.
4399 for (unsigned i = 0; i != NumComponents; ++i) {
4400 const OffsetOfComponent &OC = CompPtr[i];
4401 if (OC.isBrackets) {
4402 // Offset of an array sub-field. TODO: Should we allow vector elements?
4403 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4404 if (!AT) {
4405 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004406 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4407 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00004408 }
4409
4410 // FIXME: C++: Verify that operator[] isn't overloaded.
4411
Eli Friedman35183ac2009-02-27 06:44:11 +00004412 // Promote the array so it looks more like a normal array subscript
4413 // expression.
4414 DefaultFunctionArrayConversion(Res);
4415
Sebastian Redl28507842009-02-26 14:39:58 +00004416 // C99 6.5.2.1p1
4417 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004418 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00004419 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00004420 return ExprError(Diag(Idx->getLocStart(),
4421 diag::err_typecheck_subscript)
4422 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00004423
4424 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4425 OC.LocEnd);
4426 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004427 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004428
Sebastian Redl28507842009-02-26 14:39:58 +00004429 const RecordType *RC = Res->getType()->getAsRecordType();
4430 if (!RC) {
4431 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004432 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4433 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00004434 }
Chris Lattner704fe352007-08-30 17:59:59 +00004435
Sebastian Redl28507842009-02-26 14:39:58 +00004436 // Get the decl corresponding to this.
4437 RecordDecl *RD = RC->getDecl();
4438 FieldDecl *MemberDecl
4439 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4440 LookupMemberName)
4441 .getAsDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +00004442 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00004443 if (!MemberDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +00004444 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4445 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00004446
Sebastian Redl28507842009-02-26 14:39:58 +00004447 // FIXME: C++: Verify that MemberDecl isn't a static field.
4448 // FIXME: Verify that MemberDecl isn't a bitfield.
4449 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4450 // matter here.
4451 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004452 MemberDecl->getType().getNonReferenceType());
Sebastian Redl28507842009-02-26 14:39:58 +00004453 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004454 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004455
Sebastian Redlf53597f2009-03-15 17:47:39 +00004456 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4457 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004458}
4459
4460
Sebastian Redlf53597f2009-03-15 17:47:39 +00004461Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4462 TypeTy *arg1,TypeTy *arg2,
4463 SourceLocation RPLoc) {
Steve Naroffd34e9152007-08-01 22:05:33 +00004464 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4465 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004466
Steve Naroffd34e9152007-08-01 22:05:33 +00004467 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004468
Sebastian Redlf53597f2009-03-15 17:47:39 +00004469 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4470 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00004471}
4472
Sebastian Redlf53597f2009-03-15 17:47:39 +00004473Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4474 ExprArg cond,
4475 ExprArg expr1, ExprArg expr2,
4476 SourceLocation RPLoc) {
4477 Expr *CondExpr = static_cast<Expr*>(cond.get());
4478 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4479 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004480
Steve Naroffd04fdd52007-08-03 21:21:27 +00004481 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4482
Sebastian Redl28507842009-02-26 14:39:58 +00004483 QualType resType;
4484 if (CondExpr->isValueDependent()) {
4485 resType = Context.DependentTy;
4486 } else {
4487 // The conditional expression is required to be a constant expression.
4488 llvm::APSInt condEval(32);
4489 SourceLocation ExpLoc;
4490 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00004491 return ExprError(Diag(ExpLoc,
4492 diag::err_typecheck_choose_expr_requires_constant)
4493 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00004494
Sebastian Redl28507842009-02-26 14:39:58 +00004495 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4496 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4497 }
4498
Sebastian Redlf53597f2009-03-15 17:47:39 +00004499 cond.release(); expr1.release(); expr2.release();
4500 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4501 resType, RPLoc));
Steve Naroffd04fdd52007-08-03 21:21:27 +00004502}
4503
Steve Naroff4eb206b2008-09-03 18:15:37 +00004504//===----------------------------------------------------------------------===//
4505// Clang Extensions.
4506//===----------------------------------------------------------------------===//
4507
4508/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004509void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004510 // Analyze block parameters.
4511 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004512
Steve Naroff4eb206b2008-09-03 18:15:37 +00004513 // Add BSI to CurBlock.
4514 BSI->PrevBlockInfo = CurBlock;
4515 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004516
Steve Naroff4eb206b2008-09-03 18:15:37 +00004517 BSI->ReturnType = 0;
4518 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00004519 BSI->hasBlockDeclRefExprs = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004520
Steve Naroff090276f2008-10-10 01:28:17 +00004521 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004522 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004523}
4524
Mike Stump98eb8a72009-02-04 22:31:32 +00004525void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4526 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4527
4528 if (ParamInfo.getNumTypeObjects() == 0
4529 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4530 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4531
4532 // The type is entirely optional as well, if none, use DependentTy.
4533 if (T.isNull())
4534 T = Context.DependentTy;
4535
4536 // The parameter list is optional, if there was none, assume ().
4537 if (!T->isFunctionType())
4538 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4539
4540 CurBlock->hasPrototype = true;
4541 CurBlock->isVariadic = false;
4542 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4543 .getTypePtr();
4544
4545 if (!RetTy->isDependentType())
4546 CurBlock->ReturnType = RetTy;
4547 return;
4548 }
4549
Steve Naroff4eb206b2008-09-03 18:15:37 +00004550 // Analyze arguments to block.
4551 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4552 "Not a function declarator!");
4553 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004554
Steve Naroff090276f2008-10-10 01:28:17 +00004555 CurBlock->hasPrototype = FTI.hasPrototype;
4556 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004557
Steve Naroff4eb206b2008-09-03 18:15:37 +00004558 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4559 // no arguments, not a function that takes a single void argument.
4560 if (FTI.hasPrototype &&
4561 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4562 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4563 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4564 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004565 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004566 } else if (FTI.hasPrototype) {
4567 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004568 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4569 CurBlock->isVariadic = FTI.isVariadic;
Mike Stump98eb8a72009-02-04 22:31:32 +00004570 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4571
4572 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4573 .getTypePtr();
4574
4575 if (!RetTy->isDependentType())
4576 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004577 }
Steve Naroffe78b8092009-03-13 16:56:44 +00004578 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
4579 CurBlock->Params.size());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004580
Steve Naroff090276f2008-10-10 01:28:17 +00004581 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4582 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4583 // If this has an identifier, add it to the scope stack.
4584 if ((*AI)->getIdentifier())
4585 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004586}
4587
4588/// ActOnBlockError - If there is an error parsing a block, this callback
4589/// is invoked to pop the information about the block from the action impl.
4590void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4591 // Ensure that CurBlock is deleted.
4592 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004593
Steve Naroff4eb206b2008-09-03 18:15:37 +00004594 // Pop off CurBlock, handle nested blocks.
4595 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004596
Steve Naroff4eb206b2008-09-03 18:15:37 +00004597 // FIXME: Delete the ParmVarDecl objects as well???
Douglas Gregor4a471aa2009-03-11 23:54:15 +00004598
Steve Naroff4eb206b2008-09-03 18:15:37 +00004599}
4600
4601/// ActOnBlockStmtExpr - This is called when the body of a block statement
4602/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00004603Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4604 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00004605 // If blocks are disabled, emit an error.
4606 if (!LangOpts.Blocks)
4607 Diag(CaretLoc, diag::err_blocks_disable);
4608
Steve Naroff4eb206b2008-09-03 18:15:37 +00004609 // Ensure that CurBlock is deleted.
4610 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004611
Steve Naroff090276f2008-10-10 01:28:17 +00004612 PopDeclContext();
4613
Steve Naroff4eb206b2008-09-03 18:15:37 +00004614 // Pop off CurBlock, handle nested blocks.
4615 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004616
Steve Naroff4eb206b2008-09-03 18:15:37 +00004617 QualType RetTy = Context.VoidTy;
4618 if (BSI->ReturnType)
4619 RetTy = QualType(BSI->ReturnType, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004620
Steve Naroff4eb206b2008-09-03 18:15:37 +00004621 llvm::SmallVector<QualType, 8> ArgTypes;
4622 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4623 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004624
Steve Naroff4eb206b2008-09-03 18:15:37 +00004625 QualType BlockTy;
4626 if (!BSI->hasPrototype)
Douglas Gregor72564e72009-02-26 23:50:07 +00004627 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004628 else
4629 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004630 BSI->isVariadic, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004631
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004632 // FIXME: Check that return/parameter types are complete/non-abstract
4633
Steve Naroff4eb206b2008-09-03 18:15:37 +00004634 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004635
Sebastian Redlf53597f2009-03-15 17:47:39 +00004636 BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4637 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4638 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00004639}
4640
Sebastian Redlf53597f2009-03-15 17:47:39 +00004641Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4642 ExprArg expr, TypeTy *type,
4643 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004644 QualType T = QualType::getFromOpaquePtr(type);
4645
4646 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004647
4648 // Get the va_list type
4649 QualType VaListType = Context.getBuiltinVaListType();
4650 // Deal with implicit array decay; for example, on x86-64,
4651 // va_list is an array, but it's supposed to decay to
4652 // a pointer for va_arg.
4653 if (VaListType->isArrayType())
4654 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004655 // Make sure the input expression also decays appropriately.
Sebastian Redlf53597f2009-03-15 17:47:39 +00004656 Expr *E = static_cast<Expr*>(expr.get());
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004657 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004658
4659 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Sebastian Redlf53597f2009-03-15 17:47:39 +00004660 return ExprError(Diag(E->getLocStart(),
4661 diag::err_first_argument_to_va_arg_not_of_type_va_list)
4662 << E->getType() << E->getSourceRange());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004663
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004664 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004665 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004666
Sebastian Redlf53597f2009-03-15 17:47:39 +00004667 expr.release();
4668 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4669 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004670}
4671
Sebastian Redlf53597f2009-03-15 17:47:39 +00004672Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004673 // The type of __null will be int or long, depending on the size of
4674 // pointers on the target.
4675 QualType Ty;
4676 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4677 Ty = Context.IntTy;
4678 else
4679 Ty = Context.LongTy;
4680
Sebastian Redlf53597f2009-03-15 17:47:39 +00004681 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004682}
4683
Chris Lattner5cf216b2008-01-04 18:04:52 +00004684bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4685 SourceLocation Loc,
4686 QualType DstType, QualType SrcType,
4687 Expr *SrcExpr, const char *Flavor) {
4688 // Decode the result (notice that AST's are still created for extensions).
4689 bool isInvalid = false;
4690 unsigned DiagKind;
4691 switch (ConvTy) {
4692 default: assert(0 && "Unknown conversion type");
4693 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004694 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004695 DiagKind = diag::ext_typecheck_convert_pointer_int;
4696 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004697 case IntToPointer:
4698 DiagKind = diag::ext_typecheck_convert_int_pointer;
4699 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004700 case IncompatiblePointer:
4701 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4702 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004703 case IncompatiblePointerSign:
4704 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
4705 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004706 case FunctionVoidPointer:
4707 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4708 break;
4709 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004710 // If the qualifiers lost were because we were applying the
4711 // (deprecated) C++ conversion from a string literal to a char*
4712 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4713 // Ideally, this check would be performed in
4714 // CheckPointerTypesForAssignment. However, that would require a
4715 // bit of refactoring (so that the second argument is an
4716 // expression, rather than a type), which should be done as part
4717 // of a larger effort to fix CheckPointerTypesForAssignment for
4718 // C++ semantics.
4719 if (getLangOptions().CPlusPlus &&
4720 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4721 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004722 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4723 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004724 case IntToBlockPointer:
4725 DiagKind = diag::err_int_to_block_pointer;
4726 break;
4727 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004728 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004729 break;
Steve Naroff39579072008-10-14 22:18:38 +00004730 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00004731 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00004732 // it can give a more specific diagnostic.
4733 DiagKind = diag::warn_incompatible_qualified_id;
4734 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004735 case IncompatibleVectors:
4736 DiagKind = diag::warn_incompatible_vectors;
4737 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004738 case Incompatible:
4739 DiagKind = diag::err_typecheck_convert_incompatible;
4740 isInvalid = true;
4741 break;
4742 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004743
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004744 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4745 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004746 return isInvalid;
4747}
Anders Carlssone21555e2008-11-30 19:50:32 +00004748
4749bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4750{
4751 Expr::EvalResult EvalResult;
4752
Mike Stumpeed9cac2009-02-19 03:04:26 +00004753 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00004754 EvalResult.HasSideEffects) {
4755 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4756
4757 if (EvalResult.Diag) {
4758 // We only show the note if it's not the usual "invalid subexpression"
4759 // or if it's actually in a subexpression.
4760 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4761 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4762 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4763 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004764
Anders Carlssone21555e2008-11-30 19:50:32 +00004765 return true;
4766 }
4767
4768 if (EvalResult.Diag) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004769 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssone21555e2008-11-30 19:50:32 +00004770 E->getSourceRange();
4771
4772 // Print the reason it's not a constant.
4773 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4774 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4775 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004776
Anders Carlssone21555e2008-11-30 19:50:32 +00004777 if (Result)
4778 *Result = EvalResult.Val.getInt();
4779 return false;
4780}