blob: 9534f7354f3ee36eacbe2de75e91295dd5eee9a9 [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) {
Steve Naroff774e4152009-01-21 00:14:39 +0000442 if (SS && !SS->isEmpty())
443 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Mike Stump9afab102009-02-19 03:04:26 +0000444 ValueDependent,
445 SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000446 else
447 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000448}
449
Douglas Gregor723d3332009-01-07 00:43:41 +0000450/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
451/// variable corresponding to the anonymous union or struct whose type
452/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000453static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000454 assert(Record->isAnonymousStructOrUnion() &&
455 "Record must be an anonymous struct or union!");
456
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000457 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000458 // be an O(1) operation rather than a slow walk through DeclContext's
459 // vector (which itself will be eliminated). DeclGroups might make
460 // this even better.
461 DeclContext *Ctx = Record->getDeclContext();
462 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
463 DEnd = Ctx->decls_end();
464 D != DEnd; ++D) {
465 if (*D == Record) {
466 // The object for the anonymous struct/union directly
467 // follows its type in the list of declarations.
468 ++D;
469 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000470 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000471 return *D;
472 }
473 }
474
475 assert(false && "Missing object for anonymous record");
476 return 0;
477}
478
Sebastian Redlcd883f72009-01-18 18:53:16 +0000479Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000480Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
481 FieldDecl *Field,
482 Expr *BaseObjectExpr,
483 SourceLocation OpLoc) {
484 assert(Field->getDeclContext()->isRecord() &&
485 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
486 && "Field must be stored inside an anonymous struct or union");
487
488 // Construct the sequence of field member references
489 // we'll have to perform to get to the field in the anonymous
490 // union/struct. The list of members is built from the field
491 // outward, so traverse it backwards to go from an object in
492 // the current context to the field we found.
493 llvm::SmallVector<FieldDecl *, 4> AnonFields;
494 AnonFields.push_back(Field);
495 VarDecl *BaseObject = 0;
496 DeclContext *Ctx = Field->getDeclContext();
497 do {
498 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000499 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000500 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
501 AnonFields.push_back(AnonField);
502 else {
503 BaseObject = cast<VarDecl>(AnonObject);
504 break;
505 }
506 Ctx = Ctx->getParent();
507 } while (Ctx->isRecord() &&
508 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
509
510 // Build the expression that refers to the base object, from
511 // which we will build a sequence of member references to each
512 // of the anonymous union objects and, eventually, the field we
513 // found via name lookup.
514 bool BaseObjectIsPointer = false;
515 unsigned ExtraQuals = 0;
516 if (BaseObject) {
517 // BaseObject is an anonymous struct/union variable (and is,
518 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000519 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000520 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000521 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000522 ExtraQuals
523 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
524 } else if (BaseObjectExpr) {
525 // The caller provided the base object expression. Determine
526 // whether its a pointer and whether it adds any qualifiers to the
527 // anonymous struct/union fields we're looking into.
528 QualType ObjectType = BaseObjectExpr->getType();
529 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
530 BaseObjectIsPointer = true;
531 ObjectType = ObjectPtr->getPointeeType();
532 }
533 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
534 } else {
535 // We've found a member of an anonymous struct/union that is
536 // inside a non-anonymous struct/union, so in a well-formed
537 // program our base object expression is "this".
538 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
539 if (!MD->isStatic()) {
540 QualType AnonFieldType
541 = Context.getTagDeclType(
542 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
543 QualType ThisType = Context.getTagDeclType(MD->getParent());
544 if ((Context.getCanonicalType(AnonFieldType)
545 == Context.getCanonicalType(ThisType)) ||
546 IsDerivedFrom(ThisType, AnonFieldType)) {
547 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000548 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000549 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000550 BaseObjectIsPointer = true;
551 }
552 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000553 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
554 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000555 }
556 ExtraQuals = MD->getTypeQualifiers();
557 }
558
559 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000560 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
561 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000562 }
563
564 // Build the implicit member references to the field of the
565 // anonymous struct/union.
566 Expr *Result = BaseObjectExpr;
567 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
568 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
569 FI != FIEnd; ++FI) {
570 QualType MemberType = (*FI)->getType();
571 if (!(*FI)->isMutable()) {
572 unsigned combinedQualifiers
573 = MemberType.getCVRQualifiers() | ExtraQuals;
574 MemberType = MemberType.getQualifiedType(combinedQualifiers);
575 }
Steve Naroff774e4152009-01-21 00:14:39 +0000576 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
577 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000578 BaseObjectIsPointer = false;
579 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000580 }
581
Sebastian Redlcd883f72009-01-18 18:53:16 +0000582 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000583}
584
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000585/// ActOnDeclarationNameExpr - The parser has read some kind of name
586/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
587/// performs lookup on that name and returns an expression that refers
588/// to that name. This routine isn't directly called from the parser,
589/// because the parser doesn't know about DeclarationName. Rather,
590/// this routine is called by ActOnIdentifierExpr,
591/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
592/// which form the DeclarationName from the corresponding syntactic
593/// forms.
594///
595/// HasTrailingLParen indicates whether this identifier is used in a
596/// function call context. LookupCtx is only used for a C++
597/// qualified-id (foo::bar) to indicate the class or namespace that
598/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000599///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000600/// isAddressOfOperand means that this expression is the direct operand
601/// of an address-of operator. This matters because this is the only
602/// situation where a qualified name referencing a non-static member may
603/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000604Sema::OwningExprResult
605Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
606 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000607 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000608 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000609 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000610 if (SS && SS->isInvalid())
611 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000612 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
613 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000614
Douglas Gregor09be81b2009-02-04 17:27:36 +0000615 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 if (Lookup.isAmbiguous()) {
617 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
618 SS && SS->isSet() ? SS->getRange()
619 : SourceRange());
620 return ExprError();
621 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000622 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000623
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000624 // If this reference is in an Objective-C method, then ivar lookup happens as
625 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000626 IdentifierInfo *II = Name.getAsIdentifierInfo();
627 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000628 // There are two cases to handle here. 1) scoped lookup could have failed,
629 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000630 // found a decl, but that decl is outside the current instance method (i.e.
631 // a global variable). In these two cases, we do a lookup for an ivar with
632 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000633 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000634 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000635 ObjCInterfaceDecl *ClassDeclared;
636 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000637 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000638 if (DiagnoseUseOfDecl(IV, Loc))
639 return ExprError();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000640 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
641 // If a class method attemps to use a free standing ivar, this is
642 // an error.
643 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
644 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
645 << IV->getDeclName());
646 // If a class method uses a global variable, even if an ivar with
647 // same name exists, use the global.
648 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000649 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
650 ClassDeclared != IFace)
651 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000652 // FIXME: This should use a new expr for a direct reference, don't turn
653 // this into Self->ivar, just return a BareIVarExpr or something.
654 IdentifierInfo &II = Context.Idents.get("self");
655 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
656 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
657 Loc, static_cast<Expr*>(SelfExpr.release()),
658 true, true);
659 Context.setFieldDecl(IFace, IV, MRef);
660 return Owned(MRef);
661 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000662 }
663 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000664 else if (getCurMethodDecl()->isInstanceMethod()) {
665 // We should warn if a local variable hides an ivar.
666 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000667 ObjCInterfaceDecl *ClassDeclared;
668 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
669 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
670 IFace == ClassDeclared)
671 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
672 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000673 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000674 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000675 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000676 QualType T;
677
678 if (getCurMethodDecl()->isInstanceMethod())
679 T = Context.getPointerType(Context.getObjCInterfaceType(
680 getCurMethodDecl()->getClassInterface()));
681 else
682 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000683 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000684 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000685 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000686
Douglas Gregoraa57e862009-02-18 21:56:37 +0000687 // Determine whether this name might be a candidate for
688 // argument-dependent lookup.
689 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
690 HasTrailingLParen;
691
692 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000693 // We've seen something of the form
694 //
695 // identifier(
696 //
697 // and we did not find any entity by the name
698 // "identifier". However, this identifier is still subject to
699 // argument-dependent lookup, so keep track of the name.
700 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
701 Context.OverloadTy,
702 Loc));
703 }
704
Chris Lattner4b009652007-07-25 00:24:17 +0000705 if (D == 0) {
706 // Otherwise, this could be an implicitly declared function reference (legal
707 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000708 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000709 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000710 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000711 else {
712 // If this name wasn't predeclared and if this is not a function call,
713 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000714 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000715 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
716 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000717 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
718 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000719 return ExprError(Diag(Loc, diag::err_undeclared_use)
720 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000721 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000722 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000723 }
724 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000725
Sebastian Redl0c9da212009-02-03 20:19:35 +0000726 // If this is an expression of the form &Class::member, don't build an
727 // implicit member ref, because we want a pointer to the member in general,
728 // not any specific instance's member.
729 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000730 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000731 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000732 QualType DType;
733 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
734 DType = FD->getType().getNonReferenceType();
735 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
736 DType = Method->getType();
737 } else if (isa<OverloadedFunctionDecl>(D)) {
738 DType = Context.OverloadTy;
739 }
740 // Could be an inner type. That's diagnosed below, so ignore it here.
741 if (!DType.isNull()) {
742 // The pointer is type- and value-dependent if it points into something
743 // dependent.
744 bool Dependent = false;
745 for (; DC; DC = DC->getParent()) {
746 // FIXME: could stop early at namespace scope.
747 if (DC->isRecord()) {
748 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
749 if (Context.getTypeDeclType(Record)->isDependentType()) {
750 Dependent = true;
751 break;
752 }
753 }
754 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000755 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000756 }
757 }
758 }
759
Douglas Gregor723d3332009-01-07 00:43:41 +0000760 // We may have found a field within an anonymous union or struct
761 // (C++ [class.union]).
762 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
763 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
764 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000765
Douglas Gregor3257fb52008-12-22 05:46:06 +0000766 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
767 if (!MD->isStatic()) {
768 // C++ [class.mfct.nonstatic]p2:
769 // [...] if name lookup (3.4.1) resolves the name in the
770 // id-expression to a nonstatic nontype member of class X or of
771 // a base class of X, the id-expression is transformed into a
772 // class member access expression (5.2.5) using (*this) (9.3.2)
773 // as the postfix-expression to the left of the '.' operator.
774 DeclContext *Ctx = 0;
775 QualType MemberType;
776 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
777 Ctx = FD->getDeclContext();
778 MemberType = FD->getType();
779
780 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
781 MemberType = RefType->getPointeeType();
782 else if (!FD->isMutable()) {
783 unsigned combinedQualifiers
784 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
785 MemberType = MemberType.getQualifiedType(combinedQualifiers);
786 }
787 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
788 if (!Method->isStatic()) {
789 Ctx = Method->getParent();
790 MemberType = Method->getType();
791 }
792 } else if (OverloadedFunctionDecl *Ovl
793 = dyn_cast<OverloadedFunctionDecl>(D)) {
794 for (OverloadedFunctionDecl::function_iterator
795 Func = Ovl->function_begin(),
796 FuncEnd = Ovl->function_end();
797 Func != FuncEnd; ++Func) {
798 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
799 if (!DMethod->isStatic()) {
800 Ctx = Ovl->getDeclContext();
801 MemberType = Context.OverloadTy;
802 break;
803 }
804 }
805 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000806
807 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000808 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
809 QualType ThisType = Context.getTagDeclType(MD->getParent());
810 if ((Context.getCanonicalType(CtxType)
811 == Context.getCanonicalType(ThisType)) ||
812 IsDerivedFrom(ThisType, CtxType)) {
813 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000814 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000815 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000816 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000817 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000818 }
819 }
820 }
821 }
822
Douglas Gregor8acb7272008-12-11 16:49:14 +0000823 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000824 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
825 if (MD->isStatic())
826 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000827 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
828 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000829 }
830
Douglas Gregor3257fb52008-12-22 05:46:06 +0000831 // Any other ways we could have found the field in a well-formed
832 // program would have been turned into implicit member expressions
833 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000834 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
835 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000836 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000837
Chris Lattner4b009652007-07-25 00:24:17 +0000838 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000839 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000840 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000841 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000842 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000843 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000844
Steve Naroffd6163f32008-09-05 22:11:13 +0000845 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000846 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000847 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
848 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000849 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
850 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
851 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000852 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000853
Douglas Gregoraa57e862009-02-18 21:56:37 +0000854 // Check whether this declaration can be used. Note that we suppress
855 // this check when we're going to perform argument-dependent lookup
856 // on this function name, because this might not be the function
857 // that overload resolution actually selects.
858 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
859 return ExprError();
860
Douglas Gregor48840c72008-12-10 23:01:14 +0000861 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000862 // Warn about constructs like:
863 // if (void *X = foo()) { ... } else { X }.
864 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000865 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
866 Scope *CheckS = S;
867 while (CheckS) {
868 if (CheckS->isWithinElse() &&
869 CheckS->getControlParent()->isDeclScope(Var)) {
870 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000871 ExprError(Diag(Loc, diag::warn_value_always_false)
872 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000873 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000874 ExprError(Diag(Loc, diag::warn_value_always_zero)
875 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000876 break;
877 }
878
879 // Move up one more control parent to check again.
880 CheckS = CheckS->getControlParent();
881 if (CheckS)
882 CheckS = CheckS->getParent();
883 }
884 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000885 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
886 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
887 // C99 DR 316 says that, if a function type comes from a
888 // function definition (without a prototype), that type is only
889 // used for checking compatibility. Therefore, when referencing
890 // the function, we pretend that we don't have the full function
891 // type.
892 QualType T = Func->getType();
893 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000894 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
895 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000896 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
897 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000898 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000899
900 // Only create DeclRefExpr's for valid Decl's.
901 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000902 return ExprError();
903
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000904 // If the identifier reference is inside a block, and it refers to a value
905 // that is outside the block, create a BlockDeclRefExpr instead of a
906 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
907 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000908 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000909 // We do not do this for things like enum constants, global variables, etc,
910 // as they do not get snapshotted.
911 //
912 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000913 // Blocks that have these can't be constant.
914 CurBlock->hasBlockDeclRefExprs = true;
915
Steve Naroff52059382008-10-10 01:28:17 +0000916 // The BlocksAttr indicates the variable is bound by-reference.
917 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000918 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000919 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000920
Steve Naroff52059382008-10-10 01:28:17 +0000921 // Variable will be bound by-copy, make it const within the closure.
922 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000923 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000924 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000925 }
926 // If this reference is not in a block or if the referenced variable is
927 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000928
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000929 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000930 bool ValueDependent = false;
931 if (getLangOptions().CPlusPlus) {
932 // C++ [temp.dep.expr]p3:
933 // An id-expression is type-dependent if it contains:
934 // - an identifier that was declared with a dependent type,
935 if (VD->getType()->isDependentType())
936 TypeDependent = true;
937 // - FIXME: a template-id that is dependent,
938 // - a conversion-function-id that specifies a dependent type,
939 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
940 Name.getCXXNameType()->isDependentType())
941 TypeDependent = true;
942 // - a nested-name-specifier that contains a class-name that
943 // names a dependent type.
944 else if (SS && !SS->isEmpty()) {
945 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
946 DC; DC = DC->getParent()) {
947 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000948 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000949 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
950 if (Context.getTypeDeclType(Record)->isDependentType()) {
951 TypeDependent = true;
952 break;
953 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000954 }
955 }
956 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000957
Douglas Gregora5d84612008-12-10 20:57:37 +0000958 // C++ [temp.dep.constexpr]p2:
959 //
960 // An identifier is value-dependent if it is:
961 // - a name declared with a dependent type,
962 if (TypeDependent)
963 ValueDependent = true;
964 // - the name of a non-type template parameter,
965 else if (isa<NonTypeTemplateParmDecl>(VD))
966 ValueDependent = true;
967 // - a constant with integral or enumeration type and is
968 // initialized with an expression that is value-dependent
969 // (FIXME!).
970 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000971
Sebastian Redlcd883f72009-01-18 18:53:16 +0000972 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
973 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000974}
975
Sebastian Redlcd883f72009-01-18 18:53:16 +0000976Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
977 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000978 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000979
Chris Lattner4b009652007-07-25 00:24:17 +0000980 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000981 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000982 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
983 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
984 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000985 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000986
Chris Lattner7e637512008-01-12 08:14:25 +0000987 // Pre-defined identifiers are of type char[x], where x is the length of the
988 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000989 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000990 if (FunctionDecl *FD = getCurFunctionDecl())
991 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000992 else if (ObjCMethodDecl *MD = getCurMethodDecl())
993 Length = MD->getSynthesizedMethodSize();
994 else {
995 Diag(Loc, diag::ext_predef_outside_function);
996 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
997 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
998 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000999
1000
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001001 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001002 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001003 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001004 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001005}
1006
Sebastian Redlcd883f72009-01-18 18:53:16 +00001007Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001008 llvm::SmallString<16> CharBuffer;
1009 CharBuffer.resize(Tok.getLength());
1010 const char *ThisTokBegin = &CharBuffer[0];
1011 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001012
Chris Lattner4b009652007-07-25 00:24:17 +00001013 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1014 Tok.getLocation(), PP);
1015 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001016 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001017
1018 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1019
Sebastian Redl75324932009-01-20 22:23:13 +00001020 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1021 Literal.isWide(),
1022 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001023}
1024
Sebastian Redlcd883f72009-01-18 18:53:16 +00001025Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1026 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001027 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1028 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001029 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001030 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001031 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001032 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001033 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001034
Chris Lattner4b009652007-07-25 00:24:17 +00001035 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001036 // Add padding so that NumericLiteralParser can overread by one character.
1037 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001038 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001039
Chris Lattner4b009652007-07-25 00:24:17 +00001040 // Get the spelling of the token, which eliminates trigraphs, etc.
1041 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001042
Chris Lattner4b009652007-07-25 00:24:17 +00001043 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1044 Tok.getLocation(), PP);
1045 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001046 return ExprError();
1047
Chris Lattner1de66eb2007-08-26 03:42:43 +00001048 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001049
Chris Lattner1de66eb2007-08-26 03:42:43 +00001050 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001051 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001052 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001053 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001054 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001055 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001056 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001057 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001058
1059 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1060
Ted Kremenekddedbe22007-11-29 00:56:49 +00001061 // isExact will be set by GetFloatValue().
1062 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001063 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1064 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001065
Chris Lattner1de66eb2007-08-26 03:42:43 +00001066 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001067 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001068 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001069 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001070
Neil Booth7421e9c2007-08-29 22:00:19 +00001071 // long long is a C99 feature.
1072 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001073 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001074 Diag(Tok.getLocation(), diag::ext_longlong);
1075
Chris Lattner4b009652007-07-25 00:24:17 +00001076 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001077 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001078
Chris Lattner4b009652007-07-25 00:24:17 +00001079 if (Literal.GetIntegerValue(ResultVal)) {
1080 // If this value didn't fit into uintmax_t, warn and force to ull.
1081 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001082 Ty = Context.UnsignedLongLongTy;
1083 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001084 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001085 } else {
1086 // If this value fits into a ULL, try to figure out what else it fits into
1087 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001088
Chris Lattner4b009652007-07-25 00:24:17 +00001089 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1090 // be an unsigned int.
1091 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1092
1093 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001094 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001095 if (!Literal.isLong && !Literal.isLongLong) {
1096 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001097 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001098
Chris Lattner4b009652007-07-25 00:24:17 +00001099 // Does it fit in a unsigned int?
1100 if (ResultVal.isIntN(IntSize)) {
1101 // Does it fit in a signed int?
1102 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001103 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001104 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001105 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001106 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001107 }
Chris Lattner4b009652007-07-25 00:24:17 +00001108 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001109
Chris Lattner4b009652007-07-25 00:24:17 +00001110 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001111 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001112 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001113
Chris Lattner4b009652007-07-25 00:24:17 +00001114 // Does it fit in a unsigned long?
1115 if (ResultVal.isIntN(LongSize)) {
1116 // Does it fit in a signed long?
1117 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001118 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001119 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001120 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001121 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001122 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001123 }
1124
Chris Lattner4b009652007-07-25 00:24:17 +00001125 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001126 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001127 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001128
Chris Lattner4b009652007-07-25 00:24:17 +00001129 // Does it fit in a unsigned long long?
1130 if (ResultVal.isIntN(LongLongSize)) {
1131 // Does it fit in a signed long long?
1132 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001133 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001134 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001135 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001136 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001137 }
1138 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001139
Chris Lattner4b009652007-07-25 00:24:17 +00001140 // If we still couldn't decide a type, we probably have something that
1141 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001142 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001143 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001144 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001145 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001146 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001147
Chris Lattnere4068872008-05-09 05:59:00 +00001148 if (ResultVal.getBitWidth() != Width)
1149 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001150 }
Sebastian Redl75324932009-01-20 22:23:13 +00001151 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001152 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001153
Chris Lattner1de66eb2007-08-26 03:42:43 +00001154 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1155 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001156 Res = new (Context) ImaginaryLiteral(Res,
1157 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001158
1159 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001160}
1161
Sebastian Redlcd883f72009-01-18 18:53:16 +00001162Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1163 SourceLocation R, ExprArg Val) {
1164 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001165 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001166 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001167}
1168
1169/// The UsualUnaryConversions() function is *not* called by this routine.
1170/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001171bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001172 SourceLocation OpLoc,
1173 const SourceRange &ExprRange,
1174 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001175 if (exprType->isDependentType())
1176 return false;
1177
Chris Lattner4b009652007-07-25 00:24:17 +00001178 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001179 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001180 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001181 if (isSizeof)
1182 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1183 return false;
1184 }
1185
1186 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001187 Diag(OpLoc, diag::ext_sizeof_void_type)
1188 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001189 return false;
1190 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001191
Douglas Gregorc84d8932009-03-09 16:13:40 +00001192 return RequireCompleteType(OpLoc, exprType,
Chris Lattner159fe082009-01-24 19:46:37 +00001193 isSizeof ? diag::err_sizeof_incomplete_type :
1194 diag::err_alignof_incomplete_type,
1195 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001196}
1197
Chris Lattner8d9f7962009-01-24 20:17:12 +00001198bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1199 const SourceRange &ExprRange) {
1200 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001201
Chris Lattner8d9f7962009-01-24 20:17:12 +00001202 // alignof decl is always ok.
1203 if (isa<DeclRefExpr>(E))
1204 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001205
1206 // Cannot know anything else if the expression is dependent.
1207 if (E->isTypeDependent())
1208 return false;
1209
Chris Lattner8d9f7962009-01-24 20:17:12 +00001210 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1211 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1212 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001213 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001214 return true;
1215 }
1216 // Other fields are ok.
1217 return false;
1218 }
1219 }
1220 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1221}
1222
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001223/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1224/// the same for @c alignof and @c __alignof
1225/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001226Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001227Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1228 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001229 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001230 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001231
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001232 QualType ArgTy;
1233 SourceRange Range;
1234 if (isType) {
1235 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1236 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001237
1238 // Verify that the operand is valid.
1239 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1240 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001241 } else {
1242 // Get the end location.
1243 Expr *ArgEx = (Expr *)TyOrEx;
1244 Range = ArgEx->getSourceRange();
1245 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001246
1247 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001248 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001249 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001250 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001251 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1252 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1253 isInvalid = true;
1254 } else {
1255 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1256 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001257
1258 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001259 DeleteExpr(ArgEx);
1260 return ExprError();
1261 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001262 }
1263
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001264 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001265 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001266 Context.getSizeType(), OpLoc,
1267 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001268}
1269
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001270QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001271 if (V->isTypeDependent())
1272 return Context.DependentTy;
1273
Chris Lattner03931a72007-08-24 21:16:53 +00001274 DefaultFunctionArrayConversion(V);
1275
Chris Lattnera16e42d2007-08-26 05:39:26 +00001276 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001277 if (const ComplexType *CT = V->getType()->getAsComplexType())
1278 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001279
1280 // Otherwise they pass through real integer and floating point types here.
1281 if (V->getType()->isArithmeticType())
1282 return V->getType();
1283
1284 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001285 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1286 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001287 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001288}
1289
1290
Chris Lattner4b009652007-07-25 00:24:17 +00001291
Sebastian Redl8b769972009-01-19 00:08:26 +00001292Action::OwningExprResult
1293Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1294 tok::TokenKind Kind, ExprArg Input) {
1295 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001296
Chris Lattner4b009652007-07-25 00:24:17 +00001297 UnaryOperator::Opcode Opc;
1298 switch (Kind) {
1299 default: assert(0 && "Unknown unary op!");
1300 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1301 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1302 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001303
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001304 if (getLangOptions().CPlusPlus &&
1305 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1306 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001307 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001308 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1309
1310 // C++ [over.inc]p1:
1311 //
1312 // [...] If the function is a member function with one
1313 // parameter (which shall be of type int) or a non-member
1314 // function with two parameters (the second of which shall be
1315 // of type int), it defines the postfix increment operator ++
1316 // for objects of that type. When the postfix increment is
1317 // called as a result of using the ++ operator, the int
1318 // argument will have value zero.
1319 Expr *Args[2] = {
1320 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001321 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1322 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001323 };
1324
1325 // Build the candidate set for overloading
1326 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001327 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1328 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001329
1330 // Perform overload resolution.
1331 OverloadCandidateSet::iterator Best;
1332 switch (BestViableFunction(CandidateSet, Best)) {
1333 case OR_Success: {
1334 // We found a built-in operator or an overloaded operator.
1335 FunctionDecl *FnDecl = Best->Function;
1336
1337 if (FnDecl) {
1338 // We matched an overloaded operator. Build a call to that
1339 // operator.
1340
1341 // Convert the arguments.
1342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1343 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001344 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001345 } else {
1346 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001347 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001348 FnDecl->getParamDecl(0)->getType(),
1349 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001350 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001351 }
1352
1353 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001354 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001355 = FnDecl->getType()->getAsFunctionType()->getResultType();
1356 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001357
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001358 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001359 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001360 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001361 UsualUnaryConversions(FnExpr);
1362
Sebastian Redl8b769972009-01-19 00:08:26 +00001363 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001364 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1365 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001366 } else {
1367 // We matched a built-in operator. Convert the arguments, then
1368 // break out so that we will build the appropriate built-in
1369 // operator node.
1370 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1371 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001372 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001373
1374 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001375 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001376 }
1377
1378 case OR_No_Viable_Function:
1379 // No viable function; fall through to handling this as a
1380 // built-in operator, which will produce an error message for us.
1381 break;
1382
1383 case OR_Ambiguous:
1384 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1385 << UnaryOperator::getOpcodeStr(Opc)
1386 << Arg->getSourceRange();
1387 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001388 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001389
1390 case OR_Deleted:
1391 Diag(OpLoc, diag::err_ovl_deleted_oper)
1392 << Best->Function->isDeleted()
1393 << UnaryOperator::getOpcodeStr(Opc)
1394 << Arg->getSourceRange();
1395 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1396 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001397 }
1398
1399 // Either we found no viable overloaded operator or we matched a
1400 // built-in operator. In either case, fall through to trying to
1401 // build a built-in operation.
1402 }
1403
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001404 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1405 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001406 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001407 return ExprError();
1408 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001409 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001410}
1411
Sebastian Redl8b769972009-01-19 00:08:26 +00001412Action::OwningExprResult
1413Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1414 ExprArg Idx, SourceLocation RLoc) {
1415 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1416 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001417
Douglas Gregor80723c52008-11-19 17:17:41 +00001418 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001419 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001420 LHSExp->getType()->isEnumeralType() ||
1421 RHSExp->getType()->isRecordType() ||
1422 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001423 // Add the appropriate overloaded operators (C++ [over.match.oper])
1424 // to the candidate set.
1425 OverloadCandidateSet CandidateSet;
1426 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001427 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1428 SourceRange(LLoc, RLoc)))
1429 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001430
Douglas Gregor80723c52008-11-19 17:17:41 +00001431 // Perform overload resolution.
1432 OverloadCandidateSet::iterator Best;
1433 switch (BestViableFunction(CandidateSet, Best)) {
1434 case OR_Success: {
1435 // We found a built-in operator or an overloaded operator.
1436 FunctionDecl *FnDecl = Best->Function;
1437
1438 if (FnDecl) {
1439 // We matched an overloaded operator. Build a call to that
1440 // operator.
1441
1442 // Convert the arguments.
1443 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1444 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1445 PerformCopyInitialization(RHSExp,
1446 FnDecl->getParamDecl(0)->getType(),
1447 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001448 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001449 } else {
1450 // Convert the arguments.
1451 if (PerformCopyInitialization(LHSExp,
1452 FnDecl->getParamDecl(0)->getType(),
1453 "passing") ||
1454 PerformCopyInitialization(RHSExp,
1455 FnDecl->getParamDecl(1)->getType(),
1456 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001457 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001458 }
1459
1460 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001461 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001462 = FnDecl->getType()->getAsFunctionType()->getResultType();
1463 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001464
Douglas Gregor80723c52008-11-19 17:17:41 +00001465 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001466 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1467 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001468 UsualUnaryConversions(FnExpr);
1469
Sebastian Redl8b769972009-01-19 00:08:26 +00001470 Base.release();
1471 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001472 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001473 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001474 } else {
1475 // We matched a built-in operator. Convert the arguments, then
1476 // break out so that we will build the appropriate built-in
1477 // operator node.
1478 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1479 "passing") ||
1480 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1481 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001482 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001483
1484 break;
1485 }
1486 }
1487
1488 case OR_No_Viable_Function:
1489 // No viable function; fall through to handling this as a
1490 // built-in operator, which will produce an error message for us.
1491 break;
1492
1493 case OR_Ambiguous:
1494 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1495 << "[]"
1496 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1497 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001498 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001499
1500 case OR_Deleted:
1501 Diag(LLoc, diag::err_ovl_deleted_oper)
1502 << Best->Function->isDeleted()
1503 << "[]"
1504 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1505 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1506 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001507 }
1508
1509 // Either we found no viable overloaded operator or we matched a
1510 // built-in operator. In either case, fall through to trying to
1511 // build a built-in operation.
1512 }
1513
Chris Lattner4b009652007-07-25 00:24:17 +00001514 // Perform default conversions.
1515 DefaultFunctionArrayConversion(LHSExp);
1516 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001517
Chris Lattner4b009652007-07-25 00:24:17 +00001518 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1519
1520 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001521 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001522 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001523 // and index from the expression types.
1524 Expr *BaseExpr, *IndexExpr;
1525 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001526 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1527 BaseExpr = LHSExp;
1528 IndexExpr = RHSExp;
1529 ResultType = Context.DependentTy;
1530 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001531 BaseExpr = LHSExp;
1532 IndexExpr = RHSExp;
1533 // FIXME: need to deal with const...
1534 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001535 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001536 // Handle the uncommon case of "123[Ptr]".
1537 BaseExpr = RHSExp;
1538 IndexExpr = LHSExp;
1539 // FIXME: need to deal with const...
1540 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001541 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1542 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001543 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001544
Chris Lattner4b009652007-07-25 00:24:17 +00001545 // FIXME: need to deal with const...
1546 ResultType = VTy->getElementType();
1547 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001548 return ExprError(Diag(LHSExp->getLocStart(),
1549 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1550 }
Chris Lattner4b009652007-07-25 00:24:17 +00001551 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001552 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001553 return ExprError(Diag(IndexExpr->getLocStart(),
1554 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001555
1556 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1557 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001558 // void (*)(int)) and pointers to incomplete types. Functions are not
1559 // objects in C99.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001560 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001561 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001562 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001563 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001564
Sebastian Redl8b769972009-01-19 00:08:26 +00001565 Base.release();
1566 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001567 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001568 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001569}
1570
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001571QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001572CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001573 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001574 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001575
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001576 // The vector accessor can't exceed the number of elements.
1577 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001578
Mike Stump9afab102009-02-19 03:04:26 +00001579 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001580 // special names that indicate a subset of exactly half the elements are
1581 // to be selected.
1582 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001583
Nate Begeman1486b502009-01-18 01:47:54 +00001584 // This flag determines whether or not CompName has an 's' char prefix,
1585 // indicating that it is a string of hex values to be used as vector indices.
1586 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001587
1588 // Check that we've found one of the special components, or that the component
1589 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001590 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001591 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1592 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001593 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001594 do
1595 compStr++;
1596 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001597 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001598 do
1599 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001600 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001601 }
Nate Begeman1486b502009-01-18 01:47:54 +00001602
Mike Stump9afab102009-02-19 03:04:26 +00001603 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001604 // We didn't get to the end of the string. This means the component names
1605 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001606 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1607 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001608 return QualType();
1609 }
Mike Stump9afab102009-02-19 03:04:26 +00001610
Nate Begeman1486b502009-01-18 01:47:54 +00001611 // Ensure no component accessor exceeds the width of the vector type it
1612 // operates on.
1613 if (!HalvingSwizzle) {
1614 compStr = CompName.getName();
1615
1616 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001617 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001618
1619 while (*compStr) {
1620 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1621 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1622 << baseType << SourceRange(CompLoc);
1623 return QualType();
1624 }
1625 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001626 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001627
Nate Begeman1486b502009-01-18 01:47:54 +00001628 // If this is a halving swizzle, verify that the base type has an even
1629 // number of elements.
1630 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001631 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001632 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001633 return QualType();
1634 }
Mike Stump9afab102009-02-19 03:04:26 +00001635
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001636 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001637 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001638 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001639 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001640 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001641 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1642 : CompName.getLength();
1643 if (HexSwizzle)
1644 CompSize--;
1645
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001646 if (CompSize == 1)
1647 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001648
Nate Begemanaf6ed502008-04-18 23:10:10 +00001649 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001650 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001651 // diagostics look bad. We want extended vector types to appear built-in.
1652 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1653 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1654 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001655 }
1656 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001657}
1658
Chris Lattner2cb744b2009-02-15 22:43:40 +00001659
Sebastian Redl8b769972009-01-19 00:08:26 +00001660Action::OwningExprResult
1661Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1662 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001663 IdentifierInfo &Member,
1664 DeclTy *ObjCImpDecl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001665 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001666 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001667
1668 // Perform default conversions.
1669 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001670
Steve Naroff2cb66382007-07-26 03:11:44 +00001671 QualType BaseType = BaseExpr->getType();
1672 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001673
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001674 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1675 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001676 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001677 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001678 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001679 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001680 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1681 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001682 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001683 return ExprError(Diag(MemberLoc,
1684 diag::err_typecheck_member_reference_arrow)
1685 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001686 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001687
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001688 // Handle field access to simple records. This also handles access to fields
1689 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001690 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001691 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00001692 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001693 diag::err_typecheck_incomplete_tag,
1694 BaseExpr->getSourceRange()))
1695 return ExprError();
1696
Steve Naroff2cb66382007-07-26 03:11:44 +00001697 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001698 // FIXME: Qualified name lookup for C++ is a bit more complicated
1699 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001700 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001701 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001702 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001703
Douglas Gregor09be81b2009-02-04 17:27:36 +00001704 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001705 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001706 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1707 << &Member << BaseExpr->getSourceRange());
1708 else if (Result.isAmbiguous()) {
1709 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1710 MemberLoc, BaseExpr->getSourceRange());
1711 return ExprError();
1712 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001713 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001714
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001715 // If the decl being referenced had an error, return an error for this
1716 // sub-expr without emitting another error, in order to avoid cascading
1717 // error cases.
1718 if (MemberDecl->isInvalidDecl())
1719 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001720
Douglas Gregoraa57e862009-02-18 21:56:37 +00001721 // Check the use of this field
1722 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1723 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001724
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001725 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001726 // We may have found a field within an anonymous union or struct
1727 // (C++ [class.union]).
1728 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001729 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001730 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001731
Douglas Gregor82d44772008-12-20 23:49:58 +00001732 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1733 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001734 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001735 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1736 MemberType = Ref->getPointeeType();
1737 else {
1738 unsigned combinedQualifiers =
1739 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001740 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001741 combinedQualifiers &= ~QualType::Const;
1742 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1743 }
Eli Friedman76b49832008-02-06 22:48:16 +00001744
Steve Naroff774e4152009-01-21 00:14:39 +00001745 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1746 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001747 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001748 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001749 Var, MemberLoc,
1750 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001751 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001752 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001753 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001754 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001755 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001756 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001757 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001758 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001759 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1760 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001761 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001762 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1763 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001764
Douglas Gregor82d44772008-12-20 23:49:58 +00001765 // We found a declaration kind that we didn't expect. This is a
1766 // generic error message that tells the user that she can't refer
1767 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001768 return ExprError(Diag(MemberLoc,
1769 diag::err_typecheck_member_reference_unknown)
1770 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001771 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001772
Chris Lattnere9d71612008-07-21 04:59:05 +00001773 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1774 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001775 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001776 ObjCInterfaceDecl *ClassDeclared;
1777 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1778 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001779 // If the decl being referenced had an error, return an error for this
1780 // sub-expr without emitting another error, in order to avoid cascading
1781 // error cases.
1782 if (IV->isInvalidDecl())
1783 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001784
1785 // Check whether we can reference this field.
1786 if (DiagnoseUseOfDecl(IV, MemberLoc))
1787 return ExprError();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001788 if (IV->getAccessControl() != ObjCIvarDecl::Public) {
1789 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1790 if (ObjCMethodDecl *MD = getCurMethodDecl())
1791 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001792 else if (ObjCImpDecl && getCurFunctionDecl()) {
1793 // Case of a c-function declared inside an objc implementation.
1794 // FIXME: For a c-style function nested inside an objc implementation
1795 // class, there is no implementation context available, so we pass down
1796 // the context as argument to this routine. Ideally, this context need
1797 // be passed down in the AST node and somehow calculated from the AST
1798 // for a function decl.
1799 Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl);
1800 if (ObjCImplementationDecl *IMPD =
1801 dyn_cast<ObjCImplementationDecl>(ImplDecl))
1802 ClassOfMethodDecl = IMPD->getClassInterface();
1803 else if (ObjCCategoryImplDecl* CatImplClass =
1804 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1805 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00001806 }
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001807 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001808 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001809 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001810 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1811 }
1812 // @protected
1813 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1814 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1815 }
Mike Stump9afab102009-02-19 03:04:26 +00001816
1817 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001818 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001819 OpKind == tok::arrow);
1820 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001821 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001822 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001823 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1824 << IFTy->getDecl()->getDeclName() << &Member
1825 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001826 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001827
Chris Lattnere9d71612008-07-21 04:59:05 +00001828 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1829 // pointer to a (potentially qualified) interface type.
1830 const PointerType *PTy;
1831 const ObjCInterfaceType *IFTy;
1832 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1833 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1834 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001835
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001836 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001837 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001838 // Check whether we can reference this property.
1839 if (DiagnoseUseOfDecl(PD, MemberLoc))
1840 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001841
Steve Naroff774e4152009-01-21 00:14:39 +00001842 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001843 MemberLoc, BaseExpr));
1844 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001845
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001846 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001847 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1848 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001849 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001850 // Check whether we can reference this property.
1851 if (DiagnoseUseOfDecl(PD, MemberLoc))
1852 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001853
Steve Naroff774e4152009-01-21 00:14:39 +00001854 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001855 MemberLoc, BaseExpr));
1856 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001857
1858 // If that failed, look for an "implicit" property by seeing if the nullary
1859 // selector is implemented.
1860
1861 // FIXME: The logic for looking up nullary and unary selectors should be
1862 // shared with the code in ActOnInstanceMessage.
1863
1864 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1865 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001866
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001867 // If this reference is in an @implementation, check for 'private' methods.
1868 if (!Getter)
1869 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1870 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001871 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001872 ObjCImplementations[ClassDecl->getIdentifier()])
1873 Getter = ImpDecl->getInstanceMethod(Sel);
1874
Steve Naroff04151f32008-10-22 19:16:27 +00001875 // Look through local category implementations associated with the class.
1876 if (!Getter) {
1877 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1878 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1879 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1880 }
1881 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001882 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001883 // Check if we can reference this property.
1884 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1885 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00001886 }
1887 // If we found a getter then this may be a valid dot-reference, we
1888 // will look for the matching setter, in case it is needed.
1889 Selector SetterSel =
1890 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1891 PP.getSelectorTable(), &Member);
1892 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1893 if (!Setter) {
1894 // If this reference is in an @implementation, also check for 'private'
1895 // methods.
1896 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1897 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1898 if (ObjCImplementationDecl *ImpDecl =
1899 ObjCImplementations[ClassDecl->getIdentifier()])
1900 Setter = ImpDecl->getInstanceMethod(SetterSel);
1901 }
1902 // Look through local category implementations associated with the class.
1903 if (!Setter) {
1904 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1905 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1906 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001907 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001908 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001909
Steve Naroffdede0c92009-03-11 13:48:17 +00001910 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1911 return ExprError();
1912
1913 if (Getter || Setter) {
1914 QualType PType;
1915
1916 if (Getter)
1917 PType = Getter->getResultType();
1918 else {
1919 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
1920 E = Setter->param_end(); PI != E; ++PI)
1921 PType = (*PI)->getType();
1922 }
1923 // FIXME: we must check that the setter has property type.
1924 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
1925 Setter, MemberLoc, BaseExpr));
1926 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001927 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1928 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001929 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001930 // Handle properties on qualified "id" protocols.
1931 const ObjCQualifiedIdType *QIdTy;
1932 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1933 // Check protocols on qualified interfaces.
1934 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001935 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001936 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001937 // Check the use of this declaration
1938 if (DiagnoseUseOfDecl(PD, MemberLoc))
1939 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001940
Steve Naroff774e4152009-01-21 00:14:39 +00001941 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001942 MemberLoc, BaseExpr));
1943 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001944 // Also must look for a getter name which uses property syntax.
1945 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1946 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001947 // Check the use of this method.
1948 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1949 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001950
1951 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001952 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001953 }
1954 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001955
1956 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1957 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001958 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00001959 // Handle properties on ObjC 'Class' types.
1960 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
1961 // Also must look for a getter name which uses property syntax.
1962 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1963 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1964 ObjCMethodDecl *OMD;
1965 // FIXME: need to also look locally in the implementation.
1966 if ((OMD = MD->getClassInterface()->lookupClassMethod(Sel))) {
1967 // Check the use of this method.
1968 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1969 return ExprError();
1970
1971 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1972 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
1973 }
1974 }
1975 }
1976
Chris Lattnera57cf472008-07-21 04:28:12 +00001977 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001978 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001979 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1980 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001981 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001982 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00001983 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001984 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001985
1986 return ExprError(Diag(MemberLoc,
1987 diag::err_typecheck_member_reference_struct_union)
1988 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001989}
1990
Douglas Gregor3257fb52008-12-22 05:46:06 +00001991/// ConvertArgumentsForCall - Converts the arguments specified in
1992/// Args/NumArgs to the parameter types of the function FDecl with
1993/// function prototype Proto. Call is the call expression itself, and
1994/// Fn is the function expression. For a C++ member function, this
1995/// routine does not attempt to convert the object argument. Returns
1996/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00001997bool
1998Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001999 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002000 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002001 Expr **Args, unsigned NumArgs,
2002 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002003 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002004 // assignment, to the types of the corresponding parameter, ...
2005 unsigned NumArgsInProto = Proto->getNumArgs();
2006 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002007 bool Invalid = false;
2008
Douglas Gregor3257fb52008-12-22 05:46:06 +00002009 // If too few arguments are available (and we don't have default
2010 // arguments for the remaining parameters), don't make the call.
2011 if (NumArgs < NumArgsInProto) {
2012 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2013 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2014 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2015 // Use default arguments for missing arguments
2016 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002017 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002018 }
2019
2020 // If too many are passed and not variadic, error on the extras and drop
2021 // them.
2022 if (NumArgs > NumArgsInProto) {
2023 if (!Proto->isVariadic()) {
2024 Diag(Args[NumArgsInProto]->getLocStart(),
2025 diag::err_typecheck_call_too_many_args)
2026 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2027 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2028 Args[NumArgs-1]->getLocEnd());
2029 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002030 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002031 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002032 }
2033 NumArgsToCheck = NumArgsInProto;
2034 }
Mike Stump9afab102009-02-19 03:04:26 +00002035
Douglas Gregor3257fb52008-12-22 05:46:06 +00002036 // Continue to check argument types (even if we have too few/many args).
2037 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2038 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002039
Douglas Gregor3257fb52008-12-22 05:46:06 +00002040 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002041 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002042 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002043
2044 // Pass the argument.
2045 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2046 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002047 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002048 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002049 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002050 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002051
Douglas Gregor3257fb52008-12-22 05:46:06 +00002052 Call->setArg(i, Arg);
2053 }
Mike Stump9afab102009-02-19 03:04:26 +00002054
Douglas Gregor3257fb52008-12-22 05:46:06 +00002055 // If this is a variadic call, handle args passed through "...".
2056 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002057 VariadicCallType CallType = VariadicFunction;
2058 if (Fn->getType()->isBlockPointerType())
2059 CallType = VariadicBlock; // Block
2060 else if (isa<MemberExpr>(Fn))
2061 CallType = VariadicMethod;
2062
Douglas Gregor3257fb52008-12-22 05:46:06 +00002063 // Promote the arguments (C99 6.5.2.2p7).
2064 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2065 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002066 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002067 Call->setArg(i, Arg);
2068 }
2069 }
2070
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002071 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002072}
2073
Steve Naroff87d58b42007-09-16 03:34:24 +00002074/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002075/// This provides the location of the left/right parens and a list of comma
2076/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002077Action::OwningExprResult
2078Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2079 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002080 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002081 unsigned NumArgs = args.size();
2082 Expr *Fn = static_cast<Expr *>(fn.release());
2083 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002084 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002085 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002086 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002087
Douglas Gregor3257fb52008-12-22 05:46:06 +00002088 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002089 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002090 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002091 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2092 bool Dependent = false;
2093 if (Fn->isTypeDependent())
2094 Dependent = true;
2095 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2096 Dependent = true;
2097
2098 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002099 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002100 Context.DependentTy, RParenLoc));
2101
2102 // Determine whether this is a call to an object (C++ [over.call.object]).
2103 if (Fn->getType()->isRecordType())
2104 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2105 CommaLocs, RParenLoc));
2106
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002107 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002108 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2109 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2110 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002111 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2112 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002113 }
2114
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002115 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002116 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002117 Expr *FnExpr = Fn;
2118 bool ADL = true;
2119 while (true) {
2120 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2121 FnExpr = IcExpr->getSubExpr();
2122 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002123 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002124 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002125 ADL = false;
2126 FnExpr = PExpr->getSubExpr();
2127 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002128 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002129 == UnaryOperator::AddrOf) {
2130 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002131 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2132 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2133 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2134 break;
Mike Stump9afab102009-02-19 03:04:26 +00002135 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002136 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2137 UnqualifiedName = DepName->getName();
2138 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002139 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002140 // Any kind of name that does not refer to a declaration (or
2141 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2142 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002143 break;
2144 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002145 }
Mike Stump9afab102009-02-19 03:04:26 +00002146
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002147 OverloadedFunctionDecl *Ovl = 0;
2148 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002149 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002150 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2151 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002152
Douglas Gregorfcb19192009-02-11 23:02:49 +00002153 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002154 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002155 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002156 ADL = false;
2157
Douglas Gregorfcb19192009-02-11 23:02:49 +00002158 // We don't perform ADL in C.
2159 if (!getLangOptions().CPlusPlus)
2160 ADL = false;
2161
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002162 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002163 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2164 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002165 NumArgs, CommaLocs, RParenLoc, ADL);
2166 if (!FDecl)
2167 return ExprError();
2168
2169 // Update Fn to refer to the actual function selected.
2170 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002171 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002172 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stump9afab102009-02-19 03:04:26 +00002173 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2174 QDRExpr->getLocation(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002175 false, false,
2176 QDRExpr->getSourceRange().getBegin());
2177 else
Mike Stump9afab102009-02-19 03:04:26 +00002178 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002179 Fn->getSourceRange().getBegin());
2180 Fn->Destroy(Context);
2181 Fn = NewFn;
2182 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002183 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002184
2185 // Promote the function operand.
2186 UsualUnaryConversions(Fn);
2187
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002188 // Make the call expr early, before semantic checks. This guarantees cleanup
2189 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002190 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2191 Args, NumArgs,
2192 Context.BoolTy,
2193 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002194
Steve Naroffd6163f32008-09-05 22:11:13 +00002195 const FunctionType *FuncT;
2196 if (!Fn->getType()->isBlockPointerType()) {
2197 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2198 // have type pointer to function".
2199 const PointerType *PT = Fn->getType()->getAsPointerType();
2200 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002201 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2202 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002203 FuncT = PT->getPointeeType()->getAsFunctionType();
2204 } else { // This is a block call.
2205 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2206 getAsFunctionType();
2207 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002208 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002209 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2210 << Fn->getType() << Fn->getSourceRange());
2211
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002212 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002213 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002214
Douglas Gregor4fa58902009-02-26 23:50:07 +00002215 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002216 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002217 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002218 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002219 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002220 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002221
Steve Naroffdb65e052007-08-28 23:30:39 +00002222 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002223 for (unsigned i = 0; i != NumArgs; i++) {
2224 Expr *Arg = Args[i];
2225 DefaultArgumentPromotion(Arg);
2226 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002227 }
Chris Lattner4b009652007-07-25 00:24:17 +00002228 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002229
Douglas Gregor3257fb52008-12-22 05:46:06 +00002230 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2231 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002232 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2233 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002234
Chris Lattner2e64c072007-08-10 20:18:51 +00002235 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002236 if (FDecl)
2237 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002238
Sebastian Redl8b769972009-01-19 00:08:26 +00002239 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002240}
2241
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002242Action::OwningExprResult
2243Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2244 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002245 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002246 QualType literalType = QualType::getFromOpaquePtr(Ty);
2247 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002248 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002249 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002250
Eli Friedman8c2173d2008-05-20 05:22:08 +00002251 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002252 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002253 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2254 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregorc84d8932009-03-09 16:13:40 +00002255 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002256 diag::err_typecheck_decl_incomplete_type,
2257 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002258 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002259
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002260 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002261 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002262 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002263
Chris Lattnere5cb5862008-12-04 23:50:19 +00002264 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002265 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002266 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002267 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002268 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002269 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002270 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002271 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002272}
2273
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002274Action::OwningExprResult
2275Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2276 InitListDesignations &Designators,
2277 SourceLocation RBraceLoc) {
2278 unsigned NumInit = initlist.size();
2279 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002280
Steve Naroff0acc9c92007-09-15 18:49:24 +00002281 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002282 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002283
Mike Stump9afab102009-02-19 03:04:26 +00002284 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002285 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002286 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002287 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002288}
2289
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002290/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002291bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002292 UsualUnaryConversions(castExpr);
2293
2294 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2295 // type needs to be scalar.
2296 if (castType->isVoidType()) {
2297 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002298 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2299 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002300 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002301 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2302 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2303 (castType->isStructureType() || castType->isUnionType())) {
2304 // GCC struct/union extension: allow cast to self.
2305 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2306 << castType << castExpr->getSourceRange();
2307 } else if (castType->isUnionType()) {
2308 // GCC cast to union extension
2309 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2310 RecordDecl::field_iterator Field, FieldEnd;
2311 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2312 Field != FieldEnd; ++Field) {
2313 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2314 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2315 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2316 << castExpr->getSourceRange();
2317 break;
2318 }
2319 }
2320 if (Field == FieldEnd)
2321 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2322 << castExpr->getType() << castExpr->getSourceRange();
2323 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002324 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002325 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002326 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002327 }
Mike Stump9afab102009-02-19 03:04:26 +00002328 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002329 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002330 return Diag(castExpr->getLocStart(),
2331 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002332 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002333 } else if (castExpr->getType()->isVectorType()) {
2334 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2335 return true;
2336 } else if (castType->isVectorType()) {
2337 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2338 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002339 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Chris Lattner2e9eb042009-03-05 23:09:00 +00002340 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002341 }
2342 return false;
2343}
2344
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002345bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002346 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002347
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002348 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002349 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002350 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002351 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002352 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002353 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002354 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002355 } else
2356 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002357 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002358 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002359
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002360 return false;
2361}
2362
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002363Action::OwningExprResult
2364Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2365 SourceLocation RParenLoc, ExprArg Op) {
2366 assert((Ty != 0) && (Op.get() != 0) &&
2367 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002368
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002369 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002370 QualType castType = QualType::getFromOpaquePtr(Ty);
2371
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002372 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002373 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002374 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002375 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002376}
2377
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002378/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2379/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002380/// C99 6.5.15
2381QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2382 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002383 UsualUnaryConversions(Cond);
2384 UsualUnaryConversions(LHS);
2385 UsualUnaryConversions(RHS);
2386 QualType CondTy = Cond->getType();
2387 QualType LHSTy = LHS->getType();
2388 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002389
2390 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002391 if (!Cond->isTypeDependent()) {
2392 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2393 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2394 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002395 return QualType();
2396 }
Chris Lattner4b009652007-07-25 00:24:17 +00002397 }
Mike Stump9afab102009-02-19 03:04:26 +00002398
Chris Lattner992ae932008-01-06 22:42:25 +00002399 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002400 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002401 return Context.DependentTy;
2402
Chris Lattner992ae932008-01-06 22:42:25 +00002403 // If both operands have arithmetic type, do the usual arithmetic conversions
2404 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002405 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2406 UsualArithmeticConversions(LHS, RHS);
2407 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002408 }
Mike Stump9afab102009-02-19 03:04:26 +00002409
Chris Lattner992ae932008-01-06 22:42:25 +00002410 // If both operands are the same structure or union type, the result is that
2411 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002412 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2413 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002414 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002415 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002416 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002417 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002418 }
Mike Stump9afab102009-02-19 03:04:26 +00002419
Chris Lattner992ae932008-01-06 22:42:25 +00002420 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002421 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002422 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2423 if (!LHSTy->isVoidType())
2424 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2425 << RHS->getSourceRange();
2426 if (!RHSTy->isVoidType())
2427 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2428 << LHS->getSourceRange();
2429 ImpCastExprToType(LHS, Context.VoidTy);
2430 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002431 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002432 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002433 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2434 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002435 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2436 Context.isObjCObjectPointerType(LHSTy)) &&
2437 RHS->isNullPointerConstant(Context)) {
2438 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2439 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002440 }
Chris Lattnere2897262009-02-18 04:28:32 +00002441 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2442 Context.isObjCObjectPointerType(RHSTy)) &&
2443 LHS->isNullPointerConstant(Context)) {
2444 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2445 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002446 }
Mike Stump9afab102009-02-19 03:04:26 +00002447
Chris Lattner0ac51632008-01-06 22:50:31 +00002448 // Handle the case where both operands are pointers before we handle null
2449 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002450 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2451 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002452 // get the "pointed to" types
2453 QualType lhptee = LHSPT->getPointeeType();
2454 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002455
Chris Lattner71225142007-07-31 21:27:01 +00002456 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2457 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002458 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002459 // Figure out necessary qualifiers (C99 6.5.15p6)
2460 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002461 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002462 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2463 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002464 return destType;
2465 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002466 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002467 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002468 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002469 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2470 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002471 return destType;
2472 }
Chris Lattner4b009652007-07-25 00:24:17 +00002473
Chris Lattner9c039b52009-02-18 04:38:20 +00002474 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002475 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002476 return LHSTy;
2477 }
Mike Stump9afab102009-02-19 03:04:26 +00002478
Chris Lattnere2897262009-02-18 04:28:32 +00002479 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002480
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002481 // If either type is an Objective-C object type then check
2482 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002483 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002484 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002485 // If both operands are interfaces and either operand can be
2486 // assigned to the other, use that type as the composite
2487 // type. This allows
2488 // xxx ? (A*) a : (B*) b
2489 // where B is a subclass of A.
2490 //
2491 // Additionally, as for assignment, if either type is 'id'
2492 // allow silent coercion. Finally, if the types are
2493 // incompatible then make sure to use 'id' as the composite
2494 // type so the result is acceptable for sending messages to.
2495
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002496 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002497 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002498 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2499 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2500 if (LHSIface && RHSIface &&
2501 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002502 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002503 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002504 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002505 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002506 } else if (Context.isObjCIdStructType(lhptee) ||
2507 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002508 compositeType = Context.getObjCIdType();
2509 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002510 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002511 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002512 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002513 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002514 ImpCastExprToType(LHS, incompatTy);
2515 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002516 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002517 }
Mike Stump9afab102009-02-19 03:04:26 +00002518 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002519 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002520 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2521 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002522 // In this situation, we assume void* type. No especially good
2523 // reason, but this is what gcc does, and we do have to pick
2524 // to get a consistent AST.
2525 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002526 ImpCastExprToType(LHS, incompatTy);
2527 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002528 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002529 }
2530 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002531 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2532 // differently qualified versions of compatible types, the result type is
2533 // a pointer to an appropriately qualified version of the *composite*
2534 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002535 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002536 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002537 ImpCastExprToType(LHS, compositeType);
2538 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002539 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002540 }
Chris Lattner4b009652007-07-25 00:24:17 +00002541 }
Mike Stump9afab102009-02-19 03:04:26 +00002542
Chris Lattner9c039b52009-02-18 04:38:20 +00002543 // Selection between block pointer types is ok as long as they are the same.
2544 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2545 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2546 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002547
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002548 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2549 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002550 // id with statically typed objects).
2551 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002552 // GCC allows qualified id and any Objective-C type to devolve to
2553 // id. Currently localizing to here until clear this should be
2554 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002555 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002556 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002557 Context.isObjCObjectPointerType(RHSTy)) ||
2558 (RHSTy->isObjCQualifiedIdType() &&
2559 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002560 // FIXME: This is not the correct composite type. This only
2561 // happens to work because id can more or less be used anywhere,
2562 // however this may change the type of method sends.
2563 // FIXME: gcc adds some type-checking of the arguments and emits
2564 // (confusing) incompatible comparison warnings in some
2565 // cases. Investigate.
2566 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002567 ImpCastExprToType(LHS, compositeType);
2568 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002569 return compositeType;
2570 }
2571 }
2572
Chris Lattner992ae932008-01-06 22:42:25 +00002573 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002574 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2575 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002576 return QualType();
2577}
2578
Steve Naroff87d58b42007-09-16 03:34:24 +00002579/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002580/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002581Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2582 SourceLocation ColonLoc,
2583 ExprArg Cond, ExprArg LHS,
2584 ExprArg RHS) {
2585 Expr *CondExpr = (Expr *) Cond.get();
2586 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002587
2588 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2589 // was the condition.
2590 bool isLHSNull = LHSExpr == 0;
2591 if (isLHSNull)
2592 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002593
2594 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002595 RHSExpr, QuestionLoc);
2596 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002597 return ExprError();
2598
2599 Cond.release();
2600 LHS.release();
2601 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002602 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002603 isLHSNull ? 0 : LHSExpr,
2604 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002605}
2606
Chris Lattner4b009652007-07-25 00:24:17 +00002607
2608// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002609// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002610// routine is it effectively iqnores the qualifiers on the top level pointee.
2611// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2612// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002613Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002614Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2615 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002616
Chris Lattner4b009652007-07-25 00:24:17 +00002617 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002618 lhptee = lhsType->getAsPointerType()->getPointeeType();
2619 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002620
Chris Lattner4b009652007-07-25 00:24:17 +00002621 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002622 lhptee = Context.getCanonicalType(lhptee);
2623 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002624
Chris Lattner005ed752008-01-04 18:04:52 +00002625 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002626
2627 // C99 6.5.16.1p1: This following citation is common to constraints
2628 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2629 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002630 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002631 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002632 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002633
Mike Stump9afab102009-02-19 03:04:26 +00002634 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2635 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002636 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002637 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002638 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002639 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002640
Chris Lattner4ca3d772008-01-03 22:56:36 +00002641 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002642 assert(rhptee->isFunctionType());
2643 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002644 }
Mike Stump9afab102009-02-19 03:04:26 +00002645
Chris Lattner4ca3d772008-01-03 22:56:36 +00002646 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002647 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002648 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002649
2650 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002651 assert(lhptee->isFunctionType());
2652 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002653 }
Mike Stump9afab102009-02-19 03:04:26 +00002654 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002655 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002656 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002657 rhptee.getUnqualifiedType()))
2658 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002659 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002660}
2661
Steve Naroff3454b6c2008-09-04 15:10:53 +00002662/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2663/// block pointer types are compatible or whether a block and normal pointer
2664/// are compatible. It is more restrict than comparing two function pointer
2665// types.
Mike Stump9afab102009-02-19 03:04:26 +00002666Sema::AssignConvertType
2667Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002668 QualType rhsType) {
2669 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002670
Steve Naroff3454b6c2008-09-04 15:10:53 +00002671 // get the "pointed to" type (ignoring qualifiers at the top level)
2672 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002673 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2674
Steve Naroff3454b6c2008-09-04 15:10:53 +00002675 // make sure we operate on the canonical type
2676 lhptee = Context.getCanonicalType(lhptee);
2677 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002678
Steve Naroff3454b6c2008-09-04 15:10:53 +00002679 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002680
Steve Naroff3454b6c2008-09-04 15:10:53 +00002681 // For blocks we enforce that qualifiers are identical.
2682 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2683 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002684
Steve Naroff3454b6c2008-09-04 15:10:53 +00002685 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002686 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002687 return ConvTy;
2688}
2689
Mike Stump9afab102009-02-19 03:04:26 +00002690/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2691/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002692/// pointers. Here are some objectionable examples that GCC considers warnings:
2693///
2694/// int a, *pint;
2695/// short *pshort;
2696/// struct foo *pfoo;
2697///
2698/// pint = pshort; // warning: assignment from incompatible pointer type
2699/// a = pint; // warning: assignment makes integer from pointer without a cast
2700/// pint = a; // warning: assignment makes pointer from integer without a cast
2701/// pint = pfoo; // warning: assignment from incompatible pointer type
2702///
2703/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002704/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002705///
Chris Lattner005ed752008-01-04 18:04:52 +00002706Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002707Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002708 // Get canonical types. We're not formatting these types, just comparing
2709 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002710 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2711 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002712
2713 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002714 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002715
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002716 // If the left-hand side is a reference type, then we are in a
2717 // (rare!) case where we've allowed the use of references in C,
2718 // e.g., as a parameter type in a built-in function. In this case,
2719 // just make sure that the type referenced is compatible with the
2720 // right-hand side type. The caller is responsible for adjusting
2721 // lhsType so that the resulting expression does not have reference
2722 // type.
2723 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2724 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002725 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002726 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002727 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002728
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002729 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2730 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002731 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002732 // Relax integer conversions like we do for pointers below.
2733 if (rhsType->isIntegerType())
2734 return IntToPointer;
2735 if (lhsType->isIntegerType())
2736 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002737 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002738 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002739
Nate Begemanc5f0f652008-07-14 18:02:46 +00002740 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002741 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002742 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2743 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002744 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002745
Nate Begemanc5f0f652008-07-14 18:02:46 +00002746 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002747 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002748 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002749 if (getLangOptions().LaxVectorConversions &&
2750 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002751 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002752 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002753 }
2754 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002755 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002756
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002757 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002758 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002759
Chris Lattner390564e2008-04-07 06:49:41 +00002760 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002761 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002762 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002763
Chris Lattner390564e2008-04-07 06:49:41 +00002764 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002765 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002766
Steve Naroffa982c712008-09-29 18:10:17 +00002767 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002768 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002769 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002770
2771 // Treat block pointers as objects.
2772 if (getLangOptions().ObjC1 &&
2773 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2774 return Compatible;
2775 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002776 return Incompatible;
2777 }
2778
2779 if (isa<BlockPointerType>(lhsType)) {
2780 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002781 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002782
Steve Naroffa982c712008-09-29 18:10:17 +00002783 // Treat block pointers as objects.
2784 if (getLangOptions().ObjC1 &&
2785 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2786 return Compatible;
2787
Steve Naroff3454b6c2008-09-04 15:10:53 +00002788 if (rhsType->isBlockPointerType())
2789 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002790
Steve Naroff3454b6c2008-09-04 15:10:53 +00002791 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2792 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002793 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002794 }
Chris Lattner1853da22008-01-04 23:18:45 +00002795 return Incompatible;
2796 }
2797
Chris Lattner390564e2008-04-07 06:49:41 +00002798 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002799 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002800 if (lhsType == Context.BoolTy)
2801 return Compatible;
2802
2803 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002804 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002805
Mike Stump9afab102009-02-19 03:04:26 +00002806 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002807 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002808
2809 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002810 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002811 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002812 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002813 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002814
Chris Lattner1853da22008-01-04 23:18:45 +00002815 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002816 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002817 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002818 }
2819 return Incompatible;
2820}
2821
Chris Lattner005ed752008-01-04 18:04:52 +00002822Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002823Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002824 if (getLangOptions().CPlusPlus) {
2825 if (!lhsType->isRecordType()) {
2826 // C++ 5.17p3: If the left operand is not of class type, the
2827 // expression is implicitly converted (C++ 4) to the
2828 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002829 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2830 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002831 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002832 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002833 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002834 }
2835
2836 // FIXME: Currently, we fall through and treat C++ classes like C
2837 // structures.
2838 }
2839
Steve Naroffcdee22d2007-11-27 17:58:44 +00002840 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2841 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002842 if ((lhsType->isPointerType() ||
2843 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002844 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002845 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002846 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002847 return Compatible;
2848 }
Mike Stump9afab102009-02-19 03:04:26 +00002849
Chris Lattner5f505bf2007-10-16 02:55:40 +00002850 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002851 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002852 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002853 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002854 //
Mike Stump9afab102009-02-19 03:04:26 +00002855 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002856 if (!lhsType->isReferenceType())
2857 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002858
Chris Lattner005ed752008-01-04 18:04:52 +00002859 Sema::AssignConvertType result =
2860 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002861
Steve Naroff0f32f432007-08-24 22:33:52 +00002862 // C99 6.5.16.1p2: The value of the right operand is converted to the
2863 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002864 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2865 // so that we can use references in built-in functions even in C.
2866 // The getNonReferenceType() call makes sure that the resulting expression
2867 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002868 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002869 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002870 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002871}
2872
Chris Lattner005ed752008-01-04 18:04:52 +00002873Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002874Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2875 return CheckAssignmentConstraints(lhsType, rhsType);
2876}
2877
Chris Lattner1eafdea2008-11-18 01:30:42 +00002878QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002879 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002880 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002881 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002882 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002883}
2884
Mike Stump9afab102009-02-19 03:04:26 +00002885inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002886 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002887 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002888 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002889 QualType lhsType =
2890 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2891 QualType rhsType =
2892 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002893
Nate Begemanc5f0f652008-07-14 18:02:46 +00002894 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002895 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002896 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002897
Nate Begemanc5f0f652008-07-14 18:02:46 +00002898 // Handle the case of a vector & extvector type of the same size and element
2899 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002900 if (getLangOptions().LaxVectorConversions) {
2901 // FIXME: Should we warn here?
2902 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002903 if (const VectorType *RV = rhsType->getAsVectorType())
2904 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002905 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002906 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002907 }
2908 }
2909 }
Mike Stump9afab102009-02-19 03:04:26 +00002910
Nate Begemanc5f0f652008-07-14 18:02:46 +00002911 // If the lhs is an extended vector and the rhs is a scalar of the same type
2912 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002913 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002914 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002915
2916 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002917 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2918 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002919 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002920 return lhsType;
2921 }
2922 }
2923
Nate Begemanc5f0f652008-07-14 18:02:46 +00002924 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002925 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002926 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002927 QualType eltType = V->getElementType();
2928
Mike Stump9afab102009-02-19 03:04:26 +00002929 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002930 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2931 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002932 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002933 return rhsType;
2934 }
2935 }
2936
Chris Lattner4b009652007-07-25 00:24:17 +00002937 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002938 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002939 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002940 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002941 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002942}
2943
Chris Lattner4b009652007-07-25 00:24:17 +00002944inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002945 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002946{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002947 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002948 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002949
Steve Naroff8f708362007-08-24 19:07:16 +00002950 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002951
Chris Lattner4b009652007-07-25 00:24:17 +00002952 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002953 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002954 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002955}
2956
2957inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002958 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002959{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002960 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2961 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2962 return CheckVectorOperands(Loc, lex, rex);
2963 return InvalidOperands(Loc, lex, rex);
2964 }
Chris Lattner4b009652007-07-25 00:24:17 +00002965
Steve Naroff8f708362007-08-24 19:07:16 +00002966 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002967
Chris Lattner4b009652007-07-25 00:24:17 +00002968 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002969 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002970 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002971}
2972
2973inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00002974 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002975{
2976 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002977 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002978
Steve Naroff8f708362007-08-24 19:07:16 +00002979 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002980
Chris Lattner4b009652007-07-25 00:24:17 +00002981 // handle the common case first (both operands are arithmetic).
2982 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002983 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002984
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002985 // Put any potential pointer into PExp
2986 Expr* PExp = lex, *IExp = rex;
2987 if (IExp->getType()->isPointerType())
2988 std::swap(PExp, IExp);
2989
2990 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2991 if (IExp->getType()->isIntegerType()) {
2992 // Check for arithmetic on pointers to incomplete types
2993 if (!PTy->getPointeeType()->isObjectType()) {
2994 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002995 if (getLangOptions().CPlusPlus) {
2996 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2997 << lex->getSourceRange() << rex->getSourceRange();
2998 return QualType();
2999 }
3000
3001 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00003002 Diag(Loc, diag::ext_gnu_void_ptr)
3003 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003004 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003005 if (getLangOptions().CPlusPlus) {
3006 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3007 << lex->getType() << lex->getSourceRange();
3008 return QualType();
3009 }
3010
3011 // GNU extension: arithmetic on pointer to function
3012 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003013 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003014 } else {
Douglas Gregorc84d8932009-03-09 16:13:40 +00003015 RequireCompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003016 diag::err_typecheck_arithmetic_incomplete_type,
3017 lex->getSourceRange(), SourceRange(),
3018 lex->getType());
3019 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003020 }
3021 }
3022 return PExp->getType();
3023 }
3024 }
3025
Chris Lattner1eafdea2008-11-18 01:30:42 +00003026 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003027}
3028
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003029// C99 6.5.6
3030QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003031 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00003032 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003033 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003034
Steve Naroff8f708362007-08-24 19:07:16 +00003035 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003036
Chris Lattnerf6da2912007-12-09 21:53:25 +00003037 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003038
Chris Lattnerf6da2912007-12-09 21:53:25 +00003039 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00003040 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003041 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00003042
Chris Lattnerf6da2912007-12-09 21:53:25 +00003043 // Either ptr - int or ptr - ptr.
3044 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003045 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003046
Chris Lattnerf6da2912007-12-09 21:53:25 +00003047 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00003048 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003049 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003050 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003051 Diag(Loc, diag::ext_gnu_void_ptr)
3052 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00003053 } else if (lpointee->isFunctionType()) {
3054 if (getLangOptions().CPlusPlus) {
3055 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3056 << lex->getType() << lex->getSourceRange();
3057 return QualType();
3058 }
3059
3060 // GNU extension: arithmetic on pointer to function
3061 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3062 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003063 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003064 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003065 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003066 return QualType();
3067 }
3068 }
3069
3070 // The result type of a pointer-int computation is the pointer type.
3071 if (rex->getType()->isIntegerType())
3072 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003073
Chris Lattnerf6da2912007-12-09 21:53:25 +00003074 // Handle pointer-pointer subtractions.
3075 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003076 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003077
Chris Lattnerf6da2912007-12-09 21:53:25 +00003078 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00003079 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003080 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003081 if (rpointee->isVoidType()) {
3082 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00003083 Diag(Loc, diag::ext_gnu_void_ptr)
3084 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00003085 } else if (rpointee->isFunctionType()) {
3086 if (getLangOptions().CPlusPlus) {
3087 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3088 << rex->getType() << rex->getSourceRange();
3089 return QualType();
3090 }
Mike Stump9afab102009-02-19 03:04:26 +00003091
Douglas Gregorf93eda12009-01-23 19:03:35 +00003092 // GNU extension: arithmetic on pointer to function
3093 if (!lpointee->isFunctionType())
3094 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3095 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003096 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003097 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003098 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003099 return QualType();
3100 }
3101 }
Mike Stump9afab102009-02-19 03:04:26 +00003102
Chris Lattnerf6da2912007-12-09 21:53:25 +00003103 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003104 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003105 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003106 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003107 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003108 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003109 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003110 return QualType();
3111 }
Mike Stump9afab102009-02-19 03:04:26 +00003112
Chris Lattnerf6da2912007-12-09 21:53:25 +00003113 return Context.getPointerDiffType();
3114 }
3115 }
Mike Stump9afab102009-02-19 03:04:26 +00003116
Chris Lattner1eafdea2008-11-18 01:30:42 +00003117 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003118}
3119
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003120// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003121QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003122 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003123 // C99 6.5.7p2: Each of the operands shall have integer type.
3124 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003125 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003126
Chris Lattner2c8bff72007-12-12 05:47:28 +00003127 // Shifts don't perform usual arithmetic conversions, they just do integer
3128 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003129 if (!isCompAssign)
3130 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003131 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003132
Chris Lattner2c8bff72007-12-12 05:47:28 +00003133 // "The type of the result is that of the promoted left operand."
3134 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003135}
3136
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003137// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003138QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003139 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003140 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003141 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003142
Chris Lattner254f3bc2007-08-26 01:18:55 +00003143 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003144 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3145 UsualArithmeticConversions(lex, rex);
3146 else {
3147 UsualUnaryConversions(lex);
3148 UsualUnaryConversions(rex);
3149 }
Chris Lattner4b009652007-07-25 00:24:17 +00003150 QualType lType = lex->getType();
3151 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003152
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003153 if (!lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003154 // For non-floating point types, check for self-comparisons of the form
3155 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3156 // often indicate logic errors in the program.
3157 Expr *LHSStripped = lex->IgnoreParens();
3158 Expr *RHSStripped = rex->IgnoreParens();
3159 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3160 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003161 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003162 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003163
3164 if (isa<CastExpr>(LHSStripped))
3165 LHSStripped = LHSStripped->IgnoreParenCasts();
3166 if (isa<CastExpr>(RHSStripped))
3167 RHSStripped = RHSStripped->IgnoreParenCasts();
3168
3169 // Warn about comparisons against a string constant (unless the other
3170 // operand is null), the user probably wants strcmp.
3171 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
3172 !RHSStripped->isNullPointerConstant(Context))
3173 Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange();
3174 else if ((isa<StringLiteral>(RHSStripped) ||
3175 isa<ObjCEncodeExpr>(RHSStripped)) &&
3176 !LHSStripped->isNullPointerConstant(Context))
3177 Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange();
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003178 }
Mike Stump9afab102009-02-19 03:04:26 +00003179
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003180 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003181 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003182
Chris Lattner254f3bc2007-08-26 01:18:55 +00003183 if (isRelational) {
3184 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003185 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003186 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003187 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003188 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003189 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003190 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003191 }
Mike Stump9afab102009-02-19 03:04:26 +00003192
Chris Lattner254f3bc2007-08-26 01:18:55 +00003193 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003194 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003195 }
Mike Stump9afab102009-02-19 03:04:26 +00003196
Chris Lattner22be8422007-08-26 01:10:14 +00003197 bool LHSIsNull = lex->isNullPointerConstant(Context);
3198 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003199
Chris Lattner254f3bc2007-08-26 01:18:55 +00003200 // All of the following pointer related warnings are GCC extensions, except
3201 // when handling null pointer constants. One day, we can consider making them
3202 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003203 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003204 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003205 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003206 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003207 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003208
Steve Naroff3b435622007-11-13 14:57:38 +00003209 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003210 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3211 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003212 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003213 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003214 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003215 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003216 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003217 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003218 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003219 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003220 // Handle block pointer types.
3221 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3222 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3223 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003224
Steve Naroff3454b6c2008-09-04 15:10:53 +00003225 if (!LHSIsNull && !RHSIsNull &&
3226 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003227 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003228 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003229 }
3230 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003231 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003232 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003233 // Allow block pointers to be compared with null pointer constants.
3234 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3235 (lType->isPointerType() && rType->isBlockPointerType())) {
3236 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003237 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003238 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003239 }
3240 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003241 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003242 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003243
Steve Naroff936c4362008-06-03 14:04:54 +00003244 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003245 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003246 const PointerType *LPT = lType->getAsPointerType();
3247 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003248 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003249 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003250 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003251 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003252
Steve Naroff030fcda2008-11-17 19:49:16 +00003253 if (!LPtrToVoid && !RPtrToVoid &&
3254 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003255 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003256 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003257 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003258 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003259 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003260 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003261 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003262 }
Steve Naroff936c4362008-06-03 14:04:54 +00003263 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3264 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003265 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003266 } else {
3267 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003268 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003269 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003270 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003271 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003272 }
Steve Naroff936c4362008-06-03 14:04:54 +00003273 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003274 }
Mike Stump9afab102009-02-19 03:04:26 +00003275 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003276 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003277 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003278 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003279 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003280 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003281 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003282 }
Mike Stump9afab102009-02-19 03:04:26 +00003283 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003284 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003285 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003286 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003287 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003288 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003289 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003290 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003291 // Handle block pointers.
3292 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3293 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003294 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003295 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003296 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003297 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003298 }
3299 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3300 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003301 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003302 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003303 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003304 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003305 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003306 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003307}
3308
Nate Begemanc5f0f652008-07-14 18:02:46 +00003309/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003310/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003311/// like a scalar comparison, a vector comparison produces a vector of integer
3312/// types.
3313QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003314 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003315 bool isRelational) {
3316 // Check to make sure we're operating on vectors of the same type and width,
3317 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003318 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003319 if (vType.isNull())
3320 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003321
Nate Begemanc5f0f652008-07-14 18:02:46 +00003322 QualType lType = lex->getType();
3323 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003324
Nate Begemanc5f0f652008-07-14 18:02:46 +00003325 // For non-floating point types, check for self-comparisons of the form
3326 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3327 // often indicate logic errors in the program.
3328 if (!lType->isFloatingType()) {
3329 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3330 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3331 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003332 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003333 }
Mike Stump9afab102009-02-19 03:04:26 +00003334
Nate Begemanc5f0f652008-07-14 18:02:46 +00003335 // Check for comparisons of floating point operands using != and ==.
3336 if (!isRelational && lType->isFloatingType()) {
3337 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003338 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003339 }
Mike Stump9afab102009-02-19 03:04:26 +00003340
Nate Begemanc5f0f652008-07-14 18:02:46 +00003341 // Return the type for the comparison, which is the same as vector type for
3342 // integer vectors, or an integer type of identical size and number of
3343 // elements for floating point vectors.
3344 if (lType->isIntegerType())
3345 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003346
Nate Begemanc5f0f652008-07-14 18:02:46 +00003347 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003348 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003349 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003350 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003351 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3352 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3353
Mike Stump9afab102009-02-19 03:04:26 +00003354 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003355 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003356 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3357}
3358
Chris Lattner4b009652007-07-25 00:24:17 +00003359inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003360 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003361{
3362 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003363 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003364
Steve Naroff8f708362007-08-24 19:07:16 +00003365 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003366
Chris Lattner4b009652007-07-25 00:24:17 +00003367 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003368 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003369 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003370}
3371
3372inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003373 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003374{
3375 UsualUnaryConversions(lex);
3376 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003377
Eli Friedmanbea3f842008-05-13 20:16:47 +00003378 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003379 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003380 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003381}
3382
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003383/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3384/// is a read-only property; return true if so. A readonly property expression
3385/// depends on various declarations and thus must be treated specially.
3386///
Mike Stump9afab102009-02-19 03:04:26 +00003387static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003388{
3389 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3390 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3391 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3392 QualType BaseType = PropExpr->getBase()->getType();
3393 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003394 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003395 PTy->getPointeeType()->getAsObjCInterfaceType())
3396 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3397 if (S.isPropertyReadonly(PDecl, IFace))
3398 return true;
3399 }
3400 }
3401 return false;
3402}
3403
Chris Lattner4c2642c2008-11-18 01:22:49 +00003404/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3405/// emit an error and return true. If so, return false.
3406static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003407 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3408 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3409 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003410 if (IsLV == Expr::MLV_Valid)
3411 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003412
Chris Lattner4c2642c2008-11-18 01:22:49 +00003413 unsigned Diag = 0;
3414 bool NeedType = false;
3415 switch (IsLV) { // C99 6.5.16p2
3416 default: assert(0 && "Unknown result from isModifiableLvalue!");
3417 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003418 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003419 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3420 NeedType = true;
3421 break;
Mike Stump9afab102009-02-19 03:04:26 +00003422 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003423 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3424 NeedType = true;
3425 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003426 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003427 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3428 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003429 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003430 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3431 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003432 case Expr::MLV_IncompleteType:
3433 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00003434 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003435 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3436 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003437 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003438 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3439 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003440 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003441 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3442 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003443 case Expr::MLV_ReadonlyProperty:
3444 Diag = diag::error_readonly_property_assignment;
3445 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003446 case Expr::MLV_NoSetterProperty:
3447 Diag = diag::error_nosetter_property_assignment;
3448 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003449 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003450
Chris Lattner4c2642c2008-11-18 01:22:49 +00003451 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003452 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003453 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003454 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003455 return true;
3456}
3457
3458
3459
3460// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003461QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3462 SourceLocation Loc,
3463 QualType CompoundType) {
3464 // Verify that LHS is a modifiable lvalue, and emit error if not.
3465 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003466 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003467
3468 QualType LHSType = LHS->getType();
3469 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003470
Chris Lattner005ed752008-01-04 18:04:52 +00003471 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003472 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003473 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003474 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003475 // Special case of NSObject attributes on c-style pointer types.
3476 if (ConvTy == IncompatiblePointer &&
3477 ((Context.isObjCNSObjectType(LHSType) &&
3478 Context.isObjCObjectPointerType(RHSType)) ||
3479 (Context.isObjCNSObjectType(RHSType) &&
3480 Context.isObjCObjectPointerType(LHSType))))
3481 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003482
Chris Lattner34c85082008-08-21 18:04:13 +00003483 // If the RHS is a unary plus or minus, check to see if they = and + are
3484 // right next to each other. If so, the user may have typo'd "x =+ 4"
3485 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003486 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3488 RHSCheck = ICE->getSubExpr();
3489 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3490 if ((UO->getOpcode() == UnaryOperator::Plus ||
3491 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003492 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003493 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00003494 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3495 // And there is a space or other character before the subexpr of the
3496 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00003497 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3498 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003499 Diag(Loc, diag::warn_not_compound_assign)
3500 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3501 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00003502 }
Chris Lattner34c85082008-08-21 18:04:13 +00003503 }
3504 } else {
3505 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003506 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003507 }
Chris Lattner005ed752008-01-04 18:04:52 +00003508
Chris Lattner1eafdea2008-11-18 01:30:42 +00003509 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3510 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003511 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003512
Chris Lattner4b009652007-07-25 00:24:17 +00003513 // C99 6.5.16p3: The type of an assignment expression is the type of the
3514 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003515 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003516 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3517 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003518 // C++ 5.17p1: the type of the assignment expression is that of its left
3519 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003520 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003521}
3522
Chris Lattner1eafdea2008-11-18 01:30:42 +00003523// C99 6.5.17
3524QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3525 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003526
Chris Lattner03c430f2008-07-25 20:54:07 +00003527 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003528 DefaultFunctionArrayConversion(RHS);
3529 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003530}
3531
3532/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3533/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003534QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3535 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003536 if (Op->isTypeDependent())
3537 return Context.DependentTy;
3538
Chris Lattnere65182c2008-11-21 07:05:48 +00003539 QualType ResType = Op->getType();
3540 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003541
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003542 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3543 // Decrement of bool is not allowed.
3544 if (!isInc) {
3545 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3546 return QualType();
3547 }
3548 // Increment of bool sets it to true, but is deprecated.
3549 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3550 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003551 // OK!
3552 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3553 // C99 6.5.2.4p2, 6.5.6p2
3554 if (PT->getPointeeType()->isObjectType()) {
3555 // Pointer to object is ok!
3556 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003557 if (getLangOptions().CPlusPlus) {
3558 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3559 << Op->getSourceRange();
3560 return QualType();
3561 }
3562
3563 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003564 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003565 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003566 if (getLangOptions().CPlusPlus) {
3567 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3568 << Op->getType() << Op->getSourceRange();
3569 return QualType();
3570 }
3571
3572 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003573 << ResType << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003574 } else {
Douglas Gregorc84d8932009-03-09 16:13:40 +00003575 RequireCompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003576 diag::err_typecheck_arithmetic_incomplete_type,
3577 Op->getSourceRange(), SourceRange(),
3578 ResType);
3579 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003580 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003581 } else if (ResType->isComplexType()) {
3582 // C99 does not support ++/-- on complex types, we allow as an extension.
3583 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003584 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003585 } else {
3586 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003587 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003588 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003589 }
Mike Stump9afab102009-02-19 03:04:26 +00003590 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003591 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003592 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003593 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003594 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003595}
3596
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003597/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003598/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003599/// where the declaration is needed for type checking. We only need to
3600/// handle cases when the expression references a function designator
3601/// or is an lvalue. Here are some examples:
3602/// - &(x) => x
3603/// - &*****f => f for f a function designator.
3604/// - &s.xx => s
3605/// - &s.zz[1].yy -> s, if zz is an array
3606/// - *(x + 1) -> x, if x is an array
3607/// - &"123"[2] -> 0
3608/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003609static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003610 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003611 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003612 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003613 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003614 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003615 // Fields cannot be declared with a 'register' storage class.
3616 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003617 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003618 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003619 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003620 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003621 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003622
Douglas Gregord2baafd2008-10-21 16:13:35 +00003623 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003624 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003625 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003626 return 0;
3627 else
3628 return VD;
3629 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003630 case Stmt::UnaryOperatorClass: {
3631 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003632
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003633 switch(UO->getOpcode()) {
3634 case UnaryOperator::Deref: {
3635 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003636 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3637 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3638 if (!VD || VD->getType()->isPointerType())
3639 return 0;
3640 return VD;
3641 }
3642 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003643 }
3644 case UnaryOperator::Real:
3645 case UnaryOperator::Imag:
3646 case UnaryOperator::Extension:
3647 return getPrimaryDecl(UO->getSubExpr());
3648 default:
3649 return 0;
3650 }
3651 }
3652 case Stmt::BinaryOperatorClass: {
3653 BinaryOperator *BO = cast<BinaryOperator>(E);
3654
3655 // Handle cases involving pointer arithmetic. The result of an
3656 // Assign or AddAssign is not an lvalue so they can be ignored.
3657
3658 // (x + n) or (n + x) => x
3659 if (BO->getOpcode() == BinaryOperator::Add) {
3660 if (BO->getLHS()->getType()->isPointerType()) {
3661 return getPrimaryDecl(BO->getLHS());
3662 } else if (BO->getRHS()->getType()->isPointerType()) {
3663 return getPrimaryDecl(BO->getRHS());
3664 }
3665 }
3666
3667 return 0;
3668 }
Chris Lattner4b009652007-07-25 00:24:17 +00003669 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003670 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003671 case Stmt::ImplicitCastExprClass:
3672 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003673 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003674 default:
3675 return 0;
3676 }
3677}
3678
3679/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003680/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003681/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003682/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003683/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003684/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003685/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003686QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003687 if (op->isTypeDependent())
3688 return Context.DependentTy;
3689
Steve Naroff9c6c3592008-01-13 17:10:08 +00003690 if (getLangOptions().C99) {
3691 // Implement C99-only parts of addressof rules.
3692 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3693 if (uOp->getOpcode() == UnaryOperator::Deref)
3694 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3695 // (assuming the deref expression is valid).
3696 return uOp->getSubExpr()->getType();
3697 }
3698 // Technically, there should be a check for array subscript
3699 // expressions here, but the result of one is always an lvalue anyway.
3700 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003701 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003702 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003703
Chris Lattner4b009652007-07-25 00:24:17 +00003704 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003705 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3706 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003707 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3708 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003709 return QualType();
3710 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003711 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003712 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3713 if (Field->isBitField()) {
3714 Diag(OpLoc, diag::err_typecheck_address_of)
3715 << "bit-field" << op->getSourceRange();
3716 return QualType();
3717 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003718 }
3719 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003720 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3721 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003722 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003723 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003724 return QualType();
3725 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003726 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003727 // with the register storage-class specifier.
3728 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3729 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003730 Diag(OpLoc, diag::err_typecheck_address_of)
3731 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003732 return QualType();
3733 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003734 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003735 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003736 } else if (isa<FieldDecl>(dcl)) {
3737 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003738 // Could be a pointer to member, though, if there is an explicit
3739 // scope qualifier for the class.
3740 if (isa<QualifiedDeclRefExpr>(op)) {
3741 DeclContext *Ctx = dcl->getDeclContext();
3742 if (Ctx && Ctx->isRecord())
3743 return Context.getMemberPointerType(op->getType(),
3744 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3745 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003746 } else if (isa<FunctionDecl>(dcl)) {
3747 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003748 // As above.
3749 if (isa<QualifiedDeclRefExpr>(op)) {
3750 DeclContext *Ctx = dcl->getDeclContext();
3751 if (Ctx && Ctx->isRecord())
3752 return Context.getMemberPointerType(op->getType(),
3753 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3754 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003755 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003756 else
Chris Lattner4b009652007-07-25 00:24:17 +00003757 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003758 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003759
Chris Lattner4b009652007-07-25 00:24:17 +00003760 // If the operand has type "type", the result has type "pointer to type".
3761 return Context.getPointerType(op->getType());
3762}
3763
Chris Lattnerda5c0872008-11-23 09:13:29 +00003764QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003765 if (Op->isTypeDependent())
3766 return Context.DependentTy;
3767
Chris Lattnerda5c0872008-11-23 09:13:29 +00003768 UsualUnaryConversions(Op);
3769 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003770
Chris Lattnerda5c0872008-11-23 09:13:29 +00003771 // Note that per both C89 and C99, this is always legal, even if ptype is an
3772 // incomplete type or void. It would be possible to warn about dereferencing
3773 // a void pointer, but it's completely well-defined, and such a warning is
3774 // unlikely to catch any mistakes.
3775 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003776 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003777
Chris Lattner77d52da2008-11-20 06:06:08 +00003778 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003779 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003780 return QualType();
3781}
3782
3783static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3784 tok::TokenKind Kind) {
3785 BinaryOperator::Opcode Opc;
3786 switch (Kind) {
3787 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003788 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3789 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003790 case tok::star: Opc = BinaryOperator::Mul; break;
3791 case tok::slash: Opc = BinaryOperator::Div; break;
3792 case tok::percent: Opc = BinaryOperator::Rem; break;
3793 case tok::plus: Opc = BinaryOperator::Add; break;
3794 case tok::minus: Opc = BinaryOperator::Sub; break;
3795 case tok::lessless: Opc = BinaryOperator::Shl; break;
3796 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3797 case tok::lessequal: Opc = BinaryOperator::LE; break;
3798 case tok::less: Opc = BinaryOperator::LT; break;
3799 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3800 case tok::greater: Opc = BinaryOperator::GT; break;
3801 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3802 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3803 case tok::amp: Opc = BinaryOperator::And; break;
3804 case tok::caret: Opc = BinaryOperator::Xor; break;
3805 case tok::pipe: Opc = BinaryOperator::Or; break;
3806 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3807 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3808 case tok::equal: Opc = BinaryOperator::Assign; break;
3809 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3810 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3811 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3812 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3813 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3814 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3815 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3816 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3817 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3818 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3819 case tok::comma: Opc = BinaryOperator::Comma; break;
3820 }
3821 return Opc;
3822}
3823
3824static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3825 tok::TokenKind Kind) {
3826 UnaryOperator::Opcode Opc;
3827 switch (Kind) {
3828 default: assert(0 && "Unknown unary op!");
3829 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3830 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3831 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3832 case tok::star: Opc = UnaryOperator::Deref; break;
3833 case tok::plus: Opc = UnaryOperator::Plus; break;
3834 case tok::minus: Opc = UnaryOperator::Minus; break;
3835 case tok::tilde: Opc = UnaryOperator::Not; break;
3836 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003837 case tok::kw___real: Opc = UnaryOperator::Real; break;
3838 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3839 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3840 }
3841 return Opc;
3842}
3843
Douglas Gregord7f915e2008-11-06 23:29:22 +00003844/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3845/// operator @p Opc at location @c TokLoc. This routine only supports
3846/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003847Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3848 unsigned Op,
3849 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003850 QualType ResultTy; // Result type of the binary operator.
3851 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3852 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3853
3854 switch (Opc) {
3855 default:
3856 assert(0 && "Unknown binary expr!");
3857 case BinaryOperator::Assign:
3858 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3859 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003860 case BinaryOperator::PtrMemD:
3861 case BinaryOperator::PtrMemI:
3862 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3863 Opc == BinaryOperator::PtrMemI);
3864 break;
3865 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003866 case BinaryOperator::Div:
3867 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3868 break;
3869 case BinaryOperator::Rem:
3870 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3871 break;
3872 case BinaryOperator::Add:
3873 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3874 break;
3875 case BinaryOperator::Sub:
3876 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3877 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003878 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003879 case BinaryOperator::Shr:
3880 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3881 break;
3882 case BinaryOperator::LE:
3883 case BinaryOperator::LT:
3884 case BinaryOperator::GE:
3885 case BinaryOperator::GT:
3886 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3887 break;
3888 case BinaryOperator::EQ:
3889 case BinaryOperator::NE:
3890 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3891 break;
3892 case BinaryOperator::And:
3893 case BinaryOperator::Xor:
3894 case BinaryOperator::Or:
3895 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3896 break;
3897 case BinaryOperator::LAnd:
3898 case BinaryOperator::LOr:
3899 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3900 break;
3901 case BinaryOperator::MulAssign:
3902 case BinaryOperator::DivAssign:
3903 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3904 if (!CompTy.isNull())
3905 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3906 break;
3907 case BinaryOperator::RemAssign:
3908 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3909 if (!CompTy.isNull())
3910 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3911 break;
3912 case BinaryOperator::AddAssign:
3913 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3914 if (!CompTy.isNull())
3915 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3916 break;
3917 case BinaryOperator::SubAssign:
3918 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3919 if (!CompTy.isNull())
3920 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3921 break;
3922 case BinaryOperator::ShlAssign:
3923 case BinaryOperator::ShrAssign:
3924 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3925 if (!CompTy.isNull())
3926 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3927 break;
3928 case BinaryOperator::AndAssign:
3929 case BinaryOperator::XorAssign:
3930 case BinaryOperator::OrAssign:
3931 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3932 if (!CompTy.isNull())
3933 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3934 break;
3935 case BinaryOperator::Comma:
3936 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3937 break;
3938 }
3939 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003940 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003941 if (CompTy.isNull())
3942 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3943 else
3944 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00003945 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003946}
3947
Chris Lattner4b009652007-07-25 00:24:17 +00003948// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003949Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3950 tok::TokenKind Kind,
3951 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003952 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003953 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003954
Steve Naroff87d58b42007-09-16 03:34:24 +00003955 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3956 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003957
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003958 // If either expression is type-dependent, just build the AST.
3959 // FIXME: We'll need to perform some caching of the result of name
3960 // lookup for operator+.
3961 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003962 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3963 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003964 Context.DependentTy,
3965 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003966 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003967 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3968 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003969 }
3970
Sebastian Redl95216a62009-02-07 00:15:38 +00003971 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003972 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3973 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003974 // If this is one of the assignment operators, we only perform
3975 // overload resolution if the left-hand side is a class or
3976 // enumeration type (C++ [expr.ass]p3).
3977 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3978 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3979 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3980 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003981
Douglas Gregord7f915e2008-11-06 23:29:22 +00003982 // Determine which overloaded operator we're dealing with.
3983 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003984 // Overloading .* is not possible.
3985 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003986 OO_Star, OO_Slash, OO_Percent,
3987 OO_Plus, OO_Minus,
3988 OO_LessLess, OO_GreaterGreater,
3989 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3990 OO_EqualEqual, OO_ExclaimEqual,
3991 OO_Amp,
3992 OO_Caret,
3993 OO_Pipe,
3994 OO_AmpAmp,
3995 OO_PipePipe,
3996 OO_Equal, OO_StarEqual,
3997 OO_SlashEqual, OO_PercentEqual,
3998 OO_PlusEqual, OO_MinusEqual,
3999 OO_LessLessEqual, OO_GreaterGreaterEqual,
4000 OO_AmpEqual, OO_CaretEqual,
4001 OO_PipeEqual,
4002 OO_Comma
4003 };
4004 OverloadedOperatorKind OverOp = OverOps[Opc];
4005
Mike Stump9afab102009-02-19 03:04:26 +00004006 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor5ed15042008-11-18 23:14:02 +00004007 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004008 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00004009 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00004010 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
4011 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00004012
4013 // Perform overload resolution.
4014 OverloadCandidateSet::iterator Best;
4015 switch (BestViableFunction(CandidateSet, Best)) {
4016 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00004017 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004018 FunctionDecl *FnDecl = Best->Function;
4019
Douglas Gregor70d26122008-11-12 17:17:38 +00004020 if (FnDecl) {
4021 // We matched an overloaded operator. Build a call to that
4022 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004023
Douglas Gregor70d26122008-11-12 17:17:38 +00004024 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00004025 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4026 if (PerformObjectArgumentInitialization(lhs, Method) ||
4027 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
4028 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004029 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00004030 } else {
4031 // Convert the arguments.
4032 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
4033 "passing") ||
4034 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
4035 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004036 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00004037 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00004038
Douglas Gregor70d26122008-11-12 17:17:38 +00004039 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004040 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00004041 = FnDecl->getType()->getAsFunctionType()->getResultType();
4042 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004043
Douglas Gregor70d26122008-11-12 17:17:38 +00004044 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00004045 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4046 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00004047 UsualUnaryConversions(FnExpr);
4048
Mike Stump9afab102009-02-19 03:04:26 +00004049 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00004050 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00004051 } else {
4052 // We matched a built-in operator. Convert the arguments, then
4053 // break out so that we will build the appropriate built-in
4054 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004055 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
4056 Best->Conversions[0], "passing") ||
4057 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
4058 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004059 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00004060
4061 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004062 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00004063 }
4064
4065 case OR_No_Viable_Function:
4066 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00004067 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004068 break;
4069
4070 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00004071 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
4072 << BinaryOperator::getOpcodeStr(Opc)
4073 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00004074 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004075 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004076
4077 case OR_Deleted:
4078 Diag(TokLoc, diag::err_ovl_deleted_oper)
4079 << Best->Function->isDeleted()
4080 << BinaryOperator::getOpcodeStr(Opc)
4081 << lhs->getSourceRange() << rhs->getSourceRange();
4082 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4083 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00004084 }
4085
Douglas Gregor70d26122008-11-12 17:17:38 +00004086 // Either we found no viable overloaded operator or we matched a
4087 // built-in operator. In either case, fall through to trying to
4088 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004089 }
4090
Douglas Gregord7f915e2008-11-06 23:29:22 +00004091 // Build a built-in binary operation.
4092 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004093}
4094
4095// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00004096Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4097 tok::TokenKind Op, ExprArg input) {
4098 // FIXME: Input is modified later, but smart pointer not reassigned.
4099 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004100 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004101
4102 if (getLangOptions().CPlusPlus &&
Mike Stump9afab102009-02-19 03:04:26 +00004103 (Input->getType()->isRecordType()
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004104 || Input->getType()->isEnumeralType())) {
4105 // Determine which overloaded operator we're dealing with.
4106 static const OverloadedOperatorKind OverOps[] = {
4107 OO_None, OO_None,
4108 OO_PlusPlus, OO_MinusMinus,
4109 OO_Amp, OO_Star,
4110 OO_Plus, OO_Minus,
4111 OO_Tilde, OO_Exclaim,
4112 OO_None, OO_None,
Mike Stump9afab102009-02-19 03:04:26 +00004113 OO_None,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004114 OO_None
4115 };
4116 OverloadedOperatorKind OverOp = OverOps[Opc];
4117
Mike Stump9afab102009-02-19 03:04:26 +00004118 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004119 // to the candidate set.
4120 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00004121 if (OverOp != OO_None &&
4122 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4123 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004124
4125 // Perform overload resolution.
4126 OverloadCandidateSet::iterator Best;
4127 switch (BestViableFunction(CandidateSet, Best)) {
4128 case OR_Success: {
4129 // We found a built-in operator or an overloaded operator.
4130 FunctionDecl *FnDecl = Best->Function;
4131
4132 if (FnDecl) {
4133 // We matched an overloaded operator. Build a call to that
4134 // operator.
4135
4136 // Convert the arguments.
4137 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4138 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004139 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004140 } else {
4141 // Convert the arguments.
Mike Stump9afab102009-02-19 03:04:26 +00004142 if (PerformCopyInitialization(Input,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004143 FnDecl->getParamDecl(0)->getType(),
4144 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004145 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004146 }
4147
4148 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004149 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004150 = FnDecl->getType()->getAsFunctionType()->getResultType();
4151 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004152
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004153 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00004154 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004155 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004156 UsualUnaryConversions(FnExpr);
4157
Sebastian Redl8b769972009-01-19 00:08:26 +00004158 input.release();
Mike Stump9afab102009-02-19 03:04:26 +00004159 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4160 1, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004161 } else {
4162 // We matched a built-in operator. Convert the arguments, then
4163 // break out so that we will build the appropriate built-in
4164 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004165 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4166 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004167 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004168
4169 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004170 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004171 }
4172
4173 case OR_No_Viable_Function:
4174 // No viable function; fall through to handling this as a
4175 // built-in operator, which will produce an error message for us.
4176 break;
4177
4178 case OR_Ambiguous:
4179 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4180 << UnaryOperator::getOpcodeStr(Opc)
4181 << Input->getSourceRange();
4182 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004183 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004184
4185 case OR_Deleted:
4186 Diag(OpLoc, diag::err_ovl_deleted_oper)
4187 << Best->Function->isDeleted()
4188 << UnaryOperator::getOpcodeStr(Opc)
4189 << Input->getSourceRange();
4190 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4191 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004192 }
4193
4194 // Either we found no viable overloaded operator or we matched a
4195 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004196 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004197 }
4198
Chris Lattner4b009652007-07-25 00:24:17 +00004199 QualType resultType;
4200 switch (Opc) {
4201 default:
4202 assert(0 && "Unimplemented unary expr!");
4203 case UnaryOperator::PreInc:
4204 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004205 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4206 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004207 break;
Mike Stump9afab102009-02-19 03:04:26 +00004208 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004209 resultType = CheckAddressOfOperand(Input, OpLoc);
4210 break;
Mike Stump9afab102009-02-19 03:04:26 +00004211 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004212 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004213 resultType = CheckIndirectionOperand(Input, OpLoc);
4214 break;
4215 case UnaryOperator::Plus:
4216 case UnaryOperator::Minus:
4217 UsualUnaryConversions(Input);
4218 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004219 if (resultType->isDependentType())
4220 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004221 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4222 break;
4223 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4224 resultType->isEnumeralType())
4225 break;
4226 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4227 Opc == UnaryOperator::Plus &&
4228 resultType->isPointerType())
4229 break;
4230
Sebastian Redl8b769972009-01-19 00:08:26 +00004231 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4232 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004233 case UnaryOperator::Not: // bitwise complement
4234 UsualUnaryConversions(Input);
4235 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004236 if (resultType->isDependentType())
4237 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004238 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4239 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4240 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004241 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004242 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004243 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004244 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4245 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004246 break;
4247 case UnaryOperator::LNot: // logical negation
4248 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4249 DefaultFunctionArrayConversion(Input);
4250 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004251 if (resultType->isDependentType())
4252 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004253 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004254 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4255 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004256 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004257 // In C++, it's bool. C++ 5.3.1p8
4258 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004259 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004260 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004261 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004262 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004263 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004264 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004265 resultType = Input->getType();
4266 break;
4267 }
4268 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004269 return ExprError();
4270 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004271 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004272}
4273
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004274/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stump9afab102009-02-19 03:04:26 +00004275Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004276 SourceLocation LabLoc,
4277 IdentifierInfo *LabelII) {
4278 // Look up the record for this label identifier.
Steve Naroff313c4162009-02-28 16:48:43 +00004279 llvm::DenseMap<IdentifierInfo*, Action::StmtTy*>::iterator I =
4280 ActiveScope->LabelMap.find(LabelII);
Mike Stump9afab102009-02-19 03:04:26 +00004281
Steve Naroff313c4162009-02-28 16:48:43 +00004282 LabelStmt *LabelDecl;
4283
Daniel Dunbar879788d2008-08-04 16:51:22 +00004284 // If we haven't seen this label yet, create a forward reference. It
4285 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff313c4162009-02-28 16:48:43 +00004286 if (I == ActiveScope->LabelMap.end()) {
Steve Naroff774e4152009-01-21 00:14:39 +00004287 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004288
Steve Naroff313c4162009-02-28 16:48:43 +00004289 ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl));
4290 } else
4291 LabelDecl = static_cast<LabelStmt *>(I->second);
4292
Chris Lattner4b009652007-07-25 00:24:17 +00004293 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004294 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4295 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004296}
4297
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004298Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004299 SourceLocation RPLoc) { // "({..})"
4300 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4301 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4302 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4303
Eli Friedmanbc941e12009-01-24 23:09:00 +00004304 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4305 if (isFileScope) {
4306 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4307 }
4308
Chris Lattner4b009652007-07-25 00:24:17 +00004309 // FIXME: there are a variety of strange constraints to enforce here, for
4310 // example, it is not possible to goto into a stmt expression apparently.
4311 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004312
Chris Lattner4b009652007-07-25 00:24:17 +00004313 // FIXME: the last statement in the compount stmt has its value used. We
4314 // should not warn about it being unused.
4315
4316 // If there are sub stmts in the compound stmt, take the type of the last one
4317 // as the type of the stmtexpr.
4318 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004319
Chris Lattner200964f2008-07-26 19:51:01 +00004320 if (!Compound->body_empty()) {
4321 Stmt *LastStmt = Compound->body_back();
4322 // If LastStmt is a label, skip down through into the body.
4323 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4324 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004325
Chris Lattner200964f2008-07-26 19:51:01 +00004326 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004327 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004328 }
Mike Stump9afab102009-02-19 03:04:26 +00004329
Steve Naroff774e4152009-01-21 00:14:39 +00004330 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004331}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004332
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004333Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4334 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004335 SourceLocation TypeLoc,
4336 TypeTy *argty,
4337 OffsetOfComponent *CompPtr,
4338 unsigned NumComponents,
4339 SourceLocation RPLoc) {
4340 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4341 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004342
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004343 bool Dependent = ArgTy->isDependentType();
4344
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004345 // We must have at least one component that refers to the type, and the first
4346 // one is known to be a field designator. Verify that the ArgTy represents
4347 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004348 if (!Dependent && !ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004349 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stump9afab102009-02-19 03:04:26 +00004350
Eli Friedman342d9432009-02-27 06:44:11 +00004351 // Otherwise, create a null pointer as the base, and iteratively process
4352 // the offsetof designators.
4353 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4354 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
4355 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
4356 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004357
Chris Lattnerb37522e2007-08-31 21:49:13 +00004358 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4359 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004360 // FIXME: This diagnostic isn't actually visible because the location is in
4361 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004362 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004363 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4364 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004365
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004366 if (!Dependent) {
4367 // FIXME: Dependent case loses a lot of information here. And probably
4368 // leaks like a sieve.
4369 for (unsigned i = 0; i != NumComponents; ++i) {
4370 const OffsetOfComponent &OC = CompPtr[i];
4371 if (OC.isBrackets) {
4372 // Offset of an array sub-field. TODO: Should we allow vector elements?
4373 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4374 if (!AT) {
4375 Res->Destroy(Context);
4376 return Diag(OC.LocEnd, diag::err_offsetof_array_type)
4377 << Res->getType();
4378 }
4379
4380 // FIXME: C++: Verify that operator[] isn't overloaded.
4381
Eli Friedman342d9432009-02-27 06:44:11 +00004382 // Promote the array so it looks more like a normal array subscript
4383 // expression.
4384 DefaultFunctionArrayConversion(Res);
4385
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004386 // C99 6.5.2.1p1
4387 Expr *Idx = static_cast<Expr*>(OC.U.E);
4388 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4389 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4390 << Idx->getSourceRange();
4391
4392 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4393 OC.LocEnd);
4394 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004395 }
Mike Stump9afab102009-02-19 03:04:26 +00004396
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004397 const RecordType *RC = Res->getType()->getAsRecordType();
4398 if (!RC) {
4399 Res->Destroy(Context);
4400 return Diag(OC.LocEnd, diag::err_offsetof_record_type)
4401 << Res->getType();
4402 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004403
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004404 // Get the decl corresponding to this.
4405 RecordDecl *RD = RC->getDecl();
4406 FieldDecl *MemberDecl
4407 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4408 LookupMemberName)
4409 .getAsDecl());
4410 if (!MemberDecl)
4411 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4412 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004413
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004414 // FIXME: C++: Verify that MemberDecl isn't a static field.
4415 // FIXME: Verify that MemberDecl isn't a bitfield.
4416 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4417 // matter here.
4418 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004419 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004420 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004421 }
Mike Stump9afab102009-02-19 03:04:26 +00004422
4423 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff774e4152009-01-21 00:14:39 +00004424 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004425}
4426
4427
Mike Stump9afab102009-02-19 03:04:26 +00004428Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004429 TypeTy *arg1, TypeTy *arg2,
4430 SourceLocation RPLoc) {
4431 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4432 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004433
Steve Naroff63bad2d2007-08-01 22:05:33 +00004434 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004435
4436 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff774e4152009-01-21 00:14:39 +00004437 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004438}
4439
Mike Stump9afab102009-02-19 03:04:26 +00004440Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004441 ExprTy *expr1, ExprTy *expr2,
4442 SourceLocation RPLoc) {
4443 Expr *CondExpr = static_cast<Expr*>(cond);
4444 Expr *LHSExpr = static_cast<Expr*>(expr1);
4445 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stump9afab102009-02-19 03:04:26 +00004446
Steve Naroff93c53012007-08-03 21:21:27 +00004447 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4448
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004449 QualType resType;
4450 if (CondExpr->isValueDependent()) {
4451 resType = Context.DependentTy;
4452 } else {
4453 // The conditional expression is required to be a constant expression.
4454 llvm::APSInt condEval(32);
4455 SourceLocation ExpLoc;
4456 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4457 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4458 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004459
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004460 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4461 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4462 }
4463
Mike Stump9afab102009-02-19 03:04:26 +00004464 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00004465 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004466}
4467
Steve Naroff52a81c02008-09-03 18:15:37 +00004468//===----------------------------------------------------------------------===//
4469// Clang Extensions.
4470//===----------------------------------------------------------------------===//
4471
4472/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004473void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004474 // Analyze block parameters.
4475 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004476
Steve Naroff52a81c02008-09-03 18:15:37 +00004477 // Add BSI to CurBlock.
4478 BSI->PrevBlockInfo = CurBlock;
4479 CurBlock = BSI;
Steve Naroff313c4162009-02-28 16:48:43 +00004480 ActiveScope = BlockScope;
Mike Stump9afab102009-02-19 03:04:26 +00004481
Steve Naroff52a81c02008-09-03 18:15:37 +00004482 BSI->ReturnType = 0;
4483 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004484 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004485
Steve Naroff52059382008-10-10 01:28:17 +00004486 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004487 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004488}
4489
Mike Stumpc1fddff2009-02-04 22:31:32 +00004490void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4491 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4492
4493 if (ParamInfo.getNumTypeObjects() == 0
4494 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4495 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4496
4497 // The type is entirely optional as well, if none, use DependentTy.
4498 if (T.isNull())
4499 T = Context.DependentTy;
4500
4501 // The parameter list is optional, if there was none, assume ().
4502 if (!T->isFunctionType())
4503 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4504
4505 CurBlock->hasPrototype = true;
4506 CurBlock->isVariadic = false;
4507 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4508 .getTypePtr();
4509
4510 if (!RetTy->isDependentType())
4511 CurBlock->ReturnType = RetTy;
4512 return;
4513 }
4514
Steve Naroff52a81c02008-09-03 18:15:37 +00004515 // Analyze arguments to block.
4516 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4517 "Not a function declarator!");
4518 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004519
Steve Naroff52059382008-10-10 01:28:17 +00004520 CurBlock->hasPrototype = FTI.hasPrototype;
4521 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004522
Steve Naroff52a81c02008-09-03 18:15:37 +00004523 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4524 // no arguments, not a function that takes a single void argument.
4525 if (FTI.hasPrototype &&
4526 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4527 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4528 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4529 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004530 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004531 } else if (FTI.hasPrototype) {
4532 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004533 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4534 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004535 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4536
4537 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4538 .getTypePtr();
4539
4540 if (!RetTy->isDependentType())
4541 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004542 }
Steve Naroff52059382008-10-10 01:28:17 +00004543 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004544
Steve Naroff52059382008-10-10 01:28:17 +00004545 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4546 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4547 // If this has an identifier, add it to the scope stack.
4548 if ((*AI)->getIdentifier())
4549 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004550}
4551
4552/// ActOnBlockError - If there is an error parsing a block, this callback
4553/// is invoked to pop the information about the block from the action impl.
4554void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4555 // Ensure that CurBlock is deleted.
4556 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004557
Steve Naroff52a81c02008-09-03 18:15:37 +00004558 // Pop off CurBlock, handle nested blocks.
4559 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004560
Steve Naroff52a81c02008-09-03 18:15:37 +00004561 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stump9afab102009-02-19 03:04:26 +00004562
Steve Naroff52a81c02008-09-03 18:15:37 +00004563}
4564
4565/// ActOnBlockStmtExpr - This is called when the body of a block statement
4566/// literal was successfully completed. ^(int x){...}
4567Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4568 Scope *CurScope) {
4569 // Ensure that CurBlock is deleted.
4570 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004571 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004572
Steve Naroff52059382008-10-10 01:28:17 +00004573 PopDeclContext();
4574
Steve Naroff5cd38432009-02-28 21:01:15 +00004575 // Before poping CurBlock, set ActiveScope to this scopes parent.
4576 ActiveScope = CurBlock->TheScope->getParent();
4577
Steve Naroff52a81c02008-09-03 18:15:37 +00004578 // Pop off CurBlock, handle nested blocks.
4579 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004580
Steve Naroff52a81c02008-09-03 18:15:37 +00004581 QualType RetTy = Context.VoidTy;
4582 if (BSI->ReturnType)
4583 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004584
Steve Naroff52a81c02008-09-03 18:15:37 +00004585 llvm::SmallVector<QualType, 8> ArgTypes;
4586 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4587 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004588
Steve Naroff52a81c02008-09-03 18:15:37 +00004589 QualType BlockTy;
4590 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004591 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004592 else
4593 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004594 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004595
Steve Naroff52a81c02008-09-03 18:15:37 +00004596 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004597
Steve Naroff95029d92008-10-08 18:44:00 +00004598 BSI->TheDecl->setBody(Body.take());
Mike Stumpae93d652009-02-19 22:01:56 +00004599 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff52a81c02008-09-03 18:15:37 +00004600}
4601
Anders Carlsson36760332007-10-15 20:28:48 +00004602Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4603 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004604 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004605 Expr *E = static_cast<Expr*>(expr);
4606 QualType T = QualType::getFromOpaquePtr(type);
4607
4608 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004609
4610 // Get the va_list type
4611 QualType VaListType = Context.getBuiltinVaListType();
4612 // Deal with implicit array decay; for example, on x86-64,
4613 // va_list is an array, but it's supposed to decay to
4614 // a pointer for va_arg.
4615 if (VaListType->isArrayType())
4616 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004617 // Make sure the input expression also decays appropriately.
4618 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004619
4620 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004621 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004622 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004623 << E->getType() << E->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004624
Anders Carlsson36760332007-10-15 20:28:48 +00004625 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004626
Steve Naroff774e4152009-01-21 00:14:39 +00004627 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004628}
4629
Douglas Gregorad4b3792008-11-29 04:51:27 +00004630Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4631 // The type of __null will be int or long, depending on the size of
4632 // pointers on the target.
4633 QualType Ty;
4634 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4635 Ty = Context.IntTy;
4636 else
4637 Ty = Context.LongTy;
4638
Steve Naroff774e4152009-01-21 00:14:39 +00004639 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004640}
4641
Chris Lattner005ed752008-01-04 18:04:52 +00004642bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4643 SourceLocation Loc,
4644 QualType DstType, QualType SrcType,
4645 Expr *SrcExpr, const char *Flavor) {
4646 // Decode the result (notice that AST's are still created for extensions).
4647 bool isInvalid = false;
4648 unsigned DiagKind;
4649 switch (ConvTy) {
4650 default: assert(0 && "Unknown conversion type");
4651 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004652 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004653 DiagKind = diag::ext_typecheck_convert_pointer_int;
4654 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004655 case IntToPointer:
4656 DiagKind = diag::ext_typecheck_convert_int_pointer;
4657 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004658 case IncompatiblePointer:
4659 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4660 break;
4661 case FunctionVoidPointer:
4662 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4663 break;
4664 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004665 // If the qualifiers lost were because we were applying the
4666 // (deprecated) C++ conversion from a string literal to a char*
4667 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4668 // Ideally, this check would be performed in
4669 // CheckPointerTypesForAssignment. However, that would require a
4670 // bit of refactoring (so that the second argument is an
4671 // expression, rather than a type), which should be done as part
4672 // of a larger effort to fix CheckPointerTypesForAssignment for
4673 // C++ semantics.
4674 if (getLangOptions().CPlusPlus &&
4675 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4676 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004677 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4678 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004679 case IntToBlockPointer:
4680 DiagKind = diag::err_int_to_block_pointer;
4681 break;
4682 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004683 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004684 break;
Steve Naroff19608432008-10-14 22:18:38 +00004685 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004686 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004687 // it can give a more specific diagnostic.
4688 DiagKind = diag::warn_incompatible_qualified_id;
4689 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004690 case IncompatibleVectors:
4691 DiagKind = diag::warn_incompatible_vectors;
4692 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004693 case Incompatible:
4694 DiagKind = diag::err_typecheck_convert_incompatible;
4695 isInvalid = true;
4696 break;
4697 }
Mike Stump9afab102009-02-19 03:04:26 +00004698
Chris Lattner271d4c22008-11-24 05:29:24 +00004699 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4700 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004701 return isInvalid;
4702}
Anders Carlssond5201b92008-11-30 19:50:32 +00004703
4704bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4705{
4706 Expr::EvalResult EvalResult;
4707
Mike Stump9afab102009-02-19 03:04:26 +00004708 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004709 EvalResult.HasSideEffects) {
4710 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4711
4712 if (EvalResult.Diag) {
4713 // We only show the note if it's not the usual "invalid subexpression"
4714 // or if it's actually in a subexpression.
4715 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4716 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4717 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4718 }
Mike Stump9afab102009-02-19 03:04:26 +00004719
Anders Carlssond5201b92008-11-30 19:50:32 +00004720 return true;
4721 }
4722
4723 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004724 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004725 E->getSourceRange();
4726
4727 // Print the reason it's not a constant.
4728 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4729 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4730 }
Mike Stump9afab102009-02-19 03:04:26 +00004731
Anders Carlssond5201b92008-11-30 19:50:32 +00004732 if (Result)
4733 *Result = EvalResult.Val.getInt();
4734 return false;
4735}