blob: c46bde00ffcaa5eafea8741e647eed3eee0d6651 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Douglas Gregoraa57e862009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62 MD->isInstanceMethod());
63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64 }
65 }
66 }
67
68 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000069 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70 }
71
Douglas Gregoraa57e862009-02-18 21:56:37 +000072 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000074 if (FD->isDeleted()) {
75 Diag(Loc, diag::err_deleted_function_use);
76 Diag(D->getLocation(), diag::note_unavailable_here) << true;
77 return true;
78 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000079 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000080
81 // See if the decl is unavailable
82 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000083 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000084 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85 }
86
Douglas Gregoraa57e862009-02-18 21:56:37 +000087 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000088}
89
Douglas Gregor3bb30002009-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 Lattner299b8842008-07-25 21:10:04 +000095//===----------------------------------------------------------------------===//
96// Standard Promotions and Conversions
97//===----------------------------------------------------------------------===//
98
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000104 if (Ty->isFunctionType())
105 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-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).
Argiris Kirtzidisf580b4d2008-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 Lattner2aa68822008-07-25 21:33:13 +0000120 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
121 }
Chris Lattner299b8842008-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 Lattner299b8842008-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 Lattner9305c3d2008-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 Carlsson4b8e38c2009-01-16 16:48:51 +0000156// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
157// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000158void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-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 Lattner299b8842008-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 Gregor70d26122008-11-12 17:17:38 +0000181
Chris Lattner299b8842008-07-25 21:10:04 +0000182 // For conversion purposes, we ignore any qualifiers.
183 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000184 QualType lhs =
185 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
186 QualType rhs =
187 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-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 Lattner2cb744b2009-02-15 22:43:40 +0000212 if (lhs->isPromotableIntegerType())
213 lhs = Context.IntTy;
214 else
215 lhs = lhs.getUnqualifiedType();
216 if (rhs->isPromotableIntegerType())
217 rhs = Context.IntTy;
218 else
219 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000220
Chris Lattner299b8842008-07-25 21:10:04 +0000221 // If both types are identical, no conversion is needed.
222 if (lhs == rhs)
223 return lhs;
224
225 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
226 // The caller can deal with this (e.g. pointer + int).
227 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
228 return lhs;
229
230 // At this point, we have two different arithmetic types.
231
232 // Handle complex types first (C99 6.3.1.8p1).
233 if (lhs->isComplexType() || rhs->isComplexType()) {
234 // if we have an integer operand, the result is the complex type.
235 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
236 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000237 return lhs;
238 }
239 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
240 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000241 return rhs;
242 }
243 // This handles complex/complex, complex/float, or float/complex.
244 // When both operands are complex, the shorter operand is converted to the
245 // type of the longer, and that is the type of the result. This corresponds
246 // to what is done when combining two real floating-point operands.
247 // The fun begins when size promotion occur across type domains.
248 // From H&S 6.3.4: When one operand is complex and the other is a real
249 // floating-point type, the less precise type is converted, within it's
250 // real or complex domain, to the precision of the other type. For example,
251 // when combining a "long double" with a "double _Complex", the
252 // "double _Complex" is promoted to "long double _Complex".
253 int result = Context.getFloatingTypeOrder(lhs, rhs);
254
255 if (result > 0) { // The left side is bigger, convert rhs.
256 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000257 } else if (result < 0) { // The right side is bigger, convert lhs.
258 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000259 }
260 // At this point, lhs and rhs have the same rank/size. Now, make sure the
261 // domains match. This is a requirement for our implementation, C99
262 // does not require this promotion.
263 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
264 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000265 return rhs;
266 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000267 return lhs;
268 }
269 }
270 return lhs; // The domain/size match exactly.
271 }
272 // Now handle "real" floating types (i.e. float, double, long double).
273 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
274 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000275 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000276 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000277 return lhs;
278 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000279 if (rhs->isComplexIntegerType()) {
280 // convert rhs to the complex floating point type.
281 return Context.getComplexType(lhs);
282 }
283 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000284 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000285 return rhs;
286 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000287 if (lhs->isComplexIntegerType()) {
288 // convert lhs to the complex floating point type.
289 return Context.getComplexType(rhs);
290 }
Chris Lattner299b8842008-07-25 21:10:04 +0000291 // We have two real floating types, float/complex combos were handled above.
292 // Convert the smaller operand to the bigger result.
293 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000294 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000295 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000296 assert(result < 0 && "illegal float comparison");
297 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000298 }
299 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
300 // Handle GCC complex int extension.
301 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
302 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
303
304 if (lhsComplexInt && rhsComplexInt) {
305 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000306 rhsComplexInt->getElementType()) >= 0)
307 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000308 return rhs;
309 } else if (lhsComplexInt && rhs->isIntegerType()) {
310 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000311 return lhs;
312 } else if (rhsComplexInt && lhs->isIntegerType()) {
313 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000314 return rhs;
315 }
316 }
317 // Finally, we have two differing integer types.
318 // The rules for this case are in C99 6.3.1.8
319 int compare = Context.getIntegerTypeOrder(lhs, rhs);
320 bool lhsSigned = lhs->isSignedIntegerType(),
321 rhsSigned = rhs->isSignedIntegerType();
322 QualType destType;
323 if (lhsSigned == rhsSigned) {
324 // Same signedness; use the higher-ranked type
325 destType = compare >= 0 ? lhs : rhs;
326 } else if (compare != (lhsSigned ? 1 : -1)) {
327 // The unsigned type has greater than or equal rank to the
328 // signed type, so use the unsigned type
329 destType = lhsSigned ? rhs : lhs;
330 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
331 // The two types are different widths; if we are here, that
332 // means the signed type is larger than the unsigned type, so
333 // use the signed type.
334 destType = lhsSigned ? lhs : rhs;
335 } else {
336 // The signed type is higher-ranked than the unsigned type,
337 // but isn't actually any bigger (like unsigned int and long
338 // on most 32-bit systems). Use the unsigned type corresponding
339 // to the signed type.
340 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
341 }
Chris Lattner299b8842008-07-25 21:10:04 +0000342 return destType;
343}
344
345//===----------------------------------------------------------------------===//
346// Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
Steve Naroff87d58b42007-09-16 03:34:24 +0000350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000351/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens. However, the common case is that StringToks points to one
354/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000355///
356Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000358 assert(NumStringToks && "Must have at least one string!");
359
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000360 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000361 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000362 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000363
364 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
365 for (unsigned i = 0; i != NumStringToks; ++i)
366 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000367
Chris Lattnera6dcce32008-02-11 00:02:17 +0000368 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000369 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000371
372 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
373 if (getLangOptions().CPlusPlus)
374 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000375
Chris Lattnera6dcce32008-02-11 00:02:17 +0000376 // Get an array type for the string, according to C99 6.4.5. This includes
377 // the nul terminator character as well as the string length for pascal
378 // strings.
379 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000380 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000381 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000382
Chris Lattner4b009652007-07-25 00:24:17 +0000383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000384 return Owned(StringLiteral::Create(Context, Literal.GetString(),
385 Literal.GetStringLength(),
386 Literal.AnyWide, StrTy,
387 &StringTokLocs[0],
388 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000389}
390
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
396/// FIXME: This will create BlockDeclRefExprs for global variables,
397/// function references, etc which is suboptimal :) and breaks
398/// things like "integer constant expression" tests.
399static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
400 ValueDecl *VD) {
401 // If the value is defined inside the block, we couldn't snapshot it even if
402 // we wanted to.
403 if (CurBlock->TheDecl == VD->getDeclContext())
404 return false;
405
406 // If this is an enum constant or function, it is constant, don't snapshot.
407 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408 return false;
409
410 // If this is a reference to an extern, static, or global variable, no need to
411 // snapshot it.
412 // FIXME: What about 'const' variables in C++?
413 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
414 return Var->hasLocalStorage();
415
416 return true;
417}
418
419
420
Steve Naroff0acc9c92007-09-15 18:49:24 +0000421/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000422/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000423/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000425/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
427 IdentifierInfo &II,
428 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000429 const CXXScopeSpec *SS,
430 bool isAddressOfOperand) {
431 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000432 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000433}
434
Douglas Gregor566782a2009-01-06 05:10:23 +0000435/// BuildDeclRefExpr - Build either a DeclRefExpr or a
436/// QualifiedDeclRefExpr based on whether or not SS is a
437/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000438DeclRefExpr *
439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
440 bool TypeDependent, bool ValueDependent,
441 const CXXScopeSpec *SS) {
Douglas Gregor7e508262009-03-19 03:51:16 +0000442 if (SS && !SS->isEmpty()) {
443 llvm::SmallVector<NestedNameSpecifier, 16> Specs;
444 for (CXXScopeSpec::iterator Spec = SS->begin(), SpecEnd = SS->end();
445 Spec != SpecEnd; ++Spec)
446 Specs.push_back(NestedNameSpecifier::getFromOpaquePtr(*Spec));
447 return QualifiedDeclRefExpr::Create(Context, D, Ty, Loc, TypeDependent,
448 ValueDependent, SS->getRange(),
449 &Specs[0], Specs.size());
450 } else
Steve Naroff774e4152009-01-21 00:14:39 +0000451 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000452}
453
Douglas Gregor723d3332009-01-07 00:43:41 +0000454/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
455/// variable corresponding to the anonymous union or struct whose type
456/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000457static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000458 assert(Record->isAnonymousStructOrUnion() &&
459 "Record must be an anonymous struct or union!");
460
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000461 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000462 // be an O(1) operation rather than a slow walk through DeclContext's
463 // vector (which itself will be eliminated). DeclGroups might make
464 // this even better.
465 DeclContext *Ctx = Record->getDeclContext();
466 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
467 DEnd = Ctx->decls_end();
468 D != DEnd; ++D) {
469 if (*D == Record) {
470 // The object for the anonymous struct/union directly
471 // follows its type in the list of declarations.
472 ++D;
473 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000474 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000475 return *D;
476 }
477 }
478
479 assert(false && "Missing object for anonymous record");
480 return 0;
481}
482
Sebastian Redlcd883f72009-01-18 18:53:16 +0000483Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000484Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
485 FieldDecl *Field,
486 Expr *BaseObjectExpr,
487 SourceLocation OpLoc) {
488 assert(Field->getDeclContext()->isRecord() &&
489 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
490 && "Field must be stored inside an anonymous struct or union");
491
492 // Construct the sequence of field member references
493 // we'll have to perform to get to the field in the anonymous
494 // union/struct. The list of members is built from the field
495 // outward, so traverse it backwards to go from an object in
496 // the current context to the field we found.
497 llvm::SmallVector<FieldDecl *, 4> AnonFields;
498 AnonFields.push_back(Field);
499 VarDecl *BaseObject = 0;
500 DeclContext *Ctx = Field->getDeclContext();
501 do {
502 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000503 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000504 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
505 AnonFields.push_back(AnonField);
506 else {
507 BaseObject = cast<VarDecl>(AnonObject);
508 break;
509 }
510 Ctx = Ctx->getParent();
511 } while (Ctx->isRecord() &&
512 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
513
514 // Build the expression that refers to the base object, from
515 // which we will build a sequence of member references to each
516 // of the anonymous union objects and, eventually, the field we
517 // found via name lookup.
518 bool BaseObjectIsPointer = false;
519 unsigned ExtraQuals = 0;
520 if (BaseObject) {
521 // BaseObject is an anonymous struct/union variable (and is,
522 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000523 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000524 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000525 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000526 ExtraQuals
527 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
528 } else if (BaseObjectExpr) {
529 // The caller provided the base object expression. Determine
530 // whether its a pointer and whether it adds any qualifiers to the
531 // anonymous struct/union fields we're looking into.
532 QualType ObjectType = BaseObjectExpr->getType();
533 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
534 BaseObjectIsPointer = true;
535 ObjectType = ObjectPtr->getPointeeType();
536 }
537 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
538 } else {
539 // We've found a member of an anonymous struct/union that is
540 // inside a non-anonymous struct/union, so in a well-formed
541 // program our base object expression is "this".
542 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
543 if (!MD->isStatic()) {
544 QualType AnonFieldType
545 = Context.getTagDeclType(
546 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
547 QualType ThisType = Context.getTagDeclType(MD->getParent());
548 if ((Context.getCanonicalType(AnonFieldType)
549 == Context.getCanonicalType(ThisType)) ||
550 IsDerivedFrom(ThisType, AnonFieldType)) {
551 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000552 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000553 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000554 BaseObjectIsPointer = true;
555 }
556 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000557 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
558 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000559 }
560 ExtraQuals = MD->getTypeQualifiers();
561 }
562
563 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000564 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
565 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000566 }
567
568 // Build the implicit member references to the field of the
569 // anonymous struct/union.
570 Expr *Result = BaseObjectExpr;
571 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
572 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
573 FI != FIEnd; ++FI) {
574 QualType MemberType = (*FI)->getType();
575 if (!(*FI)->isMutable()) {
576 unsigned combinedQualifiers
577 = MemberType.getCVRQualifiers() | ExtraQuals;
578 MemberType = MemberType.getQualifiedType(combinedQualifiers);
579 }
Steve Naroff774e4152009-01-21 00:14:39 +0000580 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
581 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000582 BaseObjectIsPointer = false;
583 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000584 }
585
Sebastian Redlcd883f72009-01-18 18:53:16 +0000586 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000587}
588
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000589/// ActOnDeclarationNameExpr - The parser has read some kind of name
590/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
591/// performs lookup on that name and returns an expression that refers
592/// to that name. This routine isn't directly called from the parser,
593/// because the parser doesn't know about DeclarationName. Rather,
594/// this routine is called by ActOnIdentifierExpr,
595/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
596/// which form the DeclarationName from the corresponding syntactic
597/// forms.
598///
599/// HasTrailingLParen indicates whether this identifier is used in a
600/// function call context. LookupCtx is only used for a C++
601/// qualified-id (foo::bar) to indicate the class or namespace that
602/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000603///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000604/// isAddressOfOperand means that this expression is the direct operand
605/// of an address-of operator. This matters because this is the only
606/// situation where a qualified name referencing a non-static member may
607/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000608Sema::OwningExprResult
609Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
610 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000611 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000612 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000613 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000614 if (SS && SS->isInvalid())
615 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000616
617 // C++ [temp.dep.expr]p3:
618 // An id-expression is type-dependent if it contains:
619 // -- a nested-name-specifier that contains a class-name that
620 // names a dependent type.
621 if (SS && isDependentScopeSpecifier(*SS)) {
622 llvm::SmallVector<NestedNameSpecifier, 16> Specs;
623 for (CXXScopeSpec::iterator Spec = SS->begin(), SpecEnd = SS->end();
624 Spec != SpecEnd; ++Spec)
625 Specs.push_back(NestedNameSpecifier::getFromOpaquePtr(*Spec));
626 return Owned(UnresolvedDeclRefExpr::Create(Context, Name, Loc,
627 SS->getRange(), &Specs[0],
628 Specs.size()));
629 }
630
Douglas Gregor411889e2009-02-13 23:20:09 +0000631 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
632 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000633
Douglas Gregor09be81b2009-02-04 17:27:36 +0000634 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000635 if (Lookup.isAmbiguous()) {
636 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
637 SS && SS->isSet() ? SS->getRange()
638 : SourceRange());
639 return ExprError();
640 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000641 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000642
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000643 // If this reference is in an Objective-C method, then ivar lookup happens as
644 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000645 IdentifierInfo *II = Name.getAsIdentifierInfo();
646 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000647 // There are two cases to handle here. 1) scoped lookup could have failed,
648 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000649 // found a decl, but that decl is outside the current instance method (i.e.
650 // a global variable). In these two cases, we do a lookup for an ivar with
651 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000652 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000653 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000654 ObjCInterfaceDecl *ClassDeclared;
655 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000656 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000657 if (DiagnoseUseOfDecl(IV, Loc))
658 return ExprError();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000659 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
660 // If a class method attemps to use a free standing ivar, this is
661 // an error.
662 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
663 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
664 << IV->getDeclName());
665 // If a class method uses a global variable, even if an ivar with
666 // same name exists, use the global.
667 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000668 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
669 ClassDeclared != IFace)
670 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000671 // FIXME: This should use a new expr for a direct reference, don't turn
672 // this into Self->ivar, just return a BareIVarExpr or something.
673 IdentifierInfo &II = Context.Idents.get("self");
674 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
675 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
676 Loc, static_cast<Expr*>(SelfExpr.release()),
677 true, true);
678 Context.setFieldDecl(IFace, IV, MRef);
679 return Owned(MRef);
680 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000681 }
682 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000683 else if (getCurMethodDecl()->isInstanceMethod()) {
684 // We should warn if a local variable hides an ivar.
685 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000686 ObjCInterfaceDecl *ClassDeclared;
687 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
688 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
689 IFace == ClassDeclared)
690 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
691 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000692 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000693 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000694 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000695 QualType T;
696
697 if (getCurMethodDecl()->isInstanceMethod())
698 T = Context.getPointerType(Context.getObjCInterfaceType(
699 getCurMethodDecl()->getClassInterface()));
700 else
701 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000702 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000703 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000704 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000705
Douglas Gregoraa57e862009-02-18 21:56:37 +0000706 // Determine whether this name might be a candidate for
707 // argument-dependent lookup.
708 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
709 HasTrailingLParen;
710
711 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000712 // We've seen something of the form
713 //
714 // identifier(
715 //
716 // and we did not find any entity by the name
717 // "identifier". However, this identifier is still subject to
718 // argument-dependent lookup, so keep track of the name.
719 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
720 Context.OverloadTy,
721 Loc));
722 }
723
Chris Lattner4b009652007-07-25 00:24:17 +0000724 if (D == 0) {
725 // Otherwise, this could be an implicitly declared function reference (legal
726 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000727 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000728 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000729 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000730 else {
731 // If this name wasn't predeclared and if this is not a function call,
732 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000733 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000734 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
735 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000736 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
737 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000738 return ExprError(Diag(Loc, diag::err_undeclared_use)
739 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000740 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000741 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000742 }
743 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000744
Sebastian Redl0c9da212009-02-03 20:19:35 +0000745 // If this is an expression of the form &Class::member, don't build an
746 // implicit member ref, because we want a pointer to the member in general,
747 // not any specific instance's member.
748 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000749 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000750 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000751 QualType DType;
752 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
753 DType = FD->getType().getNonReferenceType();
754 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
755 DType = Method->getType();
756 } else if (isa<OverloadedFunctionDecl>(D)) {
757 DType = Context.OverloadTy;
758 }
759 // Could be an inner type. That's diagnosed below, so ignore it here.
760 if (!DType.isNull()) {
761 // The pointer is type- and value-dependent if it points into something
762 // dependent.
763 bool Dependent = false;
764 for (; DC; DC = DC->getParent()) {
765 // FIXME: could stop early at namespace scope.
766 if (DC->isRecord()) {
767 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
768 if (Context.getTypeDeclType(Record)->isDependentType()) {
769 Dependent = true;
770 break;
771 }
772 }
773 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000774 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000775 }
776 }
777 }
778
Douglas Gregor723d3332009-01-07 00:43:41 +0000779 // We may have found a field within an anonymous union or struct
780 // (C++ [class.union]).
781 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
782 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
783 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000784
Douglas Gregor3257fb52008-12-22 05:46:06 +0000785 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
786 if (!MD->isStatic()) {
787 // C++ [class.mfct.nonstatic]p2:
788 // [...] if name lookup (3.4.1) resolves the name in the
789 // id-expression to a nonstatic nontype member of class X or of
790 // a base class of X, the id-expression is transformed into a
791 // class member access expression (5.2.5) using (*this) (9.3.2)
792 // as the postfix-expression to the left of the '.' operator.
793 DeclContext *Ctx = 0;
794 QualType MemberType;
795 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
796 Ctx = FD->getDeclContext();
797 MemberType = FD->getType();
798
799 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
800 MemberType = RefType->getPointeeType();
801 else if (!FD->isMutable()) {
802 unsigned combinedQualifiers
803 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
804 MemberType = MemberType.getQualifiedType(combinedQualifiers);
805 }
806 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
807 if (!Method->isStatic()) {
808 Ctx = Method->getParent();
809 MemberType = Method->getType();
810 }
811 } else if (OverloadedFunctionDecl *Ovl
812 = dyn_cast<OverloadedFunctionDecl>(D)) {
813 for (OverloadedFunctionDecl::function_iterator
814 Func = Ovl->function_begin(),
815 FuncEnd = Ovl->function_end();
816 Func != FuncEnd; ++Func) {
817 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
818 if (!DMethod->isStatic()) {
819 Ctx = Ovl->getDeclContext();
820 MemberType = Context.OverloadTy;
821 break;
822 }
823 }
824 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000825
826 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000827 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
828 QualType ThisType = Context.getTagDeclType(MD->getParent());
829 if ((Context.getCanonicalType(CtxType)
830 == Context.getCanonicalType(ThisType)) ||
831 IsDerivedFrom(ThisType, CtxType)) {
832 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000833 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000834 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000835 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000836 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000837 }
838 }
839 }
840 }
841
Douglas Gregor8acb7272008-12-11 16:49:14 +0000842 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000843 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
844 if (MD->isStatic())
845 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000846 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
847 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000848 }
849
Douglas Gregor3257fb52008-12-22 05:46:06 +0000850 // Any other ways we could have found the field in a well-formed
851 // program would have been turned into implicit member expressions
852 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000853 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
854 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000855 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000856
Chris Lattner4b009652007-07-25 00:24:17 +0000857 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000858 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000859 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000860 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000861 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000862 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000863
Steve Naroffd6163f32008-09-05 22:11:13 +0000864 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000865 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000866 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
867 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000868 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
869 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
870 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000871 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000872
Douglas Gregoraa57e862009-02-18 21:56:37 +0000873 // Check whether this declaration can be used. Note that we suppress
874 // this check when we're going to perform argument-dependent lookup
875 // on this function name, because this might not be the function
876 // that overload resolution actually selects.
877 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
878 return ExprError();
879
Douglas Gregor48840c72008-12-10 23:01:14 +0000880 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000881 // Warn about constructs like:
882 // if (void *X = foo()) { ... } else { X }.
883 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000884 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
885 Scope *CheckS = S;
886 while (CheckS) {
887 if (CheckS->isWithinElse() &&
888 CheckS->getControlParent()->isDeclScope(Var)) {
889 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000890 ExprError(Diag(Loc, diag::warn_value_always_false)
891 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000892 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000893 ExprError(Diag(Loc, diag::warn_value_always_zero)
894 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000895 break;
896 }
897
898 // Move up one more control parent to check again.
899 CheckS = CheckS->getControlParent();
900 if (CheckS)
901 CheckS = CheckS->getParent();
902 }
903 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000904 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
905 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
906 // C99 DR 316 says that, if a function type comes from a
907 // function definition (without a prototype), that type is only
908 // used for checking compatibility. Therefore, when referencing
909 // the function, we pretend that we don't have the full function
910 // type.
911 QualType T = Func->getType();
912 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000913 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
914 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000915 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
916 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000917 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000918
919 // Only create DeclRefExpr's for valid Decl's.
920 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000921 return ExprError();
922
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000923 // If the identifier reference is inside a block, and it refers to a value
924 // that is outside the block, create a BlockDeclRefExpr instead of a
925 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
926 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000927 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000928 // We do not do this for things like enum constants, global variables, etc,
929 // as they do not get snapshotted.
930 //
931 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000932 // Blocks that have these can't be constant.
933 CurBlock->hasBlockDeclRefExprs = true;
934
Eli Friedman9c2b33f2009-03-22 23:00:19 +0000935 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +0000936 // The BlocksAttr indicates the variable is bound by-reference.
937 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +0000938 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000939
Steve Naroff52059382008-10-10 01:28:17 +0000940 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman9c2b33f2009-03-22 23:00:19 +0000941 ExprTy.addConst();
942 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000943 }
944 // If this reference is not in a block or if the referenced variable is
945 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000946
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000947 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000948 bool ValueDependent = false;
949 if (getLangOptions().CPlusPlus) {
950 // C++ [temp.dep.expr]p3:
951 // An id-expression is type-dependent if it contains:
952 // - an identifier that was declared with a dependent type,
953 if (VD->getType()->isDependentType())
954 TypeDependent = true;
955 // - FIXME: a template-id that is dependent,
956 // - a conversion-function-id that specifies a dependent type,
957 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
958 Name.getCXXNameType()->isDependentType())
959 TypeDependent = true;
960 // - a nested-name-specifier that contains a class-name that
961 // names a dependent type.
962 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000963 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +0000964 DC; DC = DC->getParent()) {
965 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000966 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000967 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
968 if (Context.getTypeDeclType(Record)->isDependentType()) {
969 TypeDependent = true;
970 break;
971 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000972 }
973 }
974 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000975
Douglas Gregora5d84612008-12-10 20:57:37 +0000976 // C++ [temp.dep.constexpr]p2:
977 //
978 // An identifier is value-dependent if it is:
979 // - a name declared with a dependent type,
980 if (TypeDependent)
981 ValueDependent = true;
982 // - the name of a non-type template parameter,
983 else if (isa<NonTypeTemplateParmDecl>(VD))
984 ValueDependent = true;
985 // - a constant with integral or enumeration type and is
986 // initialized with an expression that is value-dependent
987 // (FIXME!).
988 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000989
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
991 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000992}
993
Sebastian Redlcd883f72009-01-18 18:53:16 +0000994Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
995 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000996 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000997
Chris Lattner4b009652007-07-25 00:24:17 +0000998 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000999 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001000 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1001 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1002 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001003 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001004
Chris Lattner7e637512008-01-12 08:14:25 +00001005 // Pre-defined identifiers are of type char[x], where x is the length of the
1006 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001007 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001008 if (FunctionDecl *FD = getCurFunctionDecl())
1009 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001010 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1011 Length = MD->getSynthesizedMethodSize();
1012 else {
1013 Diag(Loc, diag::ext_predef_outside_function);
1014 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1015 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1016 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001017
1018
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001019 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001020 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001021 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001022 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001023}
1024
Sebastian Redlcd883f72009-01-18 18:53:16 +00001025Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001026 llvm::SmallString<16> CharBuffer;
1027 CharBuffer.resize(Tok.getLength());
1028 const char *ThisTokBegin = &CharBuffer[0];
1029 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001030
Chris Lattner4b009652007-07-25 00:24:17 +00001031 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1032 Tok.getLocation(), PP);
1033 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001034 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001035
1036 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1037
Sebastian Redl75324932009-01-20 22:23:13 +00001038 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1039 Literal.isWide(),
1040 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001041}
1042
Sebastian Redlcd883f72009-01-18 18:53:16 +00001043Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1044 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001045 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1046 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001047 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001048 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001049 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001050 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001051 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001052
Chris Lattner4b009652007-07-25 00:24:17 +00001053 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001054 // Add padding so that NumericLiteralParser can overread by one character.
1055 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001056 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001057
Chris Lattner4b009652007-07-25 00:24:17 +00001058 // Get the spelling of the token, which eliminates trigraphs, etc.
1059 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001060
Chris Lattner4b009652007-07-25 00:24:17 +00001061 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1062 Tok.getLocation(), PP);
1063 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001064 return ExprError();
1065
Chris Lattner1de66eb2007-08-26 03:42:43 +00001066 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001067
Chris Lattner1de66eb2007-08-26 03:42:43 +00001068 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001069 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001070 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001071 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001072 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001073 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001074 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001075 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001076
1077 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1078
Ted Kremenekddedbe22007-11-29 00:56:49 +00001079 // isExact will be set by GetFloatValue().
1080 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001081 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1082 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001083
Chris Lattner1de66eb2007-08-26 03:42:43 +00001084 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001085 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001086 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001087 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001088
Neil Booth7421e9c2007-08-29 22:00:19 +00001089 // long long is a C99 feature.
1090 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001091 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001092 Diag(Tok.getLocation(), diag::ext_longlong);
1093
Chris Lattner4b009652007-07-25 00:24:17 +00001094 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001095 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001096
Chris Lattner4b009652007-07-25 00:24:17 +00001097 if (Literal.GetIntegerValue(ResultVal)) {
1098 // If this value didn't fit into uintmax_t, warn and force to ull.
1099 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001100 Ty = Context.UnsignedLongLongTy;
1101 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001102 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001103 } else {
1104 // If this value fits into a ULL, try to figure out what else it fits into
1105 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001106
Chris Lattner4b009652007-07-25 00:24:17 +00001107 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1108 // be an unsigned int.
1109 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1110
1111 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001112 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001113 if (!Literal.isLong && !Literal.isLongLong) {
1114 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001115 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001116
Chris Lattner4b009652007-07-25 00:24:17 +00001117 // Does it fit in a unsigned int?
1118 if (ResultVal.isIntN(IntSize)) {
1119 // Does it fit in a signed int?
1120 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001121 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001122 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001123 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001124 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001125 }
Chris Lattner4b009652007-07-25 00:24:17 +00001126 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001127
Chris Lattner4b009652007-07-25 00:24:17 +00001128 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001129 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001130 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001131
Chris Lattner4b009652007-07-25 00:24:17 +00001132 // Does it fit in a unsigned long?
1133 if (ResultVal.isIntN(LongSize)) {
1134 // Does it fit in a signed long?
1135 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001136 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001137 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001138 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001139 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001140 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001141 }
1142
Chris Lattner4b009652007-07-25 00:24:17 +00001143 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001144 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001145 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001146
Chris Lattner4b009652007-07-25 00:24:17 +00001147 // Does it fit in a unsigned long long?
1148 if (ResultVal.isIntN(LongLongSize)) {
1149 // Does it fit in a signed long long?
1150 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001151 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001152 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001153 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001154 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001155 }
1156 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001157
Chris Lattner4b009652007-07-25 00:24:17 +00001158 // If we still couldn't decide a type, we probably have something that
1159 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001160 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001161 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001162 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001163 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001164 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001165
Chris Lattnere4068872008-05-09 05:59:00 +00001166 if (ResultVal.getBitWidth() != Width)
1167 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001168 }
Sebastian Redl75324932009-01-20 22:23:13 +00001169 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001170 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001171
Chris Lattner1de66eb2007-08-26 03:42:43 +00001172 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1173 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001174 Res = new (Context) ImaginaryLiteral(Res,
1175 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001176
1177 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001178}
1179
Sebastian Redlcd883f72009-01-18 18:53:16 +00001180Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1181 SourceLocation R, ExprArg Val) {
1182 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001183 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001184 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001185}
1186
1187/// The UsualUnaryConversions() function is *not* called by this routine.
1188/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001189bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001190 SourceLocation OpLoc,
1191 const SourceRange &ExprRange,
1192 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001193 if (exprType->isDependentType())
1194 return false;
1195
Chris Lattner4b009652007-07-25 00:24:17 +00001196 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001197 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001198 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001199 if (isSizeof)
1200 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1201 return false;
1202 }
1203
1204 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001205 Diag(OpLoc, diag::ext_sizeof_void_type)
1206 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001207 return false;
1208 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001209
Douglas Gregorc84d8932009-03-09 16:13:40 +00001210 return RequireCompleteType(OpLoc, exprType,
Chris Lattner159fe082009-01-24 19:46:37 +00001211 isSizeof ? diag::err_sizeof_incomplete_type :
1212 diag::err_alignof_incomplete_type,
1213 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001214}
1215
Chris Lattner8d9f7962009-01-24 20:17:12 +00001216bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1217 const SourceRange &ExprRange) {
1218 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001219
Chris Lattner8d9f7962009-01-24 20:17:12 +00001220 // alignof decl is always ok.
1221 if (isa<DeclRefExpr>(E))
1222 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001223
1224 // Cannot know anything else if the expression is dependent.
1225 if (E->isTypeDependent())
1226 return false;
1227
Chris Lattner8d9f7962009-01-24 20:17:12 +00001228 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1229 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1230 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001231 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001232 return true;
1233 }
1234 // Other fields are ok.
1235 return false;
1236 }
1237 }
1238 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1239}
1240
Douglas Gregor396f1142009-03-13 21:01:28 +00001241/// \brief Build a sizeof or alignof expression given a type operand.
1242Action::OwningExprResult
1243Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1244 bool isSizeOf, SourceRange R) {
1245 if (T.isNull())
1246 return ExprError();
1247
1248 if (!T->isDependentType() &&
1249 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1250 return ExprError();
1251
1252 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1253 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1254 Context.getSizeType(), OpLoc,
1255 R.getEnd()));
1256}
1257
1258/// \brief Build a sizeof or alignof expression given an expression
1259/// operand.
1260Action::OwningExprResult
1261Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1262 bool isSizeOf, SourceRange R) {
1263 // Verify that the operand is valid.
1264 bool isInvalid = false;
1265 if (E->isTypeDependent()) {
1266 // Delay type-checking for type-dependent expressions.
1267 } else if (!isSizeOf) {
1268 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1269 } else if (E->isBitField()) { // C99 6.5.3.4p1.
1270 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1271 isInvalid = true;
1272 } else {
1273 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1274 }
1275
1276 if (isInvalid)
1277 return ExprError();
1278
1279 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1280 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1281 Context.getSizeType(), OpLoc,
1282 R.getEnd()));
1283}
1284
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001285/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1286/// the same for @c alignof and @c __alignof
1287/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001288Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001289Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1290 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001291 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001292 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001293
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001294 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001295 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1296 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1297 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001298
Douglas Gregor396f1142009-03-13 21:01:28 +00001299 // Get the end location.
1300 Expr *ArgEx = (Expr *)TyOrEx;
1301 Action::OwningExprResult Result
1302 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1303
1304 if (Result.isInvalid())
1305 DeleteExpr(ArgEx);
1306
1307 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001308}
1309
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001310QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001311 if (V->isTypeDependent())
1312 return Context.DependentTy;
1313
Chris Lattner03931a72007-08-24 21:16:53 +00001314 DefaultFunctionArrayConversion(V);
1315
Chris Lattnera16e42d2007-08-26 05:39:26 +00001316 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001317 if (const ComplexType *CT = V->getType()->getAsComplexType())
1318 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001319
1320 // Otherwise they pass through real integer and floating point types here.
1321 if (V->getType()->isArithmeticType())
1322 return V->getType();
1323
1324 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001325 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1326 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001327 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001328}
1329
1330
Chris Lattner4b009652007-07-25 00:24:17 +00001331
Sebastian Redl8b769972009-01-19 00:08:26 +00001332Action::OwningExprResult
1333Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1334 tok::TokenKind Kind, ExprArg Input) {
1335 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001336
Chris Lattner4b009652007-07-25 00:24:17 +00001337 UnaryOperator::Opcode Opc;
1338 switch (Kind) {
1339 default: assert(0 && "Unknown unary op!");
1340 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1341 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1342 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001343
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001344 if (getLangOptions().CPlusPlus &&
1345 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1346 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001347 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001348 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1349
1350 // C++ [over.inc]p1:
1351 //
1352 // [...] If the function is a member function with one
1353 // parameter (which shall be of type int) or a non-member
1354 // function with two parameters (the second of which shall be
1355 // of type int), it defines the postfix increment operator ++
1356 // for objects of that type. When the postfix increment is
1357 // called as a result of using the ++ operator, the int
1358 // argument will have value zero.
1359 Expr *Args[2] = {
1360 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001361 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1362 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001363 };
1364
1365 // Build the candidate set for overloading
1366 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001367 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001368
1369 // Perform overload resolution.
1370 OverloadCandidateSet::iterator Best;
1371 switch (BestViableFunction(CandidateSet, Best)) {
1372 case OR_Success: {
1373 // We found a built-in operator or an overloaded operator.
1374 FunctionDecl *FnDecl = Best->Function;
1375
1376 if (FnDecl) {
1377 // We matched an overloaded operator. Build a call to that
1378 // operator.
1379
1380 // Convert the arguments.
1381 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1382 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001383 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001384 } else {
1385 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001386 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001387 FnDecl->getParamDecl(0)->getType(),
1388 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001389 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001390 }
1391
1392 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001393 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001394 = FnDecl->getType()->getAsFunctionType()->getResultType();
1395 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001396
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001397 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001398 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001399 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001400 UsualUnaryConversions(FnExpr);
1401
Sebastian Redl8b769972009-01-19 00:08:26 +00001402 Input.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001403 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1404 Args, 2, ResultTy,
1405 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001406 } else {
1407 // We matched a built-in operator. Convert the arguments, then
1408 // break out so that we will build the appropriate built-in
1409 // operator node.
1410 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1411 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001412 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001413
1414 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001415 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001416 }
1417
1418 case OR_No_Viable_Function:
1419 // No viable function; fall through to handling this as a
1420 // built-in operator, which will produce an error message for us.
1421 break;
1422
1423 case OR_Ambiguous:
1424 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1425 << UnaryOperator::getOpcodeStr(Opc)
1426 << Arg->getSourceRange();
1427 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001428 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001429
1430 case OR_Deleted:
1431 Diag(OpLoc, diag::err_ovl_deleted_oper)
1432 << Best->Function->isDeleted()
1433 << UnaryOperator::getOpcodeStr(Opc)
1434 << Arg->getSourceRange();
1435 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1436 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001437 }
1438
1439 // Either we found no viable overloaded operator or we matched a
1440 // built-in operator. In either case, fall through to trying to
1441 // build a built-in operation.
1442 }
1443
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001444 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1445 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001446 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001447 return ExprError();
1448 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001449 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001450}
1451
Sebastian Redl8b769972009-01-19 00:08:26 +00001452Action::OwningExprResult
1453Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1454 ExprArg Idx, SourceLocation RLoc) {
1455 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1456 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001457
Douglas Gregor80723c52008-11-19 17:17:41 +00001458 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001459 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001460 LHSExp->getType()->isEnumeralType() ||
1461 RHSExp->getType()->isRecordType() ||
1462 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001463 // Add the appropriate overloaded operators (C++ [over.match.oper])
1464 // to the candidate set.
1465 OverloadCandidateSet CandidateSet;
1466 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001467 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1468 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001469
Douglas Gregor80723c52008-11-19 17:17:41 +00001470 // Perform overload resolution.
1471 OverloadCandidateSet::iterator Best;
1472 switch (BestViableFunction(CandidateSet, Best)) {
1473 case OR_Success: {
1474 // We found a built-in operator or an overloaded operator.
1475 FunctionDecl *FnDecl = Best->Function;
1476
1477 if (FnDecl) {
1478 // We matched an overloaded operator. Build a call to that
1479 // operator.
1480
1481 // Convert the arguments.
1482 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1483 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1484 PerformCopyInitialization(RHSExp,
1485 FnDecl->getParamDecl(0)->getType(),
1486 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001487 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001488 } else {
1489 // Convert the arguments.
1490 if (PerformCopyInitialization(LHSExp,
1491 FnDecl->getParamDecl(0)->getType(),
1492 "passing") ||
1493 PerformCopyInitialization(RHSExp,
1494 FnDecl->getParamDecl(1)->getType(),
1495 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001496 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001497 }
1498
1499 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001500 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001501 = FnDecl->getType()->getAsFunctionType()->getResultType();
1502 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001503
Douglas Gregor80723c52008-11-19 17:17:41 +00001504 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001505 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1506 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001507 UsualUnaryConversions(FnExpr);
1508
Sebastian Redl8b769972009-01-19 00:08:26 +00001509 Base.release();
1510 Idx.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001511 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1512 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001513 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001514 } else {
1515 // We matched a built-in operator. Convert the arguments, then
1516 // break out so that we will build the appropriate built-in
1517 // operator node.
1518 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1519 "passing") ||
1520 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1521 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001522 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001523
1524 break;
1525 }
1526 }
1527
1528 case OR_No_Viable_Function:
1529 // No viable function; fall through to handling this as a
1530 // built-in operator, which will produce an error message for us.
1531 break;
1532
1533 case OR_Ambiguous:
1534 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1535 << "[]"
1536 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1537 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001538 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001539
1540 case OR_Deleted:
1541 Diag(LLoc, diag::err_ovl_deleted_oper)
1542 << Best->Function->isDeleted()
1543 << "[]"
1544 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1545 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1546 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001547 }
1548
1549 // Either we found no viable overloaded operator or we matched a
1550 // built-in operator. In either case, fall through to trying to
1551 // build a built-in operation.
1552 }
1553
Chris Lattner4b009652007-07-25 00:24:17 +00001554 // Perform default conversions.
1555 DefaultFunctionArrayConversion(LHSExp);
1556 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001557
Chris Lattner4b009652007-07-25 00:24:17 +00001558 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1559
1560 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001561 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001562 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001563 // and index from the expression types.
1564 Expr *BaseExpr, *IndexExpr;
1565 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001566 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1567 BaseExpr = LHSExp;
1568 IndexExpr = RHSExp;
1569 ResultType = Context.DependentTy;
1570 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001571 BaseExpr = LHSExp;
1572 IndexExpr = RHSExp;
1573 // FIXME: need to deal with const...
1574 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001575 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001576 // Handle the uncommon case of "123[Ptr]".
1577 BaseExpr = RHSExp;
1578 IndexExpr = LHSExp;
1579 // FIXME: need to deal with const...
1580 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001581 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1582 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001583 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001584
Chris Lattner4b009652007-07-25 00:24:17 +00001585 // FIXME: need to deal with const...
1586 ResultType = VTy->getElementType();
1587 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001588 return ExprError(Diag(LHSExp->getLocStart(),
1589 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1590 }
Chris Lattner4b009652007-07-25 00:24:17 +00001591 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001592 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001593 return ExprError(Diag(IndexExpr->getLocStart(),
1594 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001595
Douglas Gregor05e28f62009-03-24 19:52:54 +00001596 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1597 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1598 // type. Note that Functions are not objects, and that (in C99 parlance)
1599 // incomplete types are not object types.
1600 if (ResultType->isFunctionType()) {
1601 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1602 << ResultType << BaseExpr->getSourceRange();
1603 return ExprError();
1604 }
1605 if (!ResultType->isDependentType() &&
1606 RequireCompleteType(BaseExpr->getLocStart(), ResultType,
1607 diag::err_subscript_incomplete_type,
1608 BaseExpr->getSourceRange()))
1609 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001610
Sebastian Redl8b769972009-01-19 00:08:26 +00001611 Base.release();
1612 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001613 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001614 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001615}
1616
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001617QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001618CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001619 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001620 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001621
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001622 // The vector accessor can't exceed the number of elements.
1623 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001624
Mike Stump9afab102009-02-19 03:04:26 +00001625 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001626 // special names that indicate a subset of exactly half the elements are
1627 // to be selected.
1628 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001629
Nate Begeman1486b502009-01-18 01:47:54 +00001630 // This flag determines whether or not CompName has an 's' char prefix,
1631 // indicating that it is a string of hex values to be used as vector indices.
1632 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001633
1634 // Check that we've found one of the special components, or that the component
1635 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001636 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001637 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1638 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001639 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001640 do
1641 compStr++;
1642 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001643 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001644 do
1645 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001646 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001647 }
Nate Begeman1486b502009-01-18 01:47:54 +00001648
Mike Stump9afab102009-02-19 03:04:26 +00001649 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001650 // We didn't get to the end of the string. This means the component names
1651 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001652 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1653 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001654 return QualType();
1655 }
Mike Stump9afab102009-02-19 03:04:26 +00001656
Nate Begeman1486b502009-01-18 01:47:54 +00001657 // Ensure no component accessor exceeds the width of the vector type it
1658 // operates on.
1659 if (!HalvingSwizzle) {
1660 compStr = CompName.getName();
1661
1662 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001663 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001664
1665 while (*compStr) {
1666 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1667 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1668 << baseType << SourceRange(CompLoc);
1669 return QualType();
1670 }
1671 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001672 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001673
Nate Begeman1486b502009-01-18 01:47:54 +00001674 // If this is a halving swizzle, verify that the base type has an even
1675 // number of elements.
1676 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001677 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001678 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001679 return QualType();
1680 }
Mike Stump9afab102009-02-19 03:04:26 +00001681
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001682 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001683 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001684 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001685 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001686 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001687 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1688 : CompName.getLength();
1689 if (HexSwizzle)
1690 CompSize--;
1691
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001692 if (CompSize == 1)
1693 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001694
Nate Begemanaf6ed502008-04-18 23:10:10 +00001695 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001696 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001697 // diagostics look bad. We want extended vector types to appear built-in.
1698 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1699 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1700 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001701 }
1702 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001703}
1704
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001705static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1706 IdentifierInfo &Member,
1707 const Selector &Sel) {
1708
1709 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
1710 return PD;
1711 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1712 return OMD;
1713
1714 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1715 E = PDecl->protocol_end(); I != E; ++I) {
1716 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel))
1717 return D;
1718 }
1719 return 0;
1720}
1721
1722static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1723 IdentifierInfo &Member,
1724 const Selector &Sel) {
1725 // Check protocols on qualified interfaces.
1726 Decl *GDecl = 0;
1727 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1728 E = QIdTy->qual_end(); I != E; ++I) {
1729 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1730 GDecl = PD;
1731 break;
1732 }
1733 // Also must look for a getter name which uses property syntax.
1734 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1735 GDecl = OMD;
1736 break;
1737 }
1738 }
1739 if (!GDecl) {
1740 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1741 E = QIdTy->qual_end(); I != E; ++I) {
1742 // Search in the protocol-qualifier list of current protocol.
1743 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel);
1744 if (GDecl)
1745 return GDecl;
1746 }
1747 }
1748 return GDecl;
1749}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001750
Sebastian Redl8b769972009-01-19 00:08:26 +00001751Action::OwningExprResult
1752Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1753 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001754 IdentifierInfo &Member,
1755 DeclTy *ObjCImpDecl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001756 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001757 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001758
1759 // Perform default conversions.
1760 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001761
Steve Naroff2cb66382007-07-26 03:11:44 +00001762 QualType BaseType = BaseExpr->getType();
1763 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001764
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001765 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1766 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001767 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001768 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001769 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001770 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001771 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1772 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001773 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001774 return ExprError(Diag(MemberLoc,
1775 diag::err_typecheck_member_reference_arrow)
1776 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001777 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001778
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001779 // Handle field access to simple records. This also handles access to fields
1780 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001781 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001782 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00001783 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001784 diag::err_typecheck_incomplete_tag,
1785 BaseExpr->getSourceRange()))
1786 return ExprError();
1787
Steve Naroff2cb66382007-07-26 03:11:44 +00001788 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001789 // FIXME: Qualified name lookup for C++ is a bit more complicated
1790 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001791 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001792 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001793 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001794
Douglas Gregor09be81b2009-02-04 17:27:36 +00001795 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001796 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001797 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1798 << &Member << BaseExpr->getSourceRange());
1799 else if (Result.isAmbiguous()) {
1800 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1801 MemberLoc, BaseExpr->getSourceRange());
1802 return ExprError();
1803 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001804 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001805
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001806 // If the decl being referenced had an error, return an error for this
1807 // sub-expr without emitting another error, in order to avoid cascading
1808 // error cases.
1809 if (MemberDecl->isInvalidDecl())
1810 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001811
Douglas Gregoraa57e862009-02-18 21:56:37 +00001812 // Check the use of this field
1813 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1814 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001815
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001816 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001817 // We may have found a field within an anonymous union or struct
1818 // (C++ [class.union]).
1819 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001820 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001821 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001822
Douglas Gregor82d44772008-12-20 23:49:58 +00001823 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1824 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001825 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001826 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1827 MemberType = Ref->getPointeeType();
1828 else {
1829 unsigned combinedQualifiers =
1830 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001831 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001832 combinedQualifiers &= ~QualType::Const;
1833 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1834 }
Eli Friedman76b49832008-02-06 22:48:16 +00001835
Steve Naroff774e4152009-01-21 00:14:39 +00001836 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1837 MemberLoc, MemberType));
Douglas Gregor00660582009-03-11 20:22:50 +00001838 } else if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001839 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001840 Var, MemberLoc,
1841 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001842 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001843 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001844 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001845 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001846 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001847 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001848 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001849 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001850 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1851 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001852 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001853 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1854 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001855
Douglas Gregor82d44772008-12-20 23:49:58 +00001856 // We found a declaration kind that we didn't expect. This is a
1857 // generic error message that tells the user that she can't refer
1858 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001859 return ExprError(Diag(MemberLoc,
1860 diag::err_typecheck_member_reference_unknown)
1861 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001862 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001863
Chris Lattnere9d71612008-07-21 04:59:05 +00001864 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1865 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001866 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001867 ObjCInterfaceDecl *ClassDeclared;
1868 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1869 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001870 // If the decl being referenced had an error, return an error for this
1871 // sub-expr without emitting another error, in order to avoid cascading
1872 // error cases.
1873 if (IV->isInvalidDecl())
1874 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001875
1876 // Check whether we can reference this field.
1877 if (DiagnoseUseOfDecl(IV, MemberLoc))
1878 return ExprError();
Steve Naroff8c56ee02009-03-26 16:01:08 +00001879 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1880 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001881 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1882 if (ObjCMethodDecl *MD = getCurMethodDecl())
1883 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001884 else if (ObjCImpDecl && getCurFunctionDecl()) {
1885 // Case of a c-function declared inside an objc implementation.
1886 // FIXME: For a c-style function nested inside an objc implementation
1887 // class, there is no implementation context available, so we pass down
1888 // the context as argument to this routine. Ideally, this context need
1889 // be passed down in the AST node and somehow calculated from the AST
1890 // for a function decl.
1891 Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl);
1892 if (ObjCImplementationDecl *IMPD =
1893 dyn_cast<ObjCImplementationDecl>(ImplDecl))
1894 ClassOfMethodDecl = IMPD->getClassInterface();
1895 else if (ObjCCategoryImplDecl* CatImplClass =
1896 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1897 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00001898 }
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001899 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001900 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001901 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001902 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1903 }
1904 // @protected
1905 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1906 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1907 }
Mike Stump9afab102009-02-19 03:04:26 +00001908
1909 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001910 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001911 OpKind == tok::arrow);
1912 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001913 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001914 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001915 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1916 << IFTy->getDecl()->getDeclName() << &Member
1917 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001918 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001919
Chris Lattnere9d71612008-07-21 04:59:05 +00001920 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1921 // pointer to a (potentially qualified) interface type.
1922 const PointerType *PTy;
1923 const ObjCInterfaceType *IFTy;
1924 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1925 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1926 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001927
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001928 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001929 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001930 // Check whether we can reference this property.
1931 if (DiagnoseUseOfDecl(PD, MemberLoc))
1932 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001933
Steve Naroff774e4152009-01-21 00:14:39 +00001934 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001935 MemberLoc, BaseExpr));
1936 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001937
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001938 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001939 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1940 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001941 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001942 // Check whether we can reference this property.
1943 if (DiagnoseUseOfDecl(PD, MemberLoc))
1944 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001945
Steve Naroff774e4152009-01-21 00:14:39 +00001946 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001947 MemberLoc, BaseExpr));
1948 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001949
1950 // If that failed, look for an "implicit" property by seeing if the nullary
1951 // selector is implemented.
1952
1953 // FIXME: The logic for looking up nullary and unary selectors should be
1954 // shared with the code in ActOnInstanceMessage.
1955
1956 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1957 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001958
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001959 // If this reference is in an @implementation, check for 'private' methods.
1960 if (!Getter)
Steve Naroffd6bceef2009-03-11 15:15:01 +00001961 if (ObjCImplementationDecl *ImpDecl =
1962 ObjCImplementations[IFace->getIdentifier()])
1963 Getter = ImpDecl->getInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001964
Steve Naroff04151f32008-10-22 19:16:27 +00001965 // Look through local category implementations associated with the class.
1966 if (!Getter) {
1967 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1968 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1969 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1970 }
1971 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001972 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001973 // Check if we can reference this property.
1974 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1975 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00001976 }
1977 // If we found a getter then this may be a valid dot-reference, we
1978 // will look for the matching setter, in case it is needed.
1979 Selector SetterSel =
1980 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1981 PP.getSelectorTable(), &Member);
1982 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1983 if (!Setter) {
1984 // If this reference is in an @implementation, also check for 'private'
1985 // methods.
Steve Naroffd6bceef2009-03-11 15:15:01 +00001986 if (ObjCImplementationDecl *ImpDecl =
1987 ObjCImplementations[IFace->getIdentifier()])
1988 Setter = ImpDecl->getInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00001989 }
1990 // Look through local category implementations associated with the class.
1991 if (!Setter) {
1992 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1993 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1994 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001995 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001996 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001997
Steve Naroffdede0c92009-03-11 13:48:17 +00001998 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1999 return ExprError();
2000
2001 if (Getter || Setter) {
2002 QualType PType;
2003
2004 if (Getter)
2005 PType = Getter->getResultType();
2006 else {
2007 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2008 E = Setter->param_end(); PI != E; ++PI)
2009 PType = (*PI)->getType();
2010 }
2011 // FIXME: we must check that the setter has property type.
2012 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2013 Setter, MemberLoc, BaseExpr));
2014 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002015 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2016 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002017 }
Steve Naroffd1d44402008-10-20 22:53:06 +00002018 // Handle properties on qualified "id" protocols.
2019 const ObjCQualifiedIdType *QIdTy;
2020 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2021 // Check protocols on qualified interfaces.
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002022 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2023 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel)) {
2024 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002025 // Check the use of this declaration
2026 if (DiagnoseUseOfDecl(PD, MemberLoc))
2027 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002028
Steve Naroff774e4152009-01-21 00:14:39 +00002029 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002030 MemberLoc, BaseExpr));
2031 }
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002032 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002033 // Check the use of this method.
2034 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2035 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002036
Mike Stump9afab102009-02-19 03:04:26 +00002037 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002038 OMD->getResultType(),
2039 OMD, OpLoc, MemberLoc,
2040 NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00002041 }
2042 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002043
2044 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2045 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00002046 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002047 // Handle properties on ObjC 'Class' types.
2048 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2049 // Also must look for a getter name which uses property syntax.
2050 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2051 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002052 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2053 ObjCMethodDecl *Getter;
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002054 // FIXME: need to also look locally in the implementation.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002055 if ((Getter = IFace->lookupClassMethod(Sel))) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002056 // Check the use of this method.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002057 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002058 return ExprError();
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002059 }
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002060 // If we found a getter then this may be a valid dot-reference, we
2061 // will look for the matching setter, in case it is needed.
2062 Selector SetterSel =
2063 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2064 PP.getSelectorTable(), &Member);
2065 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2066 if (!Setter) {
2067 // If this reference is in an @implementation, also check for 'private'
2068 // methods.
2069 if (ObjCImplementationDecl *ImpDecl =
2070 ObjCImplementations[IFace->getIdentifier()])
2071 Setter = ImpDecl->getInstanceMethod(SetterSel);
2072 }
2073 // Look through local category implementations associated with the class.
2074 if (!Setter) {
2075 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2076 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2077 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2078 }
2079 }
2080
2081 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2082 return ExprError();
2083
2084 if (Getter || Setter) {
2085 QualType PType;
2086
2087 if (Getter)
2088 PType = Getter->getResultType();
2089 else {
2090 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2091 E = Setter->param_end(); PI != E; ++PI)
2092 PType = (*PI)->getType();
2093 }
2094 // FIXME: we must check that the setter has property type.
2095 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2096 Setter, MemberLoc, BaseExpr));
2097 }
2098 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2099 << &Member << BaseType);
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002100 }
2101 }
2102
Chris Lattnera57cf472008-07-21 04:28:12 +00002103 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002104 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002105 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2106 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002107 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002108 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002109 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002110 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002111
2112 return ExprError(Diag(MemberLoc,
2113 diag::err_typecheck_member_reference_struct_union)
2114 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002115}
2116
Douglas Gregor3257fb52008-12-22 05:46:06 +00002117/// ConvertArgumentsForCall - Converts the arguments specified in
2118/// Args/NumArgs to the parameter types of the function FDecl with
2119/// function prototype Proto. Call is the call expression itself, and
2120/// Fn is the function expression. For a C++ member function, this
2121/// routine does not attempt to convert the object argument. Returns
2122/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002123bool
2124Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002125 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002126 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002127 Expr **Args, unsigned NumArgs,
2128 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002129 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002130 // assignment, to the types of the corresponding parameter, ...
2131 unsigned NumArgsInProto = Proto->getNumArgs();
2132 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002133 bool Invalid = false;
2134
Douglas Gregor3257fb52008-12-22 05:46:06 +00002135 // If too few arguments are available (and we don't have default
2136 // arguments for the remaining parameters), don't make the call.
2137 if (NumArgs < NumArgsInProto) {
2138 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2139 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2140 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2141 // Use default arguments for missing arguments
2142 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002143 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002144 }
2145
2146 // If too many are passed and not variadic, error on the extras and drop
2147 // them.
2148 if (NumArgs > NumArgsInProto) {
2149 if (!Proto->isVariadic()) {
2150 Diag(Args[NumArgsInProto]->getLocStart(),
2151 diag::err_typecheck_call_too_many_args)
2152 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2153 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2154 Args[NumArgs-1]->getLocEnd());
2155 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002156 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002157 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002158 }
2159 NumArgsToCheck = NumArgsInProto;
2160 }
Mike Stump9afab102009-02-19 03:04:26 +00002161
Douglas Gregor3257fb52008-12-22 05:46:06 +00002162 // Continue to check argument types (even if we have too few/many args).
2163 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2164 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002165
Douglas Gregor3257fb52008-12-22 05:46:06 +00002166 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002167 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002168 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002169
Eli Friedman83dec9e2009-03-22 22:00:50 +00002170 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2171 ProtoArgType,
2172 diag::err_call_incomplete_argument,
2173 Arg->getSourceRange()))
2174 return true;
2175
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002176 // Pass the argument.
2177 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2178 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002179 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002180 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002181 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002182 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002183
Douglas Gregor3257fb52008-12-22 05:46:06 +00002184 Call->setArg(i, Arg);
2185 }
Mike Stump9afab102009-02-19 03:04:26 +00002186
Douglas Gregor3257fb52008-12-22 05:46:06 +00002187 // If this is a variadic call, handle args passed through "...".
2188 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002189 VariadicCallType CallType = VariadicFunction;
2190 if (Fn->getType()->isBlockPointerType())
2191 CallType = VariadicBlock; // Block
2192 else if (isa<MemberExpr>(Fn))
2193 CallType = VariadicMethod;
2194
Douglas Gregor3257fb52008-12-22 05:46:06 +00002195 // Promote the arguments (C99 6.5.2.2p7).
2196 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2197 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002198 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002199 Call->setArg(i, Arg);
2200 }
2201 }
2202
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002203 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002204}
2205
Steve Naroff87d58b42007-09-16 03:34:24 +00002206/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002207/// This provides the location of the left/right parens and a list of comma
2208/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002209Action::OwningExprResult
2210Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2211 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002212 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002213 unsigned NumArgs = args.size();
2214 Expr *Fn = static_cast<Expr *>(fn.release());
2215 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002216 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002217 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002218 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002219
Douglas Gregor3257fb52008-12-22 05:46:06 +00002220 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002221 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002222 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002223 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2224 bool Dependent = false;
2225 if (Fn->isTypeDependent())
2226 Dependent = true;
2227 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2228 Dependent = true;
2229
2230 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002231 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002232 Context.DependentTy, RParenLoc));
2233
2234 // Determine whether this is a call to an object (C++ [over.call.object]).
2235 if (Fn->getType()->isRecordType())
2236 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2237 CommaLocs, RParenLoc));
2238
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002239 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002240 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2241 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2242 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002243 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2244 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002245 }
2246
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002247 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002248 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002249 Expr *FnExpr = Fn;
2250 bool ADL = true;
2251 while (true) {
2252 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2253 FnExpr = IcExpr->getSubExpr();
2254 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002255 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002256 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002257 ADL = false;
2258 FnExpr = PExpr->getSubExpr();
2259 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002260 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002261 == UnaryOperator::AddrOf) {
2262 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002263 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2264 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2265 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2266 break;
Mike Stump9afab102009-02-19 03:04:26 +00002267 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002268 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2269 UnqualifiedName = DepName->getName();
2270 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002271 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002272 // Any kind of name that does not refer to a declaration (or
2273 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2274 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002275 break;
2276 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002277 }
Mike Stump9afab102009-02-19 03:04:26 +00002278
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002279 OverloadedFunctionDecl *Ovl = 0;
2280 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002281 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002282 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2283 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002284
Douglas Gregorfcb19192009-02-11 23:02:49 +00002285 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002286 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002287 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002288 ADL = false;
2289
Douglas Gregorfcb19192009-02-11 23:02:49 +00002290 // We don't perform ADL in C.
2291 if (!getLangOptions().CPlusPlus)
2292 ADL = false;
2293
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002294 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002295 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2296 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002297 NumArgs, CommaLocs, RParenLoc, ADL);
2298 if (!FDecl)
2299 return ExprError();
2300
2301 // Update Fn to refer to the actual function selected.
2302 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002303 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002304 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregor7e508262009-03-19 03:51:16 +00002305 NewFn = QualifiedDeclRefExpr::Create(Context, FDecl, FDecl->getType(),
2306 QDRExpr->getLocation(),
2307 false, false,
2308 QDRExpr->getQualifierRange(),
2309 QDRExpr->begin(),
2310 QDRExpr->size());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002311 else
Mike Stump9afab102009-02-19 03:04:26 +00002312 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002313 Fn->getSourceRange().getBegin());
2314 Fn->Destroy(Context);
2315 Fn = NewFn;
2316 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002317 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002318
2319 // Promote the function operand.
2320 UsualUnaryConversions(Fn);
2321
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002322 // Make the call expr early, before semantic checks. This guarantees cleanup
2323 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002324 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2325 Args, NumArgs,
2326 Context.BoolTy,
2327 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002328
Steve Naroffd6163f32008-09-05 22:11:13 +00002329 const FunctionType *FuncT;
2330 if (!Fn->getType()->isBlockPointerType()) {
2331 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2332 // have type pointer to function".
2333 const PointerType *PT = Fn->getType()->getAsPointerType();
2334 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002335 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2336 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002337 FuncT = PT->getPointeeType()->getAsFunctionType();
2338 } else { // This is a block call.
2339 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2340 getAsFunctionType();
2341 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002342 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002343 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2344 << Fn->getType() << Fn->getSourceRange());
2345
Eli Friedman83dec9e2009-03-22 22:00:50 +00002346 // Check for a valid return type
2347 if (!FuncT->getResultType()->isVoidType() &&
2348 RequireCompleteType(Fn->getSourceRange().getBegin(),
2349 FuncT->getResultType(),
2350 diag::err_call_incomplete_return,
2351 TheCall->getSourceRange()))
2352 return ExprError();
2353
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002354 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002355 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002356
Douglas Gregor4fa58902009-02-26 23:50:07 +00002357 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002358 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002359 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002360 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002361 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002362 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002363
Steve Naroffdb65e052007-08-28 23:30:39 +00002364 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002365 for (unsigned i = 0; i != NumArgs; i++) {
2366 Expr *Arg = Args[i];
2367 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002368 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2369 Arg->getType(),
2370 diag::err_call_incomplete_argument,
2371 Arg->getSourceRange()))
2372 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002373 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002374 }
Chris Lattner4b009652007-07-25 00:24:17 +00002375 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002376
Douglas Gregor3257fb52008-12-22 05:46:06 +00002377 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2378 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002379 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2380 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002381
Chris Lattner2e64c072007-08-10 20:18:51 +00002382 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002383 if (FDecl)
2384 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002385
Sebastian Redl8b769972009-01-19 00:08:26 +00002386 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002387}
2388
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002389Action::OwningExprResult
2390Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2391 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002392 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002393 QualType literalType = QualType::getFromOpaquePtr(Ty);
2394 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002395 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002396 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002397
Eli Friedman8c2173d2008-05-20 05:22:08 +00002398 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002399 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002400 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2401 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregorc84d8932009-03-09 16:13:40 +00002402 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002403 diag::err_typecheck_decl_incomplete_type,
2404 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002405 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002406
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002407 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002408 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002409 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002410
Chris Lattnere5cb5862008-12-04 23:50:19 +00002411 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002412 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002413 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002414 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002415 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002416 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002417 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002418 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002419}
2420
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002421Action::OwningExprResult
2422Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002423 SourceLocation RBraceLoc) {
2424 unsigned NumInit = initlist.size();
2425 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002426
Steve Naroff0acc9c92007-09-15 18:49:24 +00002427 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002428 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002429
Mike Stump9afab102009-02-19 03:04:26 +00002430 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002431 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002432 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002433 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002434}
2435
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002436/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002437bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002438 UsualUnaryConversions(castExpr);
2439
2440 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2441 // type needs to be scalar.
2442 if (castType->isVoidType()) {
2443 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002444 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2445 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002446 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002447 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2448 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2449 (castType->isStructureType() || castType->isUnionType())) {
2450 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002451 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002452 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2453 << castType << castExpr->getSourceRange();
2454 } else if (castType->isUnionType()) {
2455 // GCC cast to union extension
2456 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2457 RecordDecl::field_iterator Field, FieldEnd;
2458 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2459 Field != FieldEnd; ++Field) {
2460 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2461 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2462 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2463 << castExpr->getSourceRange();
2464 break;
2465 }
2466 }
2467 if (Field == FieldEnd)
2468 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2469 << castExpr->getType() << castExpr->getSourceRange();
2470 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002471 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002472 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002473 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002474 }
Mike Stump9afab102009-02-19 03:04:26 +00002475 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002476 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002477 return Diag(castExpr->getLocStart(),
2478 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002479 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002480 } else if (castExpr->getType()->isVectorType()) {
2481 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2482 return true;
2483 } else if (castType->isVectorType()) {
2484 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2485 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002486 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Chris Lattner2e9eb042009-03-05 23:09:00 +00002487 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002488 }
2489 return false;
2490}
2491
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002492bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002493 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002494
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002495 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002496 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002497 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002498 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002499 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002500 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002501 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002502 } else
2503 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002504 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002505 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002506
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002507 return false;
2508}
2509
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002510Action::OwningExprResult
2511Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2512 SourceLocation RParenLoc, ExprArg Op) {
2513 assert((Ty != 0) && (Op.get() != 0) &&
2514 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002515
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002516 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002517 QualType castType = QualType::getFromOpaquePtr(Ty);
2518
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002519 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002520 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002521 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002522 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002523}
2524
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002525/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2526/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002527/// C99 6.5.15
2528QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2529 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002530 UsualUnaryConversions(Cond);
2531 UsualUnaryConversions(LHS);
2532 UsualUnaryConversions(RHS);
2533 QualType CondTy = Cond->getType();
2534 QualType LHSTy = LHS->getType();
2535 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002536
2537 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002538 if (!Cond->isTypeDependent()) {
2539 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2540 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2541 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002542 return QualType();
2543 }
Chris Lattner4b009652007-07-25 00:24:17 +00002544 }
Mike Stump9afab102009-02-19 03:04:26 +00002545
Chris Lattner992ae932008-01-06 22:42:25 +00002546 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002547 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002548 return Context.DependentTy;
2549
Chris Lattner992ae932008-01-06 22:42:25 +00002550 // If both operands have arithmetic type, do the usual arithmetic conversions
2551 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002552 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2553 UsualArithmeticConversions(LHS, RHS);
2554 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002555 }
Mike Stump9afab102009-02-19 03:04:26 +00002556
Chris Lattner992ae932008-01-06 22:42:25 +00002557 // If both operands are the same structure or union type, the result is that
2558 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002559 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2560 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002561 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002562 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002563 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002564 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00002565 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00002566 }
Mike Stump9afab102009-02-19 03:04:26 +00002567
Chris Lattner992ae932008-01-06 22:42:25 +00002568 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002569 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002570 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2571 if (!LHSTy->isVoidType())
2572 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2573 << RHS->getSourceRange();
2574 if (!RHSTy->isVoidType())
2575 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2576 << LHS->getSourceRange();
2577 ImpCastExprToType(LHS, Context.VoidTy);
2578 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002579 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002580 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002581 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2582 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002583 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2584 Context.isObjCObjectPointerType(LHSTy)) &&
2585 RHS->isNullPointerConstant(Context)) {
2586 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2587 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002588 }
Chris Lattnere2897262009-02-18 04:28:32 +00002589 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2590 Context.isObjCObjectPointerType(RHSTy)) &&
2591 LHS->isNullPointerConstant(Context)) {
2592 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2593 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002594 }
Mike Stump9afab102009-02-19 03:04:26 +00002595
Chris Lattner0ac51632008-01-06 22:50:31 +00002596 // Handle the case where both operands are pointers before we handle null
2597 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002598 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2599 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002600 // get the "pointed to" types
2601 QualType lhptee = LHSPT->getPointeeType();
2602 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002603
Chris Lattner71225142007-07-31 21:27:01 +00002604 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2605 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002606 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002607 // Figure out necessary qualifiers (C99 6.5.15p6)
2608 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002609 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002610 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2611 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002612 return destType;
2613 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002614 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002615 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002616 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002617 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2618 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002619 return destType;
2620 }
Chris Lattner4b009652007-07-25 00:24:17 +00002621
Chris Lattner9c039b52009-02-18 04:38:20 +00002622 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002623 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002624 return LHSTy;
2625 }
Mike Stump9afab102009-02-19 03:04:26 +00002626
Chris Lattnere2897262009-02-18 04:28:32 +00002627 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002628
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002629 // If either type is an Objective-C object type then check
2630 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002631 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002632 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002633 // If both operands are interfaces and either operand can be
2634 // assigned to the other, use that type as the composite
2635 // type. This allows
2636 // xxx ? (A*) a : (B*) b
2637 // where B is a subclass of A.
2638 //
2639 // Additionally, as for assignment, if either type is 'id'
2640 // allow silent coercion. Finally, if the types are
2641 // incompatible then make sure to use 'id' as the composite
2642 // type so the result is acceptable for sending messages to.
2643
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002644 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002645 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002646 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2647 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2648 if (LHSIface && RHSIface &&
2649 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002650 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002651 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002652 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002653 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002654 } else if (Context.isObjCIdStructType(lhptee) ||
2655 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002656 compositeType = Context.getObjCIdType();
2657 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002658 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002659 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002660 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002661 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002662 ImpCastExprToType(LHS, incompatTy);
2663 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002664 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002665 }
Mike Stump9afab102009-02-19 03:04:26 +00002666 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002667 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002668 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2669 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002670 // In this situation, we assume void* type. No especially good
2671 // reason, but this is what gcc does, and we do have to pick
2672 // to get a consistent AST.
2673 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002674 ImpCastExprToType(LHS, incompatTy);
2675 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002676 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002677 }
2678 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002679 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2680 // differently qualified versions of compatible types, the result type is
2681 // a pointer to an appropriately qualified version of the *composite*
2682 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002683 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002684 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002685 ImpCastExprToType(LHS, compositeType);
2686 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002687 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002688 }
Chris Lattner4b009652007-07-25 00:24:17 +00002689 }
Mike Stump9afab102009-02-19 03:04:26 +00002690
Chris Lattner9c039b52009-02-18 04:38:20 +00002691 // Selection between block pointer types is ok as long as they are the same.
2692 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2693 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2694 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002695
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002696 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2697 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002698 // id with statically typed objects).
2699 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002700 // GCC allows qualified id and any Objective-C type to devolve to
2701 // id. Currently localizing to here until clear this should be
2702 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002703 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002704 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002705 Context.isObjCObjectPointerType(RHSTy)) ||
2706 (RHSTy->isObjCQualifiedIdType() &&
2707 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002708 // FIXME: This is not the correct composite type. This only
2709 // happens to work because id can more or less be used anywhere,
2710 // however this may change the type of method sends.
2711 // FIXME: gcc adds some type-checking of the arguments and emits
2712 // (confusing) incompatible comparison warnings in some
2713 // cases. Investigate.
2714 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002715 ImpCastExprToType(LHS, compositeType);
2716 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002717 return compositeType;
2718 }
2719 }
2720
Chris Lattner992ae932008-01-06 22:42:25 +00002721 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002722 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2723 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002724 return QualType();
2725}
2726
Steve Naroff87d58b42007-09-16 03:34:24 +00002727/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002728/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002729Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2730 SourceLocation ColonLoc,
2731 ExprArg Cond, ExprArg LHS,
2732 ExprArg RHS) {
2733 Expr *CondExpr = (Expr *) Cond.get();
2734 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002735
2736 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2737 // was the condition.
2738 bool isLHSNull = LHSExpr == 0;
2739 if (isLHSNull)
2740 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002741
2742 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002743 RHSExpr, QuestionLoc);
2744 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002745 return ExprError();
2746
2747 Cond.release();
2748 LHS.release();
2749 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002750 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002751 isLHSNull ? 0 : LHSExpr,
2752 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002753}
2754
Chris Lattner4b009652007-07-25 00:24:17 +00002755
2756// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002757// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002758// routine is it effectively iqnores the qualifiers on the top level pointee.
2759// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2760// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002761Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002762Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2763 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002764
Chris Lattner4b009652007-07-25 00:24:17 +00002765 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002766 lhptee = lhsType->getAsPointerType()->getPointeeType();
2767 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002768
Chris Lattner4b009652007-07-25 00:24:17 +00002769 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002770 lhptee = Context.getCanonicalType(lhptee);
2771 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002772
Chris Lattner005ed752008-01-04 18:04:52 +00002773 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002774
2775 // C99 6.5.16.1p1: This following citation is common to constraints
2776 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2777 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002778 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002779 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002780 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002781
Mike Stump9afab102009-02-19 03:04:26 +00002782 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2783 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002784 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002785 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002786 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002787 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002788
Chris Lattner4ca3d772008-01-03 22:56:36 +00002789 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002790 assert(rhptee->isFunctionType());
2791 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002792 }
Mike Stump9afab102009-02-19 03:04:26 +00002793
Chris Lattner4ca3d772008-01-03 22:56:36 +00002794 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002795 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002796 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002797
2798 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002799 assert(lhptee->isFunctionType());
2800 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002801 }
Mike Stump9afab102009-02-19 03:04:26 +00002802 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002803 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00002804 lhptee = lhptee.getUnqualifiedType();
2805 rhptee = rhptee.getUnqualifiedType();
2806 if (!Context.typesAreCompatible(lhptee, rhptee)) {
2807 // Check if the pointee types are compatible ignoring the sign.
2808 // We explicitly check for char so that we catch "char" vs
2809 // "unsigned char" on systems where "char" is unsigned.
2810 if (lhptee->isCharType()) {
2811 lhptee = Context.UnsignedCharTy;
2812 } else if (lhptee->isSignedIntegerType()) {
2813 lhptee = Context.getCorrespondingUnsignedType(lhptee);
2814 }
2815 if (rhptee->isCharType()) {
2816 rhptee = Context.UnsignedCharTy;
2817 } else if (rhptee->isSignedIntegerType()) {
2818 rhptee = Context.getCorrespondingUnsignedType(rhptee);
2819 }
2820 if (lhptee == rhptee) {
2821 // Types are compatible ignoring the sign. Qualifier incompatibility
2822 // takes priority over sign incompatibility because the sign
2823 // warning can be disabled.
2824 if (ConvTy != Compatible)
2825 return ConvTy;
2826 return IncompatiblePointerSign;
2827 }
2828 // General pointer incompatibility takes priority over qualifiers.
2829 return IncompatiblePointer;
2830 }
Chris Lattner005ed752008-01-04 18:04:52 +00002831 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002832}
2833
Steve Naroff3454b6c2008-09-04 15:10:53 +00002834/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2835/// block pointer types are compatible or whether a block and normal pointer
2836/// are compatible. It is more restrict than comparing two function pointer
2837// types.
Mike Stump9afab102009-02-19 03:04:26 +00002838Sema::AssignConvertType
2839Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002840 QualType rhsType) {
2841 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002842
Steve Naroff3454b6c2008-09-04 15:10:53 +00002843 // get the "pointed to" type (ignoring qualifiers at the top level)
2844 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002845 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2846
Steve Naroff3454b6c2008-09-04 15:10:53 +00002847 // make sure we operate on the canonical type
2848 lhptee = Context.getCanonicalType(lhptee);
2849 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002850
Steve Naroff3454b6c2008-09-04 15:10:53 +00002851 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002852
Steve Naroff3454b6c2008-09-04 15:10:53 +00002853 // For blocks we enforce that qualifiers are identical.
2854 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2855 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002856
Steve Naroff3454b6c2008-09-04 15:10:53 +00002857 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002858 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002859 return ConvTy;
2860}
2861
Mike Stump9afab102009-02-19 03:04:26 +00002862/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2863/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002864/// pointers. Here are some objectionable examples that GCC considers warnings:
2865///
2866/// int a, *pint;
2867/// short *pshort;
2868/// struct foo *pfoo;
2869///
2870/// pint = pshort; // warning: assignment from incompatible pointer type
2871/// a = pint; // warning: assignment makes integer from pointer without a cast
2872/// pint = a; // warning: assignment makes pointer from integer without a cast
2873/// pint = pfoo; // warning: assignment from incompatible pointer type
2874///
2875/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002876/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002877///
Chris Lattner005ed752008-01-04 18:04:52 +00002878Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002879Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002880 // Get canonical types. We're not formatting these types, just comparing
2881 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002882 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2883 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002884
2885 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002886 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002887
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002888 // If the left-hand side is a reference type, then we are in a
2889 // (rare!) case where we've allowed the use of references in C,
2890 // e.g., as a parameter type in a built-in function. In this case,
2891 // just make sure that the type referenced is compatible with the
2892 // right-hand side type. The caller is responsible for adjusting
2893 // lhsType so that the resulting expression does not have reference
2894 // type.
2895 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2896 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002897 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002898 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002899 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002900
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002901 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2902 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002903 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002904 // Relax integer conversions like we do for pointers below.
2905 if (rhsType->isIntegerType())
2906 return IntToPointer;
2907 if (lhsType->isIntegerType())
2908 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002909 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002910 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002911
Nate Begemanc5f0f652008-07-14 18:02:46 +00002912 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002913 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002914 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2915 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002916 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002917
Nate Begemanc5f0f652008-07-14 18:02:46 +00002918 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002919 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002920 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002921 if (getLangOptions().LaxVectorConversions &&
2922 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002923 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002924 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002925 }
2926 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002927 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002928
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002929 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002930 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002931
Chris Lattner390564e2008-04-07 06:49:41 +00002932 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002933 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002934 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002935
Chris Lattner390564e2008-04-07 06:49:41 +00002936 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002937 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002938
Steve Naroffa982c712008-09-29 18:10:17 +00002939 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002940 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002941 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002942
2943 // Treat block pointers as objects.
2944 if (getLangOptions().ObjC1 &&
2945 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2946 return Compatible;
2947 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002948 return Incompatible;
2949 }
2950
2951 if (isa<BlockPointerType>(lhsType)) {
2952 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002953 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002954
Steve Naroffa982c712008-09-29 18:10:17 +00002955 // Treat block pointers as objects.
2956 if (getLangOptions().ObjC1 &&
2957 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2958 return Compatible;
2959
Steve Naroff3454b6c2008-09-04 15:10:53 +00002960 if (rhsType->isBlockPointerType())
2961 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002962
Steve Naroff3454b6c2008-09-04 15:10:53 +00002963 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2964 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002965 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002966 }
Chris Lattner1853da22008-01-04 23:18:45 +00002967 return Incompatible;
2968 }
2969
Chris Lattner390564e2008-04-07 06:49:41 +00002970 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002971 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002972 if (lhsType == Context.BoolTy)
2973 return Compatible;
2974
2975 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002976 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002977
Mike Stump9afab102009-02-19 03:04:26 +00002978 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002979 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002980
2981 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002982 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002983 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002984 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002985 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002986
Chris Lattner1853da22008-01-04 23:18:45 +00002987 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002988 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002989 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002990 }
2991 return Incompatible;
2992}
2993
Chris Lattner005ed752008-01-04 18:04:52 +00002994Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002995Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002996 if (getLangOptions().CPlusPlus) {
2997 if (!lhsType->isRecordType()) {
2998 // C++ 5.17p3: If the left operand is not of class type, the
2999 // expression is implicitly converted (C++ 4) to the
3000 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003001 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3002 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003003 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00003004 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003005 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003006 }
3007
3008 // FIXME: Currently, we fall through and treat C++ classes like C
3009 // structures.
3010 }
3011
Steve Naroffcdee22d2007-11-27 17:58:44 +00003012 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3013 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003014 if ((lhsType->isPointerType() ||
3015 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003016 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003017 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003018 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003019 return Compatible;
3020 }
Mike Stump9afab102009-02-19 03:04:26 +00003021
Chris Lattner5f505bf2007-10-16 02:55:40 +00003022 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003023 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003024 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003025 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003026 //
Mike Stump9afab102009-02-19 03:04:26 +00003027 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003028 if (!lhsType->isReferenceType())
3029 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003030
Chris Lattner005ed752008-01-04 18:04:52 +00003031 Sema::AssignConvertType result =
3032 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003033
Steve Naroff0f32f432007-08-24 22:33:52 +00003034 // C99 6.5.16.1p2: The value of the right operand is converted to the
3035 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003036 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3037 // so that we can use references in built-in functions even in C.
3038 // The getNonReferenceType() call makes sure that the resulting expression
3039 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00003040 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003041 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003042 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003043}
3044
Chris Lattner005ed752008-01-04 18:04:52 +00003045Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003046Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
3047 return CheckAssignmentConstraints(lhsType, rhsType);
3048}
3049
Chris Lattner1eafdea2008-11-18 01:30:42 +00003050QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003051 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003052 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003053 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003054 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003055}
3056
Mike Stump9afab102009-02-19 03:04:26 +00003057inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003058 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003059 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003060 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003061 QualType lhsType =
3062 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3063 QualType rhsType =
3064 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003065
Nate Begemanc5f0f652008-07-14 18:02:46 +00003066 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003067 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003068 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003069
Nate Begemanc5f0f652008-07-14 18:02:46 +00003070 // Handle the case of a vector & extvector type of the same size and element
3071 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003072 if (getLangOptions().LaxVectorConversions) {
3073 // FIXME: Should we warn here?
3074 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003075 if (const VectorType *RV = rhsType->getAsVectorType())
3076 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003077 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003078 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003079 }
3080 }
3081 }
Mike Stump9afab102009-02-19 03:04:26 +00003082
Nate Begemanc5f0f652008-07-14 18:02:46 +00003083 // If the lhs is an extended vector and the rhs is a scalar of the same type
3084 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003085 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003086 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00003087
3088 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003089 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3090 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003091 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003092 return lhsType;
3093 }
3094 }
3095
Nate Begemanc5f0f652008-07-14 18:02:46 +00003096 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00003097 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003098 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003099 QualType eltType = V->getElementType();
3100
Mike Stump9afab102009-02-19 03:04:26 +00003101 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003102 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3103 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003104 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003105 return rhsType;
3106 }
3107 }
3108
Chris Lattner4b009652007-07-25 00:24:17 +00003109 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003110 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003111 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003112 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003113 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003114}
3115
Chris Lattner4b009652007-07-25 00:24:17 +00003116inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003117 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003118{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003119 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003120 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003121
Steve Naroff8f708362007-08-24 19:07:16 +00003122 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003123
Chris Lattner4b009652007-07-25 00:24:17 +00003124 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003125 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003126 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003127}
3128
3129inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003130 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003131{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003132 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3133 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3134 return CheckVectorOperands(Loc, lex, rex);
3135 return InvalidOperands(Loc, lex, rex);
3136 }
Chris Lattner4b009652007-07-25 00:24:17 +00003137
Steve Naroff8f708362007-08-24 19:07:16 +00003138 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003139
Chris Lattner4b009652007-07-25 00:24:17 +00003140 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003141 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003142 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003143}
3144
3145inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00003146 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003147{
3148 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003149 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003150
Steve Naroff8f708362007-08-24 19:07:16 +00003151 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003152
Chris Lattner4b009652007-07-25 00:24:17 +00003153 // handle the common case first (both operands are arithmetic).
3154 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003155 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00003156
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003157 // Put any potential pointer into PExp
3158 Expr* PExp = lex, *IExp = rex;
3159 if (IExp->getType()->isPointerType())
3160 std::swap(PExp, IExp);
3161
3162 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3163 if (IExp->getType()->isIntegerType()) {
3164 // Check for arithmetic on pointers to incomplete types
Douglas Gregor05e28f62009-03-24 19:52:54 +00003165 if (PTy->getPointeeType()->isVoidType()) {
3166 if (getLangOptions().CPlusPlus) {
3167 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003168 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003169 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003170 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003171
3172 // GNU extension: arithmetic on pointer to void
3173 Diag(Loc, diag::ext_gnu_void_ptr)
3174 << lex->getSourceRange() << rex->getSourceRange();
3175 } else if (PTy->getPointeeType()->isFunctionType()) {
3176 if (getLangOptions().CPlusPlus) {
3177 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3178 << lex->getType() << lex->getSourceRange();
3179 return QualType();
3180 }
3181
3182 // GNU extension: arithmetic on pointer to function
3183 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3184 << lex->getType() << lex->getSourceRange();
3185 } else if (!PTy->isDependentType() &&
3186 RequireCompleteType(Loc, PTy->getPointeeType(),
3187 diag::err_typecheck_arithmetic_incomplete_type,
3188 lex->getSourceRange(), SourceRange(),
3189 lex->getType()))
3190 return QualType();
3191
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003192 return PExp->getType();
3193 }
3194 }
3195
Chris Lattner1eafdea2008-11-18 01:30:42 +00003196 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003197}
3198
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003199// C99 6.5.6
3200QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003201 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00003202 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003203 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003204
Steve Naroff8f708362007-08-24 19:07:16 +00003205 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003206
Chris Lattnerf6da2912007-12-09 21:53:25 +00003207 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003208
Chris Lattnerf6da2912007-12-09 21:53:25 +00003209 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00003210 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003211 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00003212
Chris Lattnerf6da2912007-12-09 21:53:25 +00003213 // Either ptr - int or ptr - ptr.
3214 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003215 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003216
Douglas Gregor05e28f62009-03-24 19:52:54 +00003217 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003218
Douglas Gregor05e28f62009-03-24 19:52:54 +00003219 bool ComplainAboutVoid = false;
3220 Expr *ComplainAboutFunc = 0;
3221 if (lpointee->isVoidType()) {
3222 if (getLangOptions().CPlusPlus) {
3223 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3224 << lex->getSourceRange() << rex->getSourceRange();
3225 return QualType();
3226 }
3227
3228 // GNU C extension: arithmetic on pointer to void
3229 ComplainAboutVoid = true;
3230 } else if (lpointee->isFunctionType()) {
3231 if (getLangOptions().CPlusPlus) {
3232 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003233 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003234 return QualType();
3235 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003236
3237 // GNU C extension: arithmetic on pointer to function
3238 ComplainAboutFunc = lex;
3239 } else if (!lpointee->isDependentType() &&
3240 RequireCompleteType(Loc, lpointee,
3241 diag::err_typecheck_sub_ptr_object,
3242 lex->getSourceRange(),
3243 SourceRange(),
3244 lex->getType()))
3245 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003246
3247 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00003248 if (rex->getType()->isIntegerType()) {
3249 if (ComplainAboutVoid)
3250 Diag(Loc, diag::ext_gnu_void_ptr)
3251 << lex->getSourceRange() << rex->getSourceRange();
3252 if (ComplainAboutFunc)
3253 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3254 << ComplainAboutFunc->getType()
3255 << ComplainAboutFunc->getSourceRange();
3256
Chris Lattnerf6da2912007-12-09 21:53:25 +00003257 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00003258 }
Mike Stump9afab102009-02-19 03:04:26 +00003259
Chris Lattnerf6da2912007-12-09 21:53:25 +00003260 // Handle pointer-pointer subtractions.
3261 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003262 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003263
Douglas Gregor05e28f62009-03-24 19:52:54 +00003264 // RHS must be a completely-type object type.
3265 // Handle the GNU void* extension.
3266 if (rpointee->isVoidType()) {
3267 if (getLangOptions().CPlusPlus) {
3268 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3269 << lex->getSourceRange() << rex->getSourceRange();
3270 return QualType();
3271 }
Mike Stump9afab102009-02-19 03:04:26 +00003272
Douglas Gregor05e28f62009-03-24 19:52:54 +00003273 ComplainAboutVoid = true;
3274 } else if (rpointee->isFunctionType()) {
3275 if (getLangOptions().CPlusPlus) {
3276 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003277 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003278 return QualType();
3279 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003280
3281 // GNU extension: arithmetic on pointer to function
3282 if (!ComplainAboutFunc)
3283 ComplainAboutFunc = rex;
3284 } else if (!rpointee->isDependentType() &&
3285 RequireCompleteType(Loc, rpointee,
3286 diag::err_typecheck_sub_ptr_object,
3287 rex->getSourceRange(),
3288 SourceRange(),
3289 rex->getType()))
3290 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003291
Chris Lattnerf6da2912007-12-09 21:53:25 +00003292 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003293 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003294 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003295 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003296 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003297 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003298 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003299 return QualType();
3300 }
Mike Stump9afab102009-02-19 03:04:26 +00003301
Douglas Gregor05e28f62009-03-24 19:52:54 +00003302 if (ComplainAboutVoid)
3303 Diag(Loc, diag::ext_gnu_void_ptr)
3304 << lex->getSourceRange() << rex->getSourceRange();
3305 if (ComplainAboutFunc)
3306 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3307 << ComplainAboutFunc->getType()
3308 << ComplainAboutFunc->getSourceRange();
3309
Chris Lattnerf6da2912007-12-09 21:53:25 +00003310 return Context.getPointerDiffType();
3311 }
3312 }
Mike Stump9afab102009-02-19 03:04:26 +00003313
Chris Lattner1eafdea2008-11-18 01:30:42 +00003314 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003315}
3316
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003317// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003318QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003319 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003320 // C99 6.5.7p2: Each of the operands shall have integer type.
3321 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003322 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003323
Chris Lattner2c8bff72007-12-12 05:47:28 +00003324 // Shifts don't perform usual arithmetic conversions, they just do integer
3325 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003326 if (!isCompAssign)
3327 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003328 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003329
Chris Lattner2c8bff72007-12-12 05:47:28 +00003330 // "The type of the result is that of the promoted left operand."
3331 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003332}
3333
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003334// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003335QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003336 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003337 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003338 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003339
Chris Lattner254f3bc2007-08-26 01:18:55 +00003340 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003341 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3342 UsualArithmeticConversions(lex, rex);
3343 else {
3344 UsualUnaryConversions(lex);
3345 UsualUnaryConversions(rex);
3346 }
Chris Lattner4b009652007-07-25 00:24:17 +00003347 QualType lType = lex->getType();
3348 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003349
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003350 if (!lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003351 // For non-floating point types, check for self-comparisons of the form
3352 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3353 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00003354 // NOTE: Don't warn about comparisons of enum constants. These can arise
3355 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00003356 Expr *LHSStripped = lex->IgnoreParens();
3357 Expr *RHSStripped = rex->IgnoreParens();
3358 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3359 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00003360 if (DRL->getDecl() == DRR->getDecl() &&
3361 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00003362 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003363
3364 if (isa<CastExpr>(LHSStripped))
3365 LHSStripped = LHSStripped->IgnoreParenCasts();
3366 if (isa<CastExpr>(RHSStripped))
3367 RHSStripped = RHSStripped->IgnoreParenCasts();
3368
3369 // Warn about comparisons against a string constant (unless the other
3370 // operand is null), the user probably wants strcmp.
3371 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
3372 !RHSStripped->isNullPointerConstant(Context))
3373 Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange();
3374 else if ((isa<StringLiteral>(RHSStripped) ||
3375 isa<ObjCEncodeExpr>(RHSStripped)) &&
3376 !LHSStripped->isNullPointerConstant(Context))
3377 Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange();
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003378 }
Mike Stump9afab102009-02-19 03:04:26 +00003379
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003380 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003381 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003382
Chris Lattner254f3bc2007-08-26 01:18:55 +00003383 if (isRelational) {
3384 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003385 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003386 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003387 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003388 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003389 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003390 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003391 }
Mike Stump9afab102009-02-19 03:04:26 +00003392
Chris Lattner254f3bc2007-08-26 01:18:55 +00003393 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003394 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003395 }
Mike Stump9afab102009-02-19 03:04:26 +00003396
Chris Lattner22be8422007-08-26 01:10:14 +00003397 bool LHSIsNull = lex->isNullPointerConstant(Context);
3398 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003399
Chris Lattner254f3bc2007-08-26 01:18:55 +00003400 // All of the following pointer related warnings are GCC extensions, except
3401 // when handling null pointer constants. One day, we can consider making them
3402 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003403 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003404 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003405 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003406 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003407 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003408
Steve Naroff3b435622007-11-13 14:57:38 +00003409 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003410 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3411 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003412 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003413 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003414 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003415 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003416 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003417 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003418 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003419 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003420 // Handle block pointer types.
3421 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3422 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3423 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003424
Steve Naroff3454b6c2008-09-04 15:10:53 +00003425 if (!LHSIsNull && !RHSIsNull &&
3426 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003427 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003428 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003429 }
3430 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003431 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003432 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003433 // Allow block pointers to be compared with null pointer constants.
3434 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3435 (lType->isPointerType() && rType->isBlockPointerType())) {
3436 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003437 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003438 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003439 }
3440 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003441 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003442 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003443
Steve Naroff936c4362008-06-03 14:04:54 +00003444 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003445 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003446 const PointerType *LPT = lType->getAsPointerType();
3447 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003448 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003449 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003450 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003451 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003452
Steve Naroff030fcda2008-11-17 19:49:16 +00003453 if (!LPtrToVoid && !RPtrToVoid &&
3454 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003455 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003456 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003457 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003458 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003459 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003460 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003461 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003462 }
Steve Naroff936c4362008-06-03 14:04:54 +00003463 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3464 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003465 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003466 } else {
3467 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003468 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003469 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003470 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003471 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003472 }
Steve Naroff936c4362008-06-03 14:04:54 +00003473 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003474 }
Mike Stump9afab102009-02-19 03:04:26 +00003475 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003476 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003477 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003478 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003479 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003480 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003481 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003482 }
Mike Stump9afab102009-02-19 03:04:26 +00003483 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003484 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003485 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003486 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003487 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003488 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003489 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003490 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003491 // Handle block pointers.
3492 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3493 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003494 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003495 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003496 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003497 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003498 }
3499 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3500 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003501 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003502 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003503 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003504 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003505 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003506 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003507}
3508
Nate Begemanc5f0f652008-07-14 18:02:46 +00003509/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003510/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003511/// like a scalar comparison, a vector comparison produces a vector of integer
3512/// types.
3513QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003514 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003515 bool isRelational) {
3516 // Check to make sure we're operating on vectors of the same type and width,
3517 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003518 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003519 if (vType.isNull())
3520 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003521
Nate Begemanc5f0f652008-07-14 18:02:46 +00003522 QualType lType = lex->getType();
3523 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003524
Nate Begemanc5f0f652008-07-14 18:02:46 +00003525 // For non-floating point types, check for self-comparisons of the form
3526 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3527 // often indicate logic errors in the program.
3528 if (!lType->isFloatingType()) {
3529 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3530 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3531 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003532 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003533 }
Mike Stump9afab102009-02-19 03:04:26 +00003534
Nate Begemanc5f0f652008-07-14 18:02:46 +00003535 // Check for comparisons of floating point operands using != and ==.
3536 if (!isRelational && lType->isFloatingType()) {
3537 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003538 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003539 }
Mike Stump9afab102009-02-19 03:04:26 +00003540
Nate Begemanc5f0f652008-07-14 18:02:46 +00003541 // Return the type for the comparison, which is the same as vector type for
3542 // integer vectors, or an integer type of identical size and number of
3543 // elements for floating point vectors.
3544 if (lType->isIntegerType())
3545 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003546
Nate Begemanc5f0f652008-07-14 18:02:46 +00003547 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003548 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003549 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003550 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003551 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3552 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3553
Mike Stump9afab102009-02-19 03:04:26 +00003554 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003555 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003556 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3557}
3558
Chris Lattner4b009652007-07-25 00:24:17 +00003559inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003560 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003561{
3562 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003563 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003564
Steve Naroff8f708362007-08-24 19:07:16 +00003565 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003566
Chris Lattner4b009652007-07-25 00:24:17 +00003567 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003568 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003569 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003570}
3571
3572inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003573 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003574{
3575 UsualUnaryConversions(lex);
3576 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003577
Eli Friedmanbea3f842008-05-13 20:16:47 +00003578 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003579 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003580 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003581}
3582
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003583/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3584/// is a read-only property; return true if so. A readonly property expression
3585/// depends on various declarations and thus must be treated specially.
3586///
Mike Stump9afab102009-02-19 03:04:26 +00003587static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003588{
3589 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3590 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3591 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3592 QualType BaseType = PropExpr->getBase()->getType();
3593 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003594 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003595 PTy->getPointeeType()->getAsObjCInterfaceType())
3596 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3597 if (S.isPropertyReadonly(PDecl, IFace))
3598 return true;
3599 }
3600 }
3601 return false;
3602}
3603
Chris Lattner4c2642c2008-11-18 01:22:49 +00003604/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3605/// emit an error and return true. If so, return false.
3606static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003607 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3608 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3609 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003610 if (IsLV == Expr::MLV_Valid)
3611 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003612
Chris Lattner4c2642c2008-11-18 01:22:49 +00003613 unsigned Diag = 0;
3614 bool NeedType = false;
3615 switch (IsLV) { // C99 6.5.16p2
3616 default: assert(0 && "Unknown result from isModifiableLvalue!");
3617 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003618 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003619 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3620 NeedType = true;
3621 break;
Mike Stump9afab102009-02-19 03:04:26 +00003622 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003623 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3624 NeedType = true;
3625 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003626 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003627 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3628 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003629 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003630 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3631 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003632 case Expr::MLV_IncompleteType:
3633 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00003634 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003635 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3636 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003637 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003638 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3639 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003640 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003641 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3642 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003643 case Expr::MLV_ReadonlyProperty:
3644 Diag = diag::error_readonly_property_assignment;
3645 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003646 case Expr::MLV_NoSetterProperty:
3647 Diag = diag::error_nosetter_property_assignment;
3648 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003649 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003650
Chris Lattner4c2642c2008-11-18 01:22:49 +00003651 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003652 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003653 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003654 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003655 return true;
3656}
3657
3658
3659
3660// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003661QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3662 SourceLocation Loc,
3663 QualType CompoundType) {
3664 // Verify that LHS is a modifiable lvalue, and emit error if not.
3665 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003666 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003667
3668 QualType LHSType = LHS->getType();
3669 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003670
Chris Lattner005ed752008-01-04 18:04:52 +00003671 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003672 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003673 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003674 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003675 // Special case of NSObject attributes on c-style pointer types.
3676 if (ConvTy == IncompatiblePointer &&
3677 ((Context.isObjCNSObjectType(LHSType) &&
3678 Context.isObjCObjectPointerType(RHSType)) ||
3679 (Context.isObjCNSObjectType(RHSType) &&
3680 Context.isObjCObjectPointerType(LHSType))))
3681 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003682
Chris Lattner34c85082008-08-21 18:04:13 +00003683 // If the RHS is a unary plus or minus, check to see if they = and + are
3684 // right next to each other. If so, the user may have typo'd "x =+ 4"
3685 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003686 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003687 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3688 RHSCheck = ICE->getSubExpr();
3689 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3690 if ((UO->getOpcode() == UnaryOperator::Plus ||
3691 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003692 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003693 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00003694 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3695 // And there is a space or other character before the subexpr of the
3696 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00003697 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3698 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003699 Diag(Loc, diag::warn_not_compound_assign)
3700 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3701 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00003702 }
Chris Lattner34c85082008-08-21 18:04:13 +00003703 }
3704 } else {
3705 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003706 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003707 }
Chris Lattner005ed752008-01-04 18:04:52 +00003708
Chris Lattner1eafdea2008-11-18 01:30:42 +00003709 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3710 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003711 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003712
Chris Lattner4b009652007-07-25 00:24:17 +00003713 // C99 6.5.16p3: The type of an assignment expression is the type of the
3714 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003715 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003716 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3717 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003718 // C++ 5.17p1: the type of the assignment expression is that of its left
3719 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003720 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003721}
3722
Chris Lattner1eafdea2008-11-18 01:30:42 +00003723// C99 6.5.17
3724QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00003725 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003726 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00003727
3728 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
3729 // incomplete in C++).
3730
Chris Lattner1eafdea2008-11-18 01:30:42 +00003731 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003732}
3733
3734/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3735/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003736QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3737 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003738 if (Op->isTypeDependent())
3739 return Context.DependentTy;
3740
Chris Lattnere65182c2008-11-21 07:05:48 +00003741 QualType ResType = Op->getType();
3742 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003743
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003744 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3745 // Decrement of bool is not allowed.
3746 if (!isInc) {
3747 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3748 return QualType();
3749 }
3750 // Increment of bool sets it to true, but is deprecated.
3751 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3752 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003753 // OK!
3754 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3755 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00003756 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003757 if (getLangOptions().CPlusPlus) {
3758 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3759 << Op->getSourceRange();
3760 return QualType();
3761 }
3762
3763 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003764 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003765 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003766 if (getLangOptions().CPlusPlus) {
3767 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3768 << Op->getType() << Op->getSourceRange();
3769 return QualType();
3770 }
3771
3772 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003773 << ResType << Op->getSourceRange();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00003774 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
3775 diag::err_typecheck_arithmetic_incomplete_type,
3776 Op->getSourceRange(), SourceRange(),
3777 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003778 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003779 } else if (ResType->isComplexType()) {
3780 // C99 does not support ++/-- on complex types, we allow as an extension.
3781 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003782 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003783 } else {
3784 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003785 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003786 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003787 }
Mike Stump9afab102009-02-19 03:04:26 +00003788 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003789 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003790 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003791 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003792 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003793}
3794
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003795/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003796/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003797/// where the declaration is needed for type checking. We only need to
3798/// handle cases when the expression references a function designator
3799/// or is an lvalue. Here are some examples:
3800/// - &(x) => x
3801/// - &*****f => f for f a function designator.
3802/// - &s.xx => s
3803/// - &s.zz[1].yy -> s, if zz is an array
3804/// - *(x + 1) -> x, if x is an array
3805/// - &"123"[2] -> 0
3806/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003807static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003808 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003809 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003810 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003811 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003812 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003813 // Fields cannot be declared with a 'register' storage class.
3814 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003815 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003816 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003817 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003818 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003819 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003820
Douglas Gregord2baafd2008-10-21 16:13:35 +00003821 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003822 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003823 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003824 return 0;
3825 else
3826 return VD;
3827 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003828 case Stmt::UnaryOperatorClass: {
3829 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003830
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003831 switch(UO->getOpcode()) {
3832 case UnaryOperator::Deref: {
3833 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003834 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3835 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3836 if (!VD || VD->getType()->isPointerType())
3837 return 0;
3838 return VD;
3839 }
3840 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003841 }
3842 case UnaryOperator::Real:
3843 case UnaryOperator::Imag:
3844 case UnaryOperator::Extension:
3845 return getPrimaryDecl(UO->getSubExpr());
3846 default:
3847 return 0;
3848 }
3849 }
3850 case Stmt::BinaryOperatorClass: {
3851 BinaryOperator *BO = cast<BinaryOperator>(E);
3852
3853 // Handle cases involving pointer arithmetic. The result of an
3854 // Assign or AddAssign is not an lvalue so they can be ignored.
3855
3856 // (x + n) or (n + x) => x
3857 if (BO->getOpcode() == BinaryOperator::Add) {
3858 if (BO->getLHS()->getType()->isPointerType()) {
3859 return getPrimaryDecl(BO->getLHS());
3860 } else if (BO->getRHS()->getType()->isPointerType()) {
3861 return getPrimaryDecl(BO->getRHS());
3862 }
3863 }
3864
3865 return 0;
3866 }
Chris Lattner4b009652007-07-25 00:24:17 +00003867 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003868 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003869 case Stmt::ImplicitCastExprClass:
3870 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003871 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003872 default:
3873 return 0;
3874 }
3875}
3876
3877/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003878/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003879/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003880/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003881/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003882/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003883/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003884QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003885 if (op->isTypeDependent())
3886 return Context.DependentTy;
3887
Steve Naroff9c6c3592008-01-13 17:10:08 +00003888 if (getLangOptions().C99) {
3889 // Implement C99-only parts of addressof rules.
3890 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3891 if (uOp->getOpcode() == UnaryOperator::Deref)
3892 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3893 // (assuming the deref expression is valid).
3894 return uOp->getSubExpr()->getType();
3895 }
3896 // Technically, there should be a check for array subscript
3897 // expressions here, but the result of one is always an lvalue anyway.
3898 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003899 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003900 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003901
Chris Lattner4b009652007-07-25 00:24:17 +00003902 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003903 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3904 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003905 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3906 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003907 return QualType();
3908 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003909 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003910 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3911 if (Field->isBitField()) {
3912 Diag(OpLoc, diag::err_typecheck_address_of)
3913 << "bit-field" << op->getSourceRange();
3914 return QualType();
3915 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003916 }
3917 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003918 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3919 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003920 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003921 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003922 return QualType();
3923 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003924 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003925 // with the register storage-class specifier.
3926 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3927 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003928 Diag(OpLoc, diag::err_typecheck_address_of)
3929 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003930 return QualType();
3931 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003932 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003933 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003934 } else if (isa<FieldDecl>(dcl)) {
3935 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003936 // Could be a pointer to member, though, if there is an explicit
3937 // scope qualifier for the class.
3938 if (isa<QualifiedDeclRefExpr>(op)) {
3939 DeclContext *Ctx = dcl->getDeclContext();
3940 if (Ctx && Ctx->isRecord())
3941 return Context.getMemberPointerType(op->getType(),
3942 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3943 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003944 } else if (isa<FunctionDecl>(dcl)) {
3945 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003946 // As above.
3947 if (isa<QualifiedDeclRefExpr>(op)) {
3948 DeclContext *Ctx = dcl->getDeclContext();
3949 if (Ctx && Ctx->isRecord())
3950 return Context.getMemberPointerType(op->getType(),
3951 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3952 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003953 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003954 else
Chris Lattner4b009652007-07-25 00:24:17 +00003955 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003956 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003957
Chris Lattner4b009652007-07-25 00:24:17 +00003958 // If the operand has type "type", the result has type "pointer to type".
3959 return Context.getPointerType(op->getType());
3960}
3961
Chris Lattnerda5c0872008-11-23 09:13:29 +00003962QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003963 if (Op->isTypeDependent())
3964 return Context.DependentTy;
3965
Chris Lattnerda5c0872008-11-23 09:13:29 +00003966 UsualUnaryConversions(Op);
3967 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003968
Chris Lattnerda5c0872008-11-23 09:13:29 +00003969 // Note that per both C89 and C99, this is always legal, even if ptype is an
3970 // incomplete type or void. It would be possible to warn about dereferencing
3971 // a void pointer, but it's completely well-defined, and such a warning is
3972 // unlikely to catch any mistakes.
3973 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003974 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003975
Chris Lattner77d52da2008-11-20 06:06:08 +00003976 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003977 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003978 return QualType();
3979}
3980
3981static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3982 tok::TokenKind Kind) {
3983 BinaryOperator::Opcode Opc;
3984 switch (Kind) {
3985 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003986 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3987 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003988 case tok::star: Opc = BinaryOperator::Mul; break;
3989 case tok::slash: Opc = BinaryOperator::Div; break;
3990 case tok::percent: Opc = BinaryOperator::Rem; break;
3991 case tok::plus: Opc = BinaryOperator::Add; break;
3992 case tok::minus: Opc = BinaryOperator::Sub; break;
3993 case tok::lessless: Opc = BinaryOperator::Shl; break;
3994 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3995 case tok::lessequal: Opc = BinaryOperator::LE; break;
3996 case tok::less: Opc = BinaryOperator::LT; break;
3997 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3998 case tok::greater: Opc = BinaryOperator::GT; break;
3999 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4000 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4001 case tok::amp: Opc = BinaryOperator::And; break;
4002 case tok::caret: Opc = BinaryOperator::Xor; break;
4003 case tok::pipe: Opc = BinaryOperator::Or; break;
4004 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4005 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4006 case tok::equal: Opc = BinaryOperator::Assign; break;
4007 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4008 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4009 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4010 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4011 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4012 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4013 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4014 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4015 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4016 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4017 case tok::comma: Opc = BinaryOperator::Comma; break;
4018 }
4019 return Opc;
4020}
4021
4022static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4023 tok::TokenKind Kind) {
4024 UnaryOperator::Opcode Opc;
4025 switch (Kind) {
4026 default: assert(0 && "Unknown unary op!");
4027 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4028 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4029 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4030 case tok::star: Opc = UnaryOperator::Deref; break;
4031 case tok::plus: Opc = UnaryOperator::Plus; break;
4032 case tok::minus: Opc = UnaryOperator::Minus; break;
4033 case tok::tilde: Opc = UnaryOperator::Not; break;
4034 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004035 case tok::kw___real: Opc = UnaryOperator::Real; break;
4036 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4037 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4038 }
4039 return Opc;
4040}
4041
Douglas Gregord7f915e2008-11-06 23:29:22 +00004042/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4043/// operator @p Opc at location @c TokLoc. This routine only supports
4044/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004045Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4046 unsigned Op,
4047 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004048 QualType ResultTy; // Result type of the binary operator.
4049 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
4050 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
4051
4052 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004053 case BinaryOperator::Assign:
4054 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4055 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004056 case BinaryOperator::PtrMemD:
4057 case BinaryOperator::PtrMemI:
4058 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4059 Opc == BinaryOperator::PtrMemI);
4060 break;
4061 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004062 case BinaryOperator::Div:
4063 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4064 break;
4065 case BinaryOperator::Rem:
4066 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4067 break;
4068 case BinaryOperator::Add:
4069 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4070 break;
4071 case BinaryOperator::Sub:
4072 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4073 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004074 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004075 case BinaryOperator::Shr:
4076 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4077 break;
4078 case BinaryOperator::LE:
4079 case BinaryOperator::LT:
4080 case BinaryOperator::GE:
4081 case BinaryOperator::GT:
4082 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
4083 break;
4084 case BinaryOperator::EQ:
4085 case BinaryOperator::NE:
4086 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
4087 break;
4088 case BinaryOperator::And:
4089 case BinaryOperator::Xor:
4090 case BinaryOperator::Or:
4091 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4092 break;
4093 case BinaryOperator::LAnd:
4094 case BinaryOperator::LOr:
4095 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4096 break;
4097 case BinaryOperator::MulAssign:
4098 case BinaryOperator::DivAssign:
4099 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4100 if (!CompTy.isNull())
4101 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4102 break;
4103 case BinaryOperator::RemAssign:
4104 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4105 if (!CompTy.isNull())
4106 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4107 break;
4108 case BinaryOperator::AddAssign:
4109 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
4110 if (!CompTy.isNull())
4111 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4112 break;
4113 case BinaryOperator::SubAssign:
4114 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
4115 if (!CompTy.isNull())
4116 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4117 break;
4118 case BinaryOperator::ShlAssign:
4119 case BinaryOperator::ShrAssign:
4120 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4121 if (!CompTy.isNull())
4122 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4123 break;
4124 case BinaryOperator::AndAssign:
4125 case BinaryOperator::XorAssign:
4126 case BinaryOperator::OrAssign:
4127 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4128 if (!CompTy.isNull())
4129 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4130 break;
4131 case BinaryOperator::Comma:
4132 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4133 break;
4134 }
4135 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004136 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00004137 if (CompTy.isNull())
4138 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4139 else
4140 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00004141 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004142}
4143
Chris Lattner4b009652007-07-25 00:24:17 +00004144// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004145Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4146 tok::TokenKind Kind,
4147 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004148 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004149 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00004150
Steve Naroff87d58b42007-09-16 03:34:24 +00004151 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4152 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004153
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004154 if (getLangOptions().CPlusPlus &&
4155 (lhs->getType()->isOverloadableType() ||
4156 rhs->getType()->isOverloadableType())) {
4157 // Find all of the overloaded operators visible from this
4158 // point. We perform both an operator-name lookup from the local
4159 // scope and an argument-dependent lookup based on the types of
4160 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004161 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004162 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4163 if (OverOp != OO_None) {
4164 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4165 Functions);
4166 Expr *Args[2] = { lhs, rhs };
4167 DeclarationName OpName
4168 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4169 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004170 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004171
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004172 // Build the (potentially-overloaded, potentially-dependent)
4173 // binary operation.
4174 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004175 }
4176
Douglas Gregord7f915e2008-11-06 23:29:22 +00004177 // Build a built-in binary operation.
4178 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004179}
4180
Douglas Gregorc78182d2009-03-13 23:49:33 +00004181Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4182 unsigned OpcIn,
4183 ExprArg InputArg) {
4184 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004185
Douglas Gregorc78182d2009-03-13 23:49:33 +00004186 // FIXME: Input is modified below, but InputArg is not updated
4187 // appropriately.
4188 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004189 QualType resultType;
4190 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004191 case UnaryOperator::PostInc:
4192 case UnaryOperator::PostDec:
4193 case UnaryOperator::OffsetOf:
4194 assert(false && "Invalid unary operator");
4195 break;
4196
Chris Lattner4b009652007-07-25 00:24:17 +00004197 case UnaryOperator::PreInc:
4198 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004199 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4200 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004201 break;
Mike Stump9afab102009-02-19 03:04:26 +00004202 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004203 resultType = CheckAddressOfOperand(Input, OpLoc);
4204 break;
Mike Stump9afab102009-02-19 03:04:26 +00004205 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004206 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004207 resultType = CheckIndirectionOperand(Input, OpLoc);
4208 break;
4209 case UnaryOperator::Plus:
4210 case UnaryOperator::Minus:
4211 UsualUnaryConversions(Input);
4212 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004213 if (resultType->isDependentType())
4214 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004215 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4216 break;
4217 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4218 resultType->isEnumeralType())
4219 break;
4220 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4221 Opc == UnaryOperator::Plus &&
4222 resultType->isPointerType())
4223 break;
4224
Sebastian Redl8b769972009-01-19 00:08:26 +00004225 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4226 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004227 case UnaryOperator::Not: // bitwise complement
4228 UsualUnaryConversions(Input);
4229 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004230 if (resultType->isDependentType())
4231 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004232 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4233 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4234 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004235 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004236 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004237 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004238 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4239 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004240 break;
4241 case UnaryOperator::LNot: // logical negation
4242 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4243 DefaultFunctionArrayConversion(Input);
4244 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004245 if (resultType->isDependentType())
4246 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004247 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004248 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4249 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004250 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004251 // In C++, it's bool. C++ 5.3.1p8
4252 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004253 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004254 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004255 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004256 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004257 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004258 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004259 resultType = Input->getType();
4260 break;
4261 }
4262 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004263 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004264
4265 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004266 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004267}
4268
Douglas Gregorc78182d2009-03-13 23:49:33 +00004269// Unary Operators. 'Tok' is the token for the operator.
4270Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4271 tok::TokenKind Op, ExprArg input) {
4272 Expr *Input = (Expr*)input.get();
4273 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4274
4275 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4276 // Find all of the overloaded operators visible from this
4277 // point. We perform both an operator-name lookup from the local
4278 // scope and an argument-dependent lookup based on the types of
4279 // the arguments.
4280 FunctionSet Functions;
4281 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4282 if (OverOp != OO_None) {
4283 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4284 Functions);
4285 DeclarationName OpName
4286 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4287 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4288 }
4289
4290 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4291 }
4292
4293 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4294}
4295
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004296/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004297Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4298 SourceLocation LabLoc,
4299 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004300 // Look up the record for this label identifier.
Steve Naroffff9ecaf2009-03-13 16:03:38 +00004301 LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4302 LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004303
Daniel Dunbar879788d2008-08-04 16:51:22 +00004304 // If we haven't seen this label yet, create a forward reference. It
4305 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004306 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004307 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004308
Chris Lattner4b009652007-07-25 00:24:17 +00004309 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004310 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4311 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004312}
4313
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004314Sema::OwningExprResult
4315Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4316 SourceLocation RPLoc) { // "({..})"
4317 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004318 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4319 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4320
Eli Friedmanbc941e12009-01-24 23:09:00 +00004321 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4322 if (isFileScope) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004323 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004324 }
4325
Chris Lattner4b009652007-07-25 00:24:17 +00004326 // FIXME: there are a variety of strange constraints to enforce here, for
4327 // example, it is not possible to goto into a stmt expression apparently.
4328 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004329
Chris Lattner4b009652007-07-25 00:24:17 +00004330 // FIXME: the last statement in the compount stmt has its value used. We
4331 // should not warn about it being unused.
4332
4333 // If there are sub stmts in the compound stmt, take the type of the last one
4334 // as the type of the stmtexpr.
4335 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004336
Chris Lattner200964f2008-07-26 19:51:01 +00004337 if (!Compound->body_empty()) {
4338 Stmt *LastStmt = Compound->body_back();
4339 // If LastStmt is a label, skip down through into the body.
4340 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4341 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004342
Chris Lattner200964f2008-07-26 19:51:01 +00004343 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004344 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004345 }
Mike Stump9afab102009-02-19 03:04:26 +00004346
Eli Friedman2b128322009-03-23 00:24:07 +00004347 // FIXME: Check that expression type is complete/non-abstract; statement
4348 // expressions are not lvalues.
4349
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004350 substmt.release();
4351 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004352}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004353
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004354Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4355 SourceLocation BuiltinLoc,
4356 SourceLocation TypeLoc,
4357 TypeTy *argty,
4358 OffsetOfComponent *CompPtr,
4359 unsigned NumComponents,
4360 SourceLocation RPLoc) {
4361 // FIXME: This function leaks all expressions in the offset components on
4362 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004363 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4364 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004365
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004366 bool Dependent = ArgTy->isDependentType();
4367
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004368 // We must have at least one component that refers to the type, and the first
4369 // one is known to be a field designator. Verify that the ArgTy represents
4370 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004371 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004372 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004373
Eli Friedman2b128322009-03-23 00:24:07 +00004374 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4375 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004376
Eli Friedman342d9432009-02-27 06:44:11 +00004377 // Otherwise, create a null pointer as the base, and iteratively process
4378 // the offsetof designators.
4379 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4380 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004381 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004382 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004383
Chris Lattnerb37522e2007-08-31 21:49:13 +00004384 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4385 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004386 // FIXME: This diagnostic isn't actually visible because the location is in
4387 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004388 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004389 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4390 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004391
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004392 if (!Dependent) {
4393 // FIXME: Dependent case loses a lot of information here. And probably
4394 // leaks like a sieve.
4395 for (unsigned i = 0; i != NumComponents; ++i) {
4396 const OffsetOfComponent &OC = CompPtr[i];
4397 if (OC.isBrackets) {
4398 // Offset of an array sub-field. TODO: Should we allow vector elements?
4399 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4400 if (!AT) {
4401 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004402 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4403 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004404 }
4405
4406 // FIXME: C++: Verify that operator[] isn't overloaded.
4407
Eli Friedman342d9432009-02-27 06:44:11 +00004408 // Promote the array so it looks more like a normal array subscript
4409 // expression.
4410 DefaultFunctionArrayConversion(Res);
4411
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004412 // C99 6.5.2.1p1
4413 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004414 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004415 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004416 return ExprError(Diag(Idx->getLocStart(),
4417 diag::err_typecheck_subscript)
4418 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004419
4420 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4421 OC.LocEnd);
4422 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004423 }
Mike Stump9afab102009-02-19 03:04:26 +00004424
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004425 const RecordType *RC = Res->getType()->getAsRecordType();
4426 if (!RC) {
4427 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004428 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4429 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004430 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004431
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004432 // Get the decl corresponding to this.
4433 RecordDecl *RD = RC->getDecl();
4434 FieldDecl *MemberDecl
4435 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4436 LookupMemberName)
4437 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004438 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004439 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004440 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4441 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00004442
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004443 // FIXME: C++: Verify that MemberDecl isn't a static field.
4444 // FIXME: Verify that MemberDecl isn't a bitfield.
4445 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4446 // matter here.
4447 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004448 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004449 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004450 }
Mike Stump9afab102009-02-19 03:04:26 +00004451
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004452 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4453 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004454}
4455
4456
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004457Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4458 TypeTy *arg1,TypeTy *arg2,
4459 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00004460 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4461 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004462
Steve Naroff63bad2d2007-08-01 22:05:33 +00004463 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004464
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004465 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4466 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00004467}
4468
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004469Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4470 ExprArg cond,
4471 ExprArg expr1, ExprArg expr2,
4472 SourceLocation RPLoc) {
4473 Expr *CondExpr = static_cast<Expr*>(cond.get());
4474 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4475 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00004476
Steve Naroff93c53012007-08-03 21:21:27 +00004477 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4478
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004479 QualType resType;
4480 if (CondExpr->isValueDependent()) {
4481 resType = Context.DependentTy;
4482 } else {
4483 // The conditional expression is required to be a constant expression.
4484 llvm::APSInt condEval(32);
4485 SourceLocation ExpLoc;
4486 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004487 return ExprError(Diag(ExpLoc,
4488 diag::err_typecheck_choose_expr_requires_constant)
4489 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00004490
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004491 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4492 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4493 }
4494
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004495 cond.release(); expr1.release(); expr2.release();
4496 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4497 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00004498}
4499
Steve Naroff52a81c02008-09-03 18:15:37 +00004500//===----------------------------------------------------------------------===//
4501// Clang Extensions.
4502//===----------------------------------------------------------------------===//
4503
4504/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004505void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004506 // Analyze block parameters.
4507 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004508
Steve Naroff52a81c02008-09-03 18:15:37 +00004509 // Add BSI to CurBlock.
4510 BSI->PrevBlockInfo = CurBlock;
4511 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004512
Steve Naroff52a81c02008-09-03 18:15:37 +00004513 BSI->ReturnType = 0;
4514 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004515 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004516
Steve Naroff52059382008-10-10 01:28:17 +00004517 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004518 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004519}
4520
Mike Stumpc1fddff2009-02-04 22:31:32 +00004521void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4522 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4523
4524 if (ParamInfo.getNumTypeObjects() == 0
4525 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4526 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4527
4528 // The type is entirely optional as well, if none, use DependentTy.
4529 if (T.isNull())
4530 T = Context.DependentTy;
4531
4532 // The parameter list is optional, if there was none, assume ().
4533 if (!T->isFunctionType())
4534 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4535
4536 CurBlock->hasPrototype = true;
4537 CurBlock->isVariadic = false;
4538 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4539 .getTypePtr();
4540
4541 if (!RetTy->isDependentType())
4542 CurBlock->ReturnType = RetTy;
4543 return;
4544 }
4545
Steve Naroff52a81c02008-09-03 18:15:37 +00004546 // Analyze arguments to block.
4547 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4548 "Not a function declarator!");
4549 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004550
Steve Naroff52059382008-10-10 01:28:17 +00004551 CurBlock->hasPrototype = FTI.hasPrototype;
4552 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004553
Steve Naroff52a81c02008-09-03 18:15:37 +00004554 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4555 // no arguments, not a function that takes a single void argument.
4556 if (FTI.hasPrototype &&
4557 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4558 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4559 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4560 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004561 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004562 } else if (FTI.hasPrototype) {
4563 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004564 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4565 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004566 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4567
4568 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4569 .getTypePtr();
4570
4571 if (!RetTy->isDependentType())
4572 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004573 }
Steve Naroff494cb0f2009-03-13 16:56:44 +00004574 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
4575 CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004576
Steve Naroff52059382008-10-10 01:28:17 +00004577 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4578 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4579 // If this has an identifier, add it to the scope stack.
4580 if ((*AI)->getIdentifier())
4581 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004582}
4583
4584/// ActOnBlockError - If there is an error parsing a block, this callback
4585/// is invoked to pop the information about the block from the action impl.
4586void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4587 // Ensure that CurBlock is deleted.
4588 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004589
Steve Naroff52a81c02008-09-03 18:15:37 +00004590 // Pop off CurBlock, handle nested blocks.
4591 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004592
Steve Naroff52a81c02008-09-03 18:15:37 +00004593 // FIXME: Delete the ParmVarDecl objects as well???
Douglas Gregorc1408ea2009-03-11 23:54:15 +00004594
Steve Naroff52a81c02008-09-03 18:15:37 +00004595}
4596
4597/// ActOnBlockStmtExpr - This is called when the body of a block statement
4598/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004599Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4600 StmtArg body, Scope *CurScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004601 // Ensure that CurBlock is deleted.
4602 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00004603
Steve Naroff52059382008-10-10 01:28:17 +00004604 PopDeclContext();
4605
Steve Naroff52a81c02008-09-03 18:15:37 +00004606 // Pop off CurBlock, handle nested blocks.
4607 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004608
Steve Naroff52a81c02008-09-03 18:15:37 +00004609 QualType RetTy = Context.VoidTy;
4610 if (BSI->ReturnType)
4611 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004612
Steve Naroff52a81c02008-09-03 18:15:37 +00004613 llvm::SmallVector<QualType, 8> ArgTypes;
4614 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4615 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004616
Steve Naroff52a81c02008-09-03 18:15:37 +00004617 QualType BlockTy;
4618 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004619 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004620 else
4621 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004622 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004623
Eli Friedman2b128322009-03-23 00:24:07 +00004624 // FIXME: Check that return/parameter types are complete/non-abstract
4625
Steve Naroff52a81c02008-09-03 18:15:37 +00004626 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004627
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004628 BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4629 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4630 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00004631}
4632
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004633Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4634 ExprArg expr, TypeTy *type,
4635 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004636 QualType T = QualType::getFromOpaquePtr(type);
4637
4638 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004639
4640 // Get the va_list type
4641 QualType VaListType = Context.getBuiltinVaListType();
4642 // Deal with implicit array decay; for example, on x86-64,
4643 // va_list is an array, but it's supposed to decay to
4644 // a pointer for va_arg.
4645 if (VaListType->isArrayType())
4646 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004647 // Make sure the input expression also decays appropriately.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004648 Expr *E = static_cast<Expr*>(expr.get());
Eli Friedman8754e5b2008-08-20 22:17:17 +00004649 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004650
4651 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004652 return ExprError(Diag(E->getLocStart(),
4653 diag::err_first_argument_to_va_arg_not_of_type_va_list)
4654 << E->getType() << E->getSourceRange());
Mike Stump9afab102009-02-19 03:04:26 +00004655
Eli Friedman2b128322009-03-23 00:24:07 +00004656 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00004657 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004658
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004659 expr.release();
4660 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4661 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00004662}
4663
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004664Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00004665 // The type of __null will be int or long, depending on the size of
4666 // pointers on the target.
4667 QualType Ty;
4668 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4669 Ty = Context.IntTy;
4670 else
4671 Ty = Context.LongTy;
4672
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004673 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00004674}
4675
Chris Lattner005ed752008-01-04 18:04:52 +00004676bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4677 SourceLocation Loc,
4678 QualType DstType, QualType SrcType,
4679 Expr *SrcExpr, const char *Flavor) {
4680 // Decode the result (notice that AST's are still created for extensions).
4681 bool isInvalid = false;
4682 unsigned DiagKind;
4683 switch (ConvTy) {
4684 default: assert(0 && "Unknown conversion type");
4685 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004686 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004687 DiagKind = diag::ext_typecheck_convert_pointer_int;
4688 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004689 case IntToPointer:
4690 DiagKind = diag::ext_typecheck_convert_int_pointer;
4691 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004692 case IncompatiblePointer:
4693 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4694 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00004695 case IncompatiblePointerSign:
4696 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
4697 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004698 case FunctionVoidPointer:
4699 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4700 break;
4701 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004702 // If the qualifiers lost were because we were applying the
4703 // (deprecated) C++ conversion from a string literal to a char*
4704 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4705 // Ideally, this check would be performed in
4706 // CheckPointerTypesForAssignment. However, that would require a
4707 // bit of refactoring (so that the second argument is an
4708 // expression, rather than a type), which should be done as part
4709 // of a larger effort to fix CheckPointerTypesForAssignment for
4710 // C++ semantics.
4711 if (getLangOptions().CPlusPlus &&
4712 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4713 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004714 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4715 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004716 case IntToBlockPointer:
4717 DiagKind = diag::err_int_to_block_pointer;
4718 break;
4719 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004720 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004721 break;
Steve Naroff19608432008-10-14 22:18:38 +00004722 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004723 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004724 // it can give a more specific diagnostic.
4725 DiagKind = diag::warn_incompatible_qualified_id;
4726 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004727 case IncompatibleVectors:
4728 DiagKind = diag::warn_incompatible_vectors;
4729 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004730 case Incompatible:
4731 DiagKind = diag::err_typecheck_convert_incompatible;
4732 isInvalid = true;
4733 break;
4734 }
Mike Stump9afab102009-02-19 03:04:26 +00004735
Chris Lattner271d4c22008-11-24 05:29:24 +00004736 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4737 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004738 return isInvalid;
4739}
Anders Carlssond5201b92008-11-30 19:50:32 +00004740
4741bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4742{
4743 Expr::EvalResult EvalResult;
4744
Mike Stump9afab102009-02-19 03:04:26 +00004745 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004746 EvalResult.HasSideEffects) {
4747 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4748
4749 if (EvalResult.Diag) {
4750 // We only show the note if it's not the usual "invalid subexpression"
4751 // or if it's actually in a subexpression.
4752 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4753 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4754 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4755 }
Mike Stump9afab102009-02-19 03:04:26 +00004756
Anders Carlssond5201b92008-11-30 19:50:32 +00004757 return true;
4758 }
4759
4760 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004761 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004762 E->getSourceRange();
4763
4764 // Print the reason it's not a constant.
4765 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4766 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4767 }
Mike Stump9afab102009-02-19 03:04:26 +00004768
Anders Carlssond5201b92008-11-30 19:50:32 +00004769 if (Result)
4770 *Result = EvalResult.Val.getInt();
4771 return false;
4772}