blob: aca19cdca675fc8d393aba314755e8c7c04d42a4 [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
630 // found a decl, but that decl is outside the current method (i.e. a global
631 // variable). In these two cases, we do a lookup for an ivar with this
632 // name, if the lookup suceeds, 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();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000635 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000636 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000637 if (DiagnoseUseOfDecl(IV, Loc))
638 return ExprError();
Chris Lattner2a3bef92009-02-16 17:19:12 +0000639
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000640 // FIXME: This should use a new expr for a direct reference, don't turn
641 // this into Self->ivar, just return a BareIVarExpr or something.
642 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000643 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Mike Stump9afab102009-02-19 03:04:26 +0000644 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +0000645 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000646 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000647 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000648 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000649 }
650 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000651 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000652 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000653 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000654 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000655 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000656 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000657 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000658
Douglas Gregoraa57e862009-02-18 21:56:37 +0000659 // Determine whether this name might be a candidate for
660 // argument-dependent lookup.
661 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
662 HasTrailingLParen;
663
664 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000665 // We've seen something of the form
666 //
667 // identifier(
668 //
669 // and we did not find any entity by the name
670 // "identifier". However, this identifier is still subject to
671 // argument-dependent lookup, so keep track of the name.
672 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
673 Context.OverloadTy,
674 Loc));
675 }
676
Chris Lattner4b009652007-07-25 00:24:17 +0000677 if (D == 0) {
678 // Otherwise, this could be an implicitly declared function reference (legal
679 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000680 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000681 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000682 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000683 else {
684 // If this name wasn't predeclared and if this is not a function call,
685 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000686 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000687 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
688 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000689 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
690 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000691 return ExprError(Diag(Loc, diag::err_undeclared_use)
692 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000693 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000694 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000695 }
696 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000697
Sebastian Redl0c9da212009-02-03 20:19:35 +0000698 // If this is an expression of the form &Class::member, don't build an
699 // implicit member ref, because we want a pointer to the member in general,
700 // not any specific instance's member.
701 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000702 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000703 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000704 QualType DType;
705 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
706 DType = FD->getType().getNonReferenceType();
707 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
708 DType = Method->getType();
709 } else if (isa<OverloadedFunctionDecl>(D)) {
710 DType = Context.OverloadTy;
711 }
712 // Could be an inner type. That's diagnosed below, so ignore it here.
713 if (!DType.isNull()) {
714 // The pointer is type- and value-dependent if it points into something
715 // dependent.
716 bool Dependent = false;
717 for (; DC; DC = DC->getParent()) {
718 // FIXME: could stop early at namespace scope.
719 if (DC->isRecord()) {
720 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
721 if (Context.getTypeDeclType(Record)->isDependentType()) {
722 Dependent = true;
723 break;
724 }
725 }
726 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000727 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000728 }
729 }
730 }
731
Douglas Gregor723d3332009-01-07 00:43:41 +0000732 // We may have found a field within an anonymous union or struct
733 // (C++ [class.union]).
734 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
735 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
736 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000737
Douglas Gregor3257fb52008-12-22 05:46:06 +0000738 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
739 if (!MD->isStatic()) {
740 // C++ [class.mfct.nonstatic]p2:
741 // [...] if name lookup (3.4.1) resolves the name in the
742 // id-expression to a nonstatic nontype member of class X or of
743 // a base class of X, the id-expression is transformed into a
744 // class member access expression (5.2.5) using (*this) (9.3.2)
745 // as the postfix-expression to the left of the '.' operator.
746 DeclContext *Ctx = 0;
747 QualType MemberType;
748 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
749 Ctx = FD->getDeclContext();
750 MemberType = FD->getType();
751
752 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
753 MemberType = RefType->getPointeeType();
754 else if (!FD->isMutable()) {
755 unsigned combinedQualifiers
756 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
757 MemberType = MemberType.getQualifiedType(combinedQualifiers);
758 }
759 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
760 if (!Method->isStatic()) {
761 Ctx = Method->getParent();
762 MemberType = Method->getType();
763 }
764 } else if (OverloadedFunctionDecl *Ovl
765 = dyn_cast<OverloadedFunctionDecl>(D)) {
766 for (OverloadedFunctionDecl::function_iterator
767 Func = Ovl->function_begin(),
768 FuncEnd = Ovl->function_end();
769 Func != FuncEnd; ++Func) {
770 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
771 if (!DMethod->isStatic()) {
772 Ctx = Ovl->getDeclContext();
773 MemberType = Context.OverloadTy;
774 break;
775 }
776 }
777 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000778
779 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000780 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
781 QualType ThisType = Context.getTagDeclType(MD->getParent());
782 if ((Context.getCanonicalType(CtxType)
783 == Context.getCanonicalType(ThisType)) ||
784 IsDerivedFrom(ThisType, CtxType)) {
785 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000786 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000787 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000788 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000789 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000790 }
791 }
792 }
793 }
794
Douglas Gregor8acb7272008-12-11 16:49:14 +0000795 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000796 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
797 if (MD->isStatic())
798 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000799 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
800 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000801 }
802
Douglas Gregor3257fb52008-12-22 05:46:06 +0000803 // Any other ways we could have found the field in a well-formed
804 // program would have been turned into implicit member expressions
805 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000806 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
807 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000808 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000809
Chris Lattner4b009652007-07-25 00:24:17 +0000810 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000811 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000812 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000813 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000814 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000815 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000816
Steve Naroffd6163f32008-09-05 22:11:13 +0000817 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000818 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000819 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
820 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000821 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
822 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
823 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000824 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000825
Douglas Gregoraa57e862009-02-18 21:56:37 +0000826 // Check whether this declaration can be used. Note that we suppress
827 // this check when we're going to perform argument-dependent lookup
828 // on this function name, because this might not be the function
829 // that overload resolution actually selects.
830 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
831 return ExprError();
832
Douglas Gregor48840c72008-12-10 23:01:14 +0000833 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000834 // Warn about constructs like:
835 // if (void *X = foo()) { ... } else { X }.
836 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000837 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
838 Scope *CheckS = S;
839 while (CheckS) {
840 if (CheckS->isWithinElse() &&
841 CheckS->getControlParent()->isDeclScope(Var)) {
842 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000843 ExprError(Diag(Loc, diag::warn_value_always_false)
844 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000845 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000846 ExprError(Diag(Loc, diag::warn_value_always_zero)
847 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000848 break;
849 }
850
851 // Move up one more control parent to check again.
852 CheckS = CheckS->getControlParent();
853 if (CheckS)
854 CheckS = CheckS->getParent();
855 }
856 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000857 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
858 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
859 // C99 DR 316 says that, if a function type comes from a
860 // function definition (without a prototype), that type is only
861 // used for checking compatibility. Therefore, when referencing
862 // the function, we pretend that we don't have the full function
863 // type.
864 QualType T = Func->getType();
865 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000866 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
867 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000868 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
869 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000870 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000871
872 // Only create DeclRefExpr's for valid Decl's.
873 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000874 return ExprError();
875
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000876 // If the identifier reference is inside a block, and it refers to a value
877 // that is outside the block, create a BlockDeclRefExpr instead of a
878 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
879 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000880 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000881 // We do not do this for things like enum constants, global variables, etc,
882 // as they do not get snapshotted.
883 //
884 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000885 // Blocks that have these can't be constant.
886 CurBlock->hasBlockDeclRefExprs = true;
887
Steve Naroff52059382008-10-10 01:28:17 +0000888 // The BlocksAttr indicates the variable is bound by-reference.
889 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000890 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000891 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000892
Steve Naroff52059382008-10-10 01:28:17 +0000893 // Variable will be bound by-copy, make it const within the closure.
894 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000895 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000896 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000897 }
898 // If this reference is not in a block or if the referenced variable is
899 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000900
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000901 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000902 bool ValueDependent = false;
903 if (getLangOptions().CPlusPlus) {
904 // C++ [temp.dep.expr]p3:
905 // An id-expression is type-dependent if it contains:
906 // - an identifier that was declared with a dependent type,
907 if (VD->getType()->isDependentType())
908 TypeDependent = true;
909 // - FIXME: a template-id that is dependent,
910 // - a conversion-function-id that specifies a dependent type,
911 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
912 Name.getCXXNameType()->isDependentType())
913 TypeDependent = true;
914 // - a nested-name-specifier that contains a class-name that
915 // names a dependent type.
916 else if (SS && !SS->isEmpty()) {
917 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
918 DC; DC = DC->getParent()) {
919 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000920 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000921 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
922 if (Context.getTypeDeclType(Record)->isDependentType()) {
923 TypeDependent = true;
924 break;
925 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000926 }
927 }
928 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000929
Douglas Gregora5d84612008-12-10 20:57:37 +0000930 // C++ [temp.dep.constexpr]p2:
931 //
932 // An identifier is value-dependent if it is:
933 // - a name declared with a dependent type,
934 if (TypeDependent)
935 ValueDependent = true;
936 // - the name of a non-type template parameter,
937 else if (isa<NonTypeTemplateParmDecl>(VD))
938 ValueDependent = true;
939 // - a constant with integral or enumeration type and is
940 // initialized with an expression that is value-dependent
941 // (FIXME!).
942 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000943
Sebastian Redlcd883f72009-01-18 18:53:16 +0000944 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
945 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000946}
947
Sebastian Redlcd883f72009-01-18 18:53:16 +0000948Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
949 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000950 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000951
Chris Lattner4b009652007-07-25 00:24:17 +0000952 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000953 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000954 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
955 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
956 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000957 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000958
Chris Lattner7e637512008-01-12 08:14:25 +0000959 // Pre-defined identifiers are of type char[x], where x is the length of the
960 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000961 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000962 if (FunctionDecl *FD = getCurFunctionDecl())
963 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000964 else if (ObjCMethodDecl *MD = getCurMethodDecl())
965 Length = MD->getSynthesizedMethodSize();
966 else {
967 Diag(Loc, diag::ext_predef_outside_function);
968 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
969 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
970 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000971
972
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000973 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000974 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000975 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000976 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000977}
978
Sebastian Redlcd883f72009-01-18 18:53:16 +0000979Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000980 llvm::SmallString<16> CharBuffer;
981 CharBuffer.resize(Tok.getLength());
982 const char *ThisTokBegin = &CharBuffer[0];
983 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000984
Chris Lattner4b009652007-07-25 00:24:17 +0000985 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
986 Tok.getLocation(), PP);
987 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000988 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000989
990 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
991
Sebastian Redl75324932009-01-20 22:23:13 +0000992 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
993 Literal.isWide(),
994 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000995}
996
Sebastian Redlcd883f72009-01-18 18:53:16 +0000997Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
998 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000999 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1000 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001001 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001002 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001003 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001004 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001005 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001006
Chris Lattner4b009652007-07-25 00:24:17 +00001007 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001008 // Add padding so that NumericLiteralParser can overread by one character.
1009 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001010 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001011
Chris Lattner4b009652007-07-25 00:24:17 +00001012 // Get the spelling of the token, which eliminates trigraphs, etc.
1013 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001014
Chris Lattner4b009652007-07-25 00:24:17 +00001015 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1016 Tok.getLocation(), PP);
1017 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001018 return ExprError();
1019
Chris Lattner1de66eb2007-08-26 03:42:43 +00001020 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001021
Chris Lattner1de66eb2007-08-26 03:42:43 +00001022 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001023 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001024 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001025 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001026 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001027 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001028 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001029 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001030
1031 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1032
Ted Kremenekddedbe22007-11-29 00:56:49 +00001033 // isExact will be set by GetFloatValue().
1034 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001035 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1036 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001037
Chris Lattner1de66eb2007-08-26 03:42:43 +00001038 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001039 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001040 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001041 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001042
Neil Booth7421e9c2007-08-29 22:00:19 +00001043 // long long is a C99 feature.
1044 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001045 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001046 Diag(Tok.getLocation(), diag::ext_longlong);
1047
Chris Lattner4b009652007-07-25 00:24:17 +00001048 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001049 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001050
Chris Lattner4b009652007-07-25 00:24:17 +00001051 if (Literal.GetIntegerValue(ResultVal)) {
1052 // If this value didn't fit into uintmax_t, warn and force to ull.
1053 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001054 Ty = Context.UnsignedLongLongTy;
1055 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001056 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001057 } else {
1058 // If this value fits into a ULL, try to figure out what else it fits into
1059 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001060
Chris Lattner4b009652007-07-25 00:24:17 +00001061 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1062 // be an unsigned int.
1063 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1064
1065 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001066 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001067 if (!Literal.isLong && !Literal.isLongLong) {
1068 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001069 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001070
Chris Lattner4b009652007-07-25 00:24:17 +00001071 // Does it fit in a unsigned int?
1072 if (ResultVal.isIntN(IntSize)) {
1073 // Does it fit in a signed int?
1074 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001075 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001076 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001077 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001078 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001079 }
Chris Lattner4b009652007-07-25 00:24:17 +00001080 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001081
Chris Lattner4b009652007-07-25 00:24:17 +00001082 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001083 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001084 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001085
Chris Lattner4b009652007-07-25 00:24:17 +00001086 // Does it fit in a unsigned long?
1087 if (ResultVal.isIntN(LongSize)) {
1088 // Does it fit in a signed long?
1089 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001090 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001091 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001092 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001093 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001094 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001095 }
1096
Chris Lattner4b009652007-07-25 00:24:17 +00001097 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001098 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001099 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001100
Chris Lattner4b009652007-07-25 00:24:17 +00001101 // Does it fit in a unsigned long long?
1102 if (ResultVal.isIntN(LongLongSize)) {
1103 // Does it fit in a signed long long?
1104 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001105 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001106 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001107 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001108 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001109 }
1110 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001111
Chris Lattner4b009652007-07-25 00:24:17 +00001112 // If we still couldn't decide a type, we probably have something that
1113 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001114 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001115 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001116 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001117 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001118 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001119
Chris Lattnere4068872008-05-09 05:59:00 +00001120 if (ResultVal.getBitWidth() != Width)
1121 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001122 }
Sebastian Redl75324932009-01-20 22:23:13 +00001123 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001124 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001125
Chris Lattner1de66eb2007-08-26 03:42:43 +00001126 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1127 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001128 Res = new (Context) ImaginaryLiteral(Res,
1129 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001130
1131 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001132}
1133
Sebastian Redlcd883f72009-01-18 18:53:16 +00001134Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1135 SourceLocation R, ExprArg Val) {
1136 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001137 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001138 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001139}
1140
1141/// The UsualUnaryConversions() function is *not* called by this routine.
1142/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001143bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001144 SourceLocation OpLoc,
1145 const SourceRange &ExprRange,
1146 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001147 if (exprType->isDependentType())
1148 return false;
1149
Chris Lattner4b009652007-07-25 00:24:17 +00001150 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001151 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001152 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001153 if (isSizeof)
1154 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1155 return false;
1156 }
1157
1158 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001159 Diag(OpLoc, diag::ext_sizeof_void_type)
1160 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001161 return false;
1162 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001163
Chris Lattner159fe082009-01-24 19:46:37 +00001164 return DiagnoseIncompleteType(OpLoc, exprType,
1165 isSizeof ? diag::err_sizeof_incomplete_type :
1166 diag::err_alignof_incomplete_type,
1167 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001168}
1169
Chris Lattner8d9f7962009-01-24 20:17:12 +00001170bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1171 const SourceRange &ExprRange) {
1172 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001173
Chris Lattner8d9f7962009-01-24 20:17:12 +00001174 // alignof decl is always ok.
1175 if (isa<DeclRefExpr>(E))
1176 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001177
1178 // Cannot know anything else if the expression is dependent.
1179 if (E->isTypeDependent())
1180 return false;
1181
Chris Lattner8d9f7962009-01-24 20:17:12 +00001182 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1183 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1184 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001185 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001186 return true;
1187 }
1188 // Other fields are ok.
1189 return false;
1190 }
1191 }
1192 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1193}
1194
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001195/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1196/// the same for @c alignof and @c __alignof
1197/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001198Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001199Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1200 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001201 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001202 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001203
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001204 QualType ArgTy;
1205 SourceRange Range;
1206 if (isType) {
1207 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1208 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001209
1210 // Verify that the operand is valid.
1211 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1212 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001213 } else {
1214 // Get the end location.
1215 Expr *ArgEx = (Expr *)TyOrEx;
1216 Range = ArgEx->getSourceRange();
1217 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001218
1219 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001220 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001221 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001222 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001223 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1224 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1225 isInvalid = true;
1226 } else {
1227 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1228 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001229
1230 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001231 DeleteExpr(ArgEx);
1232 return ExprError();
1233 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001234 }
1235
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001236 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001237 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001238 Context.getSizeType(), OpLoc,
1239 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001240}
1241
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001242QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001243 if (V->isTypeDependent())
1244 return Context.DependentTy;
1245
Chris Lattner03931a72007-08-24 21:16:53 +00001246 DefaultFunctionArrayConversion(V);
1247
Chris Lattnera16e42d2007-08-26 05:39:26 +00001248 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001249 if (const ComplexType *CT = V->getType()->getAsComplexType())
1250 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001251
1252 // Otherwise they pass through real integer and floating point types here.
1253 if (V->getType()->isArithmeticType())
1254 return V->getType();
1255
1256 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001257 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1258 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001259 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001260}
1261
1262
Chris Lattner4b009652007-07-25 00:24:17 +00001263
Sebastian Redl8b769972009-01-19 00:08:26 +00001264Action::OwningExprResult
1265Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1266 tok::TokenKind Kind, ExprArg Input) {
1267 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001268
Chris Lattner4b009652007-07-25 00:24:17 +00001269 UnaryOperator::Opcode Opc;
1270 switch (Kind) {
1271 default: assert(0 && "Unknown unary op!");
1272 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1273 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1274 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001275
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001276 if (getLangOptions().CPlusPlus &&
1277 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1278 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001279 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001280 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1281
1282 // C++ [over.inc]p1:
1283 //
1284 // [...] If the function is a member function with one
1285 // parameter (which shall be of type int) or a non-member
1286 // function with two parameters (the second of which shall be
1287 // of type int), it defines the postfix increment operator ++
1288 // for objects of that type. When the postfix increment is
1289 // called as a result of using the ++ operator, the int
1290 // argument will have value zero.
1291 Expr *Args[2] = {
1292 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001293 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1294 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001295 };
1296
1297 // Build the candidate set for overloading
1298 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001299 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1300 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001301
1302 // Perform overload resolution.
1303 OverloadCandidateSet::iterator Best;
1304 switch (BestViableFunction(CandidateSet, Best)) {
1305 case OR_Success: {
1306 // We found a built-in operator or an overloaded operator.
1307 FunctionDecl *FnDecl = Best->Function;
1308
1309 if (FnDecl) {
1310 // We matched an overloaded operator. Build a call to that
1311 // operator.
1312
1313 // Convert the arguments.
1314 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1315 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001316 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001317 } else {
1318 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001319 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001320 FnDecl->getParamDecl(0)->getType(),
1321 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001322 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001323 }
1324
1325 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001326 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001327 = FnDecl->getType()->getAsFunctionType()->getResultType();
1328 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001329
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001330 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001331 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001332 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001333 UsualUnaryConversions(FnExpr);
1334
Sebastian Redl8b769972009-01-19 00:08:26 +00001335 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001336 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1337 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001338 } else {
1339 // We matched a built-in operator. Convert the arguments, then
1340 // break out so that we will build the appropriate built-in
1341 // operator node.
1342 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1343 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001344 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001345
1346 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001347 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001348 }
1349
1350 case OR_No_Viable_Function:
1351 // No viable function; fall through to handling this as a
1352 // built-in operator, which will produce an error message for us.
1353 break;
1354
1355 case OR_Ambiguous:
1356 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1357 << UnaryOperator::getOpcodeStr(Opc)
1358 << Arg->getSourceRange();
1359 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001360 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001361
1362 case OR_Deleted:
1363 Diag(OpLoc, diag::err_ovl_deleted_oper)
1364 << Best->Function->isDeleted()
1365 << UnaryOperator::getOpcodeStr(Opc)
1366 << Arg->getSourceRange();
1367 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1368 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001369 }
1370
1371 // Either we found no viable overloaded operator or we matched a
1372 // built-in operator. In either case, fall through to trying to
1373 // build a built-in operation.
1374 }
1375
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001376 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1377 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001378 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001379 return ExprError();
1380 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001381 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001382}
1383
Sebastian Redl8b769972009-01-19 00:08:26 +00001384Action::OwningExprResult
1385Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1386 ExprArg Idx, SourceLocation RLoc) {
1387 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1388 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001389
Douglas Gregor80723c52008-11-19 17:17:41 +00001390 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001391 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001392 LHSExp->getType()->isEnumeralType() ||
1393 RHSExp->getType()->isRecordType() ||
1394 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001395 // Add the appropriate overloaded operators (C++ [over.match.oper])
1396 // to the candidate set.
1397 OverloadCandidateSet CandidateSet;
1398 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001399 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1400 SourceRange(LLoc, RLoc)))
1401 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001402
Douglas Gregor80723c52008-11-19 17:17:41 +00001403 // Perform overload resolution.
1404 OverloadCandidateSet::iterator Best;
1405 switch (BestViableFunction(CandidateSet, Best)) {
1406 case OR_Success: {
1407 // We found a built-in operator or an overloaded operator.
1408 FunctionDecl *FnDecl = Best->Function;
1409
1410 if (FnDecl) {
1411 // We matched an overloaded operator. Build a call to that
1412 // operator.
1413
1414 // Convert the arguments.
1415 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1416 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1417 PerformCopyInitialization(RHSExp,
1418 FnDecl->getParamDecl(0)->getType(),
1419 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001420 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001421 } else {
1422 // Convert the arguments.
1423 if (PerformCopyInitialization(LHSExp,
1424 FnDecl->getParamDecl(0)->getType(),
1425 "passing") ||
1426 PerformCopyInitialization(RHSExp,
1427 FnDecl->getParamDecl(1)->getType(),
1428 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001429 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001430 }
1431
1432 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001433 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001434 = FnDecl->getType()->getAsFunctionType()->getResultType();
1435 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001436
Douglas Gregor80723c52008-11-19 17:17:41 +00001437 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001438 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1439 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001440 UsualUnaryConversions(FnExpr);
1441
Sebastian Redl8b769972009-01-19 00:08:26 +00001442 Base.release();
1443 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001444 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001445 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001446 } else {
1447 // We matched a built-in operator. Convert the arguments, then
1448 // break out so that we will build the appropriate built-in
1449 // operator node.
1450 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1451 "passing") ||
1452 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1453 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001454 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001455
1456 break;
1457 }
1458 }
1459
1460 case OR_No_Viable_Function:
1461 // No viable function; fall through to handling this as a
1462 // built-in operator, which will produce an error message for us.
1463 break;
1464
1465 case OR_Ambiguous:
1466 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1467 << "[]"
1468 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1469 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001470 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001471
1472 case OR_Deleted:
1473 Diag(LLoc, diag::err_ovl_deleted_oper)
1474 << Best->Function->isDeleted()
1475 << "[]"
1476 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1477 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1478 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001479 }
1480
1481 // Either we found no viable overloaded operator or we matched a
1482 // built-in operator. In either case, fall through to trying to
1483 // build a built-in operation.
1484 }
1485
Chris Lattner4b009652007-07-25 00:24:17 +00001486 // Perform default conversions.
1487 DefaultFunctionArrayConversion(LHSExp);
1488 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001489
Chris Lattner4b009652007-07-25 00:24:17 +00001490 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1491
1492 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001493 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001494 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001495 // and index from the expression types.
1496 Expr *BaseExpr, *IndexExpr;
1497 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001498 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1499 BaseExpr = LHSExp;
1500 IndexExpr = RHSExp;
1501 ResultType = Context.DependentTy;
1502 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001503 BaseExpr = LHSExp;
1504 IndexExpr = RHSExp;
1505 // FIXME: need to deal with const...
1506 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001507 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001508 // Handle the uncommon case of "123[Ptr]".
1509 BaseExpr = RHSExp;
1510 IndexExpr = LHSExp;
1511 // FIXME: need to deal with const...
1512 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001513 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1514 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001515 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001516
Chris Lattner4b009652007-07-25 00:24:17 +00001517 // FIXME: need to deal with const...
1518 ResultType = VTy->getElementType();
1519 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001520 return ExprError(Diag(LHSExp->getLocStart(),
1521 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1522 }
Chris Lattner4b009652007-07-25 00:24:17 +00001523 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001524 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001525 return ExprError(Diag(IndexExpr->getLocStart(),
1526 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001527
1528 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1529 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001530 // void (*)(int)) and pointers to incomplete types. Functions are not
1531 // objects in C99.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001532 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001533 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001534 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001535 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001536
Sebastian Redl8b769972009-01-19 00:08:26 +00001537 Base.release();
1538 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001539 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001540 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001541}
1542
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001543QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001544CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001545 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001546 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001547
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001548 // The vector accessor can't exceed the number of elements.
1549 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001550
Mike Stump9afab102009-02-19 03:04:26 +00001551 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001552 // special names that indicate a subset of exactly half the elements are
1553 // to be selected.
1554 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001555
Nate Begeman1486b502009-01-18 01:47:54 +00001556 // This flag determines whether or not CompName has an 's' char prefix,
1557 // indicating that it is a string of hex values to be used as vector indices.
1558 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001559
1560 // Check that we've found one of the special components, or that the component
1561 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001562 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001563 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1564 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001565 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001566 do
1567 compStr++;
1568 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001569 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001570 do
1571 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001572 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001573 }
Nate Begeman1486b502009-01-18 01:47:54 +00001574
Mike Stump9afab102009-02-19 03:04:26 +00001575 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001576 // We didn't get to the end of the string. This means the component names
1577 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001578 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1579 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001580 return QualType();
1581 }
Mike Stump9afab102009-02-19 03:04:26 +00001582
Nate Begeman1486b502009-01-18 01:47:54 +00001583 // Ensure no component accessor exceeds the width of the vector type it
1584 // operates on.
1585 if (!HalvingSwizzle) {
1586 compStr = CompName.getName();
1587
1588 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001589 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001590
1591 while (*compStr) {
1592 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1593 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1594 << baseType << SourceRange(CompLoc);
1595 return QualType();
1596 }
1597 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001598 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001599
Nate Begeman1486b502009-01-18 01:47:54 +00001600 // If this is a halving swizzle, verify that the base type has an even
1601 // number of elements.
1602 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001603 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001604 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001605 return QualType();
1606 }
Mike Stump9afab102009-02-19 03:04:26 +00001607
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001608 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001609 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001610 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001611 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001612 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001613 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1614 : CompName.getLength();
1615 if (HexSwizzle)
1616 CompSize--;
1617
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001618 if (CompSize == 1)
1619 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001620
Nate Begemanaf6ed502008-04-18 23:10:10 +00001621 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001622 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001623 // diagostics look bad. We want extended vector types to appear built-in.
1624 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1625 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1626 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001627 }
1628 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001629}
1630
Chris Lattner2cb744b2009-02-15 22:43:40 +00001631
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001632/// constructSetterName - Return the setter name for the given
1633/// identifier, i.e. "set" + Name where the initial character of Name
1634/// has been capitalized.
1635// FIXME: Merge with same routine in Parser. But where should this
1636// live?
1637static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1638 const IdentifierInfo *Name) {
1639 llvm::SmallString<100> SelectorName;
1640 SelectorName = "set";
1641 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1642 SelectorName[3] = toupper(SelectorName[3]);
1643 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1644}
1645
Sebastian Redl8b769972009-01-19 00:08:26 +00001646Action::OwningExprResult
1647Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1648 tok::TokenKind OpKind, SourceLocation MemberLoc,
1649 IdentifierInfo &Member) {
1650 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001651 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001652
1653 // Perform default conversions.
1654 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001655
Steve Naroff2cb66382007-07-26 03:11:44 +00001656 QualType BaseType = BaseExpr->getType();
1657 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001658
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001659 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1660 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001661 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001662 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001663 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001664 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001665 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1666 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001667 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001668 return ExprError(Diag(MemberLoc,
1669 diag::err_typecheck_member_reference_arrow)
1670 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001671 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001672
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001673 // Handle field access to simple records. This also handles access to fields
1674 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001675 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001676 RecordDecl *RDecl = RTy->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00001677 if (DiagnoseIncompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001678 diag::err_typecheck_incomplete_tag,
1679 BaseExpr->getSourceRange()))
1680 return ExprError();
1681
Steve Naroff2cb66382007-07-26 03:11:44 +00001682 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001683 // FIXME: Qualified name lookup for C++ is a bit more complicated
1684 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001685 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001686 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001687 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001688
Douglas Gregor09be81b2009-02-04 17:27:36 +00001689 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001690 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001691 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1692 << &Member << BaseExpr->getSourceRange());
1693 else if (Result.isAmbiguous()) {
1694 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1695 MemberLoc, BaseExpr->getSourceRange());
1696 return ExprError();
1697 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001698 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001699
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001700 // If the decl being referenced had an error, return an error for this
1701 // sub-expr without emitting another error, in order to avoid cascading
1702 // error cases.
1703 if (MemberDecl->isInvalidDecl())
1704 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001705
Douglas Gregoraa57e862009-02-18 21:56:37 +00001706 // Check the use of this field
1707 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1708 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001709
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001710 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001711 // We may have found a field within an anonymous union or struct
1712 // (C++ [class.union]).
1713 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001714 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001715 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001716
Douglas Gregor82d44772008-12-20 23:49:58 +00001717 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1718 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001719 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001720 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1721 MemberType = Ref->getPointeeType();
1722 else {
1723 unsigned combinedQualifiers =
1724 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001725 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001726 combinedQualifiers &= ~QualType::Const;
1727 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1728 }
Eli Friedman76b49832008-02-06 22:48:16 +00001729
Steve Naroff774e4152009-01-21 00:14:39 +00001730 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1731 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001732 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001733 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001734 Var, MemberLoc,
1735 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001736 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001737 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001738 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001739 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001740 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001741 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001742 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001743 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001744 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1745 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001746 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001747 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1748 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001749
Douglas Gregor82d44772008-12-20 23:49:58 +00001750 // We found a declaration kind that we didn't expect. This is a
1751 // generic error message that tells the user that she can't refer
1752 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001753 return ExprError(Diag(MemberLoc,
1754 diag::err_typecheck_member_reference_unknown)
1755 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001756 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001757
Chris Lattnere9d71612008-07-21 04:59:05 +00001758 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1759 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001760 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001761 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001762 // If the decl being referenced had an error, return an error for this
1763 // sub-expr without emitting another error, in order to avoid cascading
1764 // error cases.
1765 if (IV->isInvalidDecl())
1766 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001767
1768 // Check whether we can reference this field.
1769 if (DiagnoseUseOfDecl(IV, MemberLoc))
1770 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001771
1772 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001773 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001774 OpKind == tok::arrow);
1775 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001776 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001777 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001778 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1779 << IFTy->getDecl()->getDeclName() << &Member
1780 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001781 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001782
Chris Lattnere9d71612008-07-21 04:59:05 +00001783 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1784 // pointer to a (potentially qualified) interface type.
1785 const PointerType *PTy;
1786 const ObjCInterfaceType *IFTy;
1787 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1788 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1789 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001790
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001791 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001792 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001793 // Check whether we can reference this property.
1794 if (DiagnoseUseOfDecl(PD, MemberLoc))
1795 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001796
Steve Naroff774e4152009-01-21 00:14:39 +00001797 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001798 MemberLoc, BaseExpr));
1799 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001800
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001801 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001802 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1803 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001804 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001805 // Check whether we can reference this property.
1806 if (DiagnoseUseOfDecl(PD, MemberLoc))
1807 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001808
Steve Naroff774e4152009-01-21 00:14:39 +00001809 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001810 MemberLoc, BaseExpr));
1811 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001812
1813 // If that failed, look for an "implicit" property by seeing if the nullary
1814 // selector is implemented.
1815
1816 // FIXME: The logic for looking up nullary and unary selectors should be
1817 // shared with the code in ActOnInstanceMessage.
1818
1819 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1820 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001821
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001822 // If this reference is in an @implementation, check for 'private' methods.
1823 if (!Getter)
1824 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1825 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001826 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001827 ObjCImplementations[ClassDecl->getIdentifier()])
1828 Getter = ImpDecl->getInstanceMethod(Sel);
1829
Steve Naroff04151f32008-10-22 19:16:27 +00001830 // Look through local category implementations associated with the class.
1831 if (!Getter) {
1832 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1833 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1834 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1835 }
1836 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001837 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001838 // Check if we can reference this property.
1839 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1840 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001841
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001842 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001843 // will look for the matching setter, in case it is needed.
1844 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1845 &Member);
1846 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1847 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1848 if (!Setter) {
Mike Stump9afab102009-02-19 03:04:26 +00001849 // If this reference is in an @implementation, also check for 'private'
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001850 // methods.
1851 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1852 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001853 if (ObjCImplementationDecl *ImpDecl =
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001854 ObjCImplementations[ClassDecl->getIdentifier()])
1855 Setter = ImpDecl->getInstanceMethod(SetterSel);
1856 }
1857 // Look through local category implementations associated with the class.
1858 if (!Setter) {
1859 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1860 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1861 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1862 }
1863 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001864
Douglas Gregoraa57e862009-02-18 21:56:37 +00001865 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1866 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001867
Sebastian Redl8b769972009-01-19 00:08:26 +00001868 // FIXME: we must check that the setter has property type.
Mike Stump9afab102009-02-19 03:04:26 +00001869 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001870 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001871 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001872
1873 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1874 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001875 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001876 // Handle properties on qualified "id" protocols.
1877 const ObjCQualifiedIdType *QIdTy;
1878 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1879 // Check protocols on qualified interfaces.
1880 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001881 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001882 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001883 // Check the use of this declaration
1884 if (DiagnoseUseOfDecl(PD, MemberLoc))
1885 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001886
Steve Naroff774e4152009-01-21 00:14:39 +00001887 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001888 MemberLoc, BaseExpr));
1889 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001890 // Also must look for a getter name which uses property syntax.
1891 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1892 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001893 // Check the use of this method.
1894 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1895 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001896
1897 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001898 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001899 }
1900 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001901
1902 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1903 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001904 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001905 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001906 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001907 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1908 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001909 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001910 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00001911 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001912 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001913
1914 return ExprError(Diag(MemberLoc,
1915 diag::err_typecheck_member_reference_struct_union)
1916 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001917}
1918
Douglas Gregor3257fb52008-12-22 05:46:06 +00001919/// ConvertArgumentsForCall - Converts the arguments specified in
1920/// Args/NumArgs to the parameter types of the function FDecl with
1921/// function prototype Proto. Call is the call expression itself, and
1922/// Fn is the function expression. For a C++ member function, this
1923/// routine does not attempt to convert the object argument. Returns
1924/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00001925bool
1926Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001927 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001928 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001929 Expr **Args, unsigned NumArgs,
1930 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00001931 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00001932 // assignment, to the types of the corresponding parameter, ...
1933 unsigned NumArgsInProto = Proto->getNumArgs();
1934 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001935 bool Invalid = false;
1936
Douglas Gregor3257fb52008-12-22 05:46:06 +00001937 // If too few arguments are available (and we don't have default
1938 // arguments for the remaining parameters), don't make the call.
1939 if (NumArgs < NumArgsInProto) {
1940 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1941 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1942 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1943 // Use default arguments for missing arguments
1944 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001945 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001946 }
1947
1948 // If too many are passed and not variadic, error on the extras and drop
1949 // them.
1950 if (NumArgs > NumArgsInProto) {
1951 if (!Proto->isVariadic()) {
1952 Diag(Args[NumArgsInProto]->getLocStart(),
1953 diag::err_typecheck_call_too_many_args)
1954 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1955 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1956 Args[NumArgs-1]->getLocEnd());
1957 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001958 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001959 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001960 }
1961 NumArgsToCheck = NumArgsInProto;
1962 }
Mike Stump9afab102009-02-19 03:04:26 +00001963
Douglas Gregor3257fb52008-12-22 05:46:06 +00001964 // Continue to check argument types (even if we have too few/many args).
1965 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1966 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00001967
Douglas Gregor3257fb52008-12-22 05:46:06 +00001968 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001969 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001970 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001971
1972 // Pass the argument.
1973 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1974 return true;
Mike Stump9afab102009-02-19 03:04:26 +00001975 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001976 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001977 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001978 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00001979
Douglas Gregor3257fb52008-12-22 05:46:06 +00001980 Call->setArg(i, Arg);
1981 }
Mike Stump9afab102009-02-19 03:04:26 +00001982
Douglas Gregor3257fb52008-12-22 05:46:06 +00001983 // If this is a variadic call, handle args passed through "...".
1984 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001985 VariadicCallType CallType = VariadicFunction;
1986 if (Fn->getType()->isBlockPointerType())
1987 CallType = VariadicBlock; // Block
1988 else if (isa<MemberExpr>(Fn))
1989 CallType = VariadicMethod;
1990
Douglas Gregor3257fb52008-12-22 05:46:06 +00001991 // Promote the arguments (C99 6.5.2.2p7).
1992 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1993 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001994 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001995 Call->setArg(i, Arg);
1996 }
1997 }
1998
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001999 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002000}
2001
Steve Naroff87d58b42007-09-16 03:34:24 +00002002/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002003/// This provides the location of the left/right parens and a list of comma
2004/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002005Action::OwningExprResult
2006Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2007 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002008 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002009 unsigned NumArgs = args.size();
2010 Expr *Fn = static_cast<Expr *>(fn.release());
2011 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002012 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002013 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002014 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002015
Douglas Gregor3257fb52008-12-22 05:46:06 +00002016 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002017 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002018 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002019 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2020 bool Dependent = false;
2021 if (Fn->isTypeDependent())
2022 Dependent = true;
2023 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2024 Dependent = true;
2025
2026 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002027 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002028 Context.DependentTy, RParenLoc));
2029
2030 // Determine whether this is a call to an object (C++ [over.call.object]).
2031 if (Fn->getType()->isRecordType())
2032 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2033 CommaLocs, RParenLoc));
2034
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002035 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002036 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2037 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2038 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002039 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2040 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002041 }
2042
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002043 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002044 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002045 Expr *FnExpr = Fn;
2046 bool ADL = true;
2047 while (true) {
2048 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2049 FnExpr = IcExpr->getSubExpr();
2050 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002051 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002052 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002053 ADL = false;
2054 FnExpr = PExpr->getSubExpr();
2055 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002056 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002057 == UnaryOperator::AddrOf) {
2058 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002059 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2060 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2061 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2062 break;
Mike Stump9afab102009-02-19 03:04:26 +00002063 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002064 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2065 UnqualifiedName = DepName->getName();
2066 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002067 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002068 // Any kind of name that does not refer to a declaration (or
2069 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2070 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002071 break;
2072 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002073 }
Mike Stump9afab102009-02-19 03:04:26 +00002074
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002075 OverloadedFunctionDecl *Ovl = 0;
2076 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002077 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002078 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2079 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002080
Douglas Gregorfcb19192009-02-11 23:02:49 +00002081 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002082 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002083 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002084 ADL = false;
2085
Douglas Gregorfcb19192009-02-11 23:02:49 +00002086 // We don't perform ADL in C.
2087 if (!getLangOptions().CPlusPlus)
2088 ADL = false;
2089
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002090 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002091 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2092 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002093 NumArgs, CommaLocs, RParenLoc, ADL);
2094 if (!FDecl)
2095 return ExprError();
2096
2097 // Update Fn to refer to the actual function selected.
2098 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002099 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002100 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stump9afab102009-02-19 03:04:26 +00002101 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2102 QDRExpr->getLocation(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002103 false, false,
2104 QDRExpr->getSourceRange().getBegin());
2105 else
Mike Stump9afab102009-02-19 03:04:26 +00002106 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002107 Fn->getSourceRange().getBegin());
2108 Fn->Destroy(Context);
2109 Fn = NewFn;
2110 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002111 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002112
2113 // Promote the function operand.
2114 UsualUnaryConversions(Fn);
2115
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002116 // Make the call expr early, before semantic checks. This guarantees cleanup
2117 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002118 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2119 Args, NumArgs,
2120 Context.BoolTy,
2121 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002122
Steve Naroffd6163f32008-09-05 22:11:13 +00002123 const FunctionType *FuncT;
2124 if (!Fn->getType()->isBlockPointerType()) {
2125 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2126 // have type pointer to function".
2127 const PointerType *PT = Fn->getType()->getAsPointerType();
2128 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002129 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2130 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002131 FuncT = PT->getPointeeType()->getAsFunctionType();
2132 } else { // This is a block call.
2133 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2134 getAsFunctionType();
2135 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002136 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002137 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2138 << Fn->getType() << Fn->getSourceRange());
2139
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002140 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002141 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002142
Douglas Gregor4fa58902009-02-26 23:50:07 +00002143 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002144 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002145 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002146 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002147 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002148 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002149
Steve Naroffdb65e052007-08-28 23:30:39 +00002150 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002151 for (unsigned i = 0; i != NumArgs; i++) {
2152 Expr *Arg = Args[i];
2153 DefaultArgumentPromotion(Arg);
2154 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002155 }
Chris Lattner4b009652007-07-25 00:24:17 +00002156 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002157
Douglas Gregor3257fb52008-12-22 05:46:06 +00002158 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2159 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002160 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2161 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002162
Chris Lattner2e64c072007-08-10 20:18:51 +00002163 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002164 if (FDecl)
2165 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002166
Sebastian Redl8b769972009-01-19 00:08:26 +00002167 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002168}
2169
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002170Action::OwningExprResult
2171Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2172 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002173 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002174 QualType literalType = QualType::getFromOpaquePtr(Ty);
2175 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002176 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002177 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002178
Eli Friedman8c2173d2008-05-20 05:22:08 +00002179 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002180 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002181 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2182 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002183 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2184 diag::err_typecheck_decl_incomplete_type,
2185 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002186 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002187
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002188 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002189 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002190 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002191
Chris Lattnere5cb5862008-12-04 23:50:19 +00002192 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002193 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002194 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002195 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002196 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002197 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002198 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002199 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002200}
2201
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002202Action::OwningExprResult
2203Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2204 InitListDesignations &Designators,
2205 SourceLocation RBraceLoc) {
2206 unsigned NumInit = initlist.size();
2207 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002208
Steve Naroff0acc9c92007-09-15 18:49:24 +00002209 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002210 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002211
Mike Stump9afab102009-02-19 03:04:26 +00002212 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002213 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002214 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002215 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002216}
2217
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002218/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002219bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002220 UsualUnaryConversions(castExpr);
2221
2222 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2223 // type needs to be scalar.
2224 if (castType->isVoidType()) {
2225 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002226 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2227 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002228 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002229 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2230 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2231 (castType->isStructureType() || castType->isUnionType())) {
2232 // GCC struct/union extension: allow cast to self.
2233 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2234 << castType << castExpr->getSourceRange();
2235 } else if (castType->isUnionType()) {
2236 // GCC cast to union extension
2237 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2238 RecordDecl::field_iterator Field, FieldEnd;
2239 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2240 Field != FieldEnd; ++Field) {
2241 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2242 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2243 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2244 << castExpr->getSourceRange();
2245 break;
2246 }
2247 }
2248 if (Field == FieldEnd)
2249 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2250 << castExpr->getType() << castExpr->getSourceRange();
2251 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002252 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002253 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002254 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002255 }
Mike Stump9afab102009-02-19 03:04:26 +00002256 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002257 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002258 return Diag(castExpr->getLocStart(),
2259 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002260 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002261 } else if (castExpr->getType()->isVectorType()) {
2262 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2263 return true;
2264 } else if (castType->isVectorType()) {
2265 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2266 return true;
2267 }
2268 return false;
2269}
2270
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002271bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002272 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002273
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002274 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002275 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002276 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002277 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002278 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002279 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002280 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002281 } else
2282 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002283 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002284 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002285
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002286 return false;
2287}
2288
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002289Action::OwningExprResult
2290Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2291 SourceLocation RParenLoc, ExprArg Op) {
2292 assert((Ty != 0) && (Op.get() != 0) &&
2293 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002294
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002295 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002296 QualType castType = QualType::getFromOpaquePtr(Ty);
2297
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002298 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002299 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002300 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002301 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002302}
2303
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002304/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2305/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002306/// C99 6.5.15
2307QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2308 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002309 UsualUnaryConversions(Cond);
2310 UsualUnaryConversions(LHS);
2311 UsualUnaryConversions(RHS);
2312 QualType CondTy = Cond->getType();
2313 QualType LHSTy = LHS->getType();
2314 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002315
2316 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002317 if (!Cond->isTypeDependent()) {
2318 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2319 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2320 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002321 return QualType();
2322 }
Chris Lattner4b009652007-07-25 00:24:17 +00002323 }
Mike Stump9afab102009-02-19 03:04:26 +00002324
Chris Lattner992ae932008-01-06 22:42:25 +00002325 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002326 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002327 return Context.DependentTy;
2328
Chris Lattner992ae932008-01-06 22:42:25 +00002329 // If both operands have arithmetic type, do the usual arithmetic conversions
2330 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002331 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2332 UsualArithmeticConversions(LHS, RHS);
2333 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002334 }
Mike Stump9afab102009-02-19 03:04:26 +00002335
Chris Lattner992ae932008-01-06 22:42:25 +00002336 // If both operands are the same structure or union type, the result is that
2337 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002338 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2339 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002340 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002341 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002342 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002343 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002344 }
Mike Stump9afab102009-02-19 03:04:26 +00002345
Chris Lattner992ae932008-01-06 22:42:25 +00002346 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002347 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002348 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2349 if (!LHSTy->isVoidType())
2350 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2351 << RHS->getSourceRange();
2352 if (!RHSTy->isVoidType())
2353 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2354 << LHS->getSourceRange();
2355 ImpCastExprToType(LHS, Context.VoidTy);
2356 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002357 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002358 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002359 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2360 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002361 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2362 Context.isObjCObjectPointerType(LHSTy)) &&
2363 RHS->isNullPointerConstant(Context)) {
2364 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2365 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002366 }
Chris Lattnere2897262009-02-18 04:28:32 +00002367 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2368 Context.isObjCObjectPointerType(RHSTy)) &&
2369 LHS->isNullPointerConstant(Context)) {
2370 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2371 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002372 }
Mike Stump9afab102009-02-19 03:04:26 +00002373
Chris Lattner0ac51632008-01-06 22:50:31 +00002374 // Handle the case where both operands are pointers before we handle null
2375 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002376 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2377 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002378 // get the "pointed to" types
2379 QualType lhptee = LHSPT->getPointeeType();
2380 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002381
Chris Lattner71225142007-07-31 21:27:01 +00002382 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2383 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002384 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002385 // Figure out necessary qualifiers (C99 6.5.15p6)
2386 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002387 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002388 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2389 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002390 return destType;
2391 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002392 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002393 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002394 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002395 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2396 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002397 return destType;
2398 }
Chris Lattner4b009652007-07-25 00:24:17 +00002399
Chris Lattner9c039b52009-02-18 04:38:20 +00002400 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002401 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002402 return LHSTy;
2403 }
Mike Stump9afab102009-02-19 03:04:26 +00002404
Chris Lattnere2897262009-02-18 04:28:32 +00002405 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002406
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002407 // If either type is an Objective-C object type then check
2408 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002409 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002410 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002411 // If both operands are interfaces and either operand can be
2412 // assigned to the other, use that type as the composite
2413 // type. This allows
2414 // xxx ? (A*) a : (B*) b
2415 // where B is a subclass of A.
2416 //
2417 // Additionally, as for assignment, if either type is 'id'
2418 // allow silent coercion. Finally, if the types are
2419 // incompatible then make sure to use 'id' as the composite
2420 // type so the result is acceptable for sending messages to.
2421
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002422 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002423 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002424 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2425 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2426 if (LHSIface && RHSIface &&
2427 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002428 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002429 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002430 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002431 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002432 } else if (Context.isObjCIdStructType(lhptee) ||
2433 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002434 compositeType = Context.getObjCIdType();
2435 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002436 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002437 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002438 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002439 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002440 ImpCastExprToType(LHS, incompatTy);
2441 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002442 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002443 }
Mike Stump9afab102009-02-19 03:04:26 +00002444 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002445 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002446 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2447 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002448 // In this situation, we assume void* type. No especially good
2449 // reason, but this is what gcc does, and we do have to pick
2450 // to get a consistent AST.
2451 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002452 ImpCastExprToType(LHS, incompatTy);
2453 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002454 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002455 }
2456 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002457 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2458 // differently qualified versions of compatible types, the result type is
2459 // a pointer to an appropriately qualified version of the *composite*
2460 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002461 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002462 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002463 ImpCastExprToType(LHS, compositeType);
2464 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002465 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002466 }
Chris Lattner4b009652007-07-25 00:24:17 +00002467 }
Mike Stump9afab102009-02-19 03:04:26 +00002468
Chris Lattner9c039b52009-02-18 04:38:20 +00002469 // Selection between block pointer types is ok as long as they are the same.
2470 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2471 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2472 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002473
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002474 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2475 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002476 // id with statically typed objects).
2477 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002478 // GCC allows qualified id and any Objective-C type to devolve to
2479 // id. Currently localizing to here until clear this should be
2480 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002481 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002482 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002483 Context.isObjCObjectPointerType(RHSTy)) ||
2484 (RHSTy->isObjCQualifiedIdType() &&
2485 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002486 // FIXME: This is not the correct composite type. This only
2487 // happens to work because id can more or less be used anywhere,
2488 // however this may change the type of method sends.
2489 // FIXME: gcc adds some type-checking of the arguments and emits
2490 // (confusing) incompatible comparison warnings in some
2491 // cases. Investigate.
2492 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002493 ImpCastExprToType(LHS, compositeType);
2494 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002495 return compositeType;
2496 }
2497 }
2498
Chris Lattner992ae932008-01-06 22:42:25 +00002499 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002500 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2501 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002502 return QualType();
2503}
2504
Steve Naroff87d58b42007-09-16 03:34:24 +00002505/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002506/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002507Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2508 SourceLocation ColonLoc,
2509 ExprArg Cond, ExprArg LHS,
2510 ExprArg RHS) {
2511 Expr *CondExpr = (Expr *) Cond.get();
2512 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002513
2514 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2515 // was the condition.
2516 bool isLHSNull = LHSExpr == 0;
2517 if (isLHSNull)
2518 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002519
2520 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002521 RHSExpr, QuestionLoc);
2522 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002523 return ExprError();
2524
2525 Cond.release();
2526 LHS.release();
2527 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002528 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002529 isLHSNull ? 0 : LHSExpr,
2530 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002531}
2532
Chris Lattner4b009652007-07-25 00:24:17 +00002533
2534// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002535// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002536// routine is it effectively iqnores the qualifiers on the top level pointee.
2537// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2538// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002539Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002540Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2541 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002542
Chris Lattner4b009652007-07-25 00:24:17 +00002543 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002544 lhptee = lhsType->getAsPointerType()->getPointeeType();
2545 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002546
Chris Lattner4b009652007-07-25 00:24:17 +00002547 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002548 lhptee = Context.getCanonicalType(lhptee);
2549 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002550
Chris Lattner005ed752008-01-04 18:04:52 +00002551 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002552
2553 // C99 6.5.16.1p1: This following citation is common to constraints
2554 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2555 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002556 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002557 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002558 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002559
Mike Stump9afab102009-02-19 03:04:26 +00002560 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2561 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002562 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002563 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002564 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002565 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002566
Chris Lattner4ca3d772008-01-03 22:56:36 +00002567 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002568 assert(rhptee->isFunctionType());
2569 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002570 }
Mike Stump9afab102009-02-19 03:04:26 +00002571
Chris Lattner4ca3d772008-01-03 22:56:36 +00002572 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002573 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002574 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002575
2576 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002577 assert(lhptee->isFunctionType());
2578 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002579 }
Mike Stump9afab102009-02-19 03:04:26 +00002580 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002581 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002582 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002583 rhptee.getUnqualifiedType()))
2584 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002585 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002586}
2587
Steve Naroff3454b6c2008-09-04 15:10:53 +00002588/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2589/// block pointer types are compatible or whether a block and normal pointer
2590/// are compatible. It is more restrict than comparing two function pointer
2591// types.
Mike Stump9afab102009-02-19 03:04:26 +00002592Sema::AssignConvertType
2593Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002594 QualType rhsType) {
2595 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002596
Steve Naroff3454b6c2008-09-04 15:10:53 +00002597 // get the "pointed to" type (ignoring qualifiers at the top level)
2598 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002599 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2600
Steve Naroff3454b6c2008-09-04 15:10:53 +00002601 // make sure we operate on the canonical type
2602 lhptee = Context.getCanonicalType(lhptee);
2603 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002604
Steve Naroff3454b6c2008-09-04 15:10:53 +00002605 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002606
Steve Naroff3454b6c2008-09-04 15:10:53 +00002607 // For blocks we enforce that qualifiers are identical.
2608 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2609 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002610
Steve Naroff3454b6c2008-09-04 15:10:53 +00002611 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002612 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002613 return ConvTy;
2614}
2615
Mike Stump9afab102009-02-19 03:04:26 +00002616/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2617/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002618/// pointers. Here are some objectionable examples that GCC considers warnings:
2619///
2620/// int a, *pint;
2621/// short *pshort;
2622/// struct foo *pfoo;
2623///
2624/// pint = pshort; // warning: assignment from incompatible pointer type
2625/// a = pint; // warning: assignment makes integer from pointer without a cast
2626/// pint = a; // warning: assignment makes pointer from integer without a cast
2627/// pint = pfoo; // warning: assignment from incompatible pointer type
2628///
2629/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002630/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002631///
Chris Lattner005ed752008-01-04 18:04:52 +00002632Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002633Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002634 // Get canonical types. We're not formatting these types, just comparing
2635 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002636 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2637 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002638
2639 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002640 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002641
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002642 // If the left-hand side is a reference type, then we are in a
2643 // (rare!) case where we've allowed the use of references in C,
2644 // e.g., as a parameter type in a built-in function. In this case,
2645 // just make sure that the type referenced is compatible with the
2646 // right-hand side type. The caller is responsible for adjusting
2647 // lhsType so that the resulting expression does not have reference
2648 // type.
2649 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2650 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002651 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002652 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002653 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002654
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002655 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2656 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002657 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002658 // Relax integer conversions like we do for pointers below.
2659 if (rhsType->isIntegerType())
2660 return IntToPointer;
2661 if (lhsType->isIntegerType())
2662 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002663 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002664 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002665
Nate Begemanc5f0f652008-07-14 18:02:46 +00002666 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002667 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002668 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2669 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002670 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002671
Nate Begemanc5f0f652008-07-14 18:02:46 +00002672 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002673 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002674 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002675 if (getLangOptions().LaxVectorConversions &&
2676 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002677 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002678 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002679 }
2680 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002681 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002682
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002683 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002684 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002685
Chris Lattner390564e2008-04-07 06:49:41 +00002686 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002687 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002688 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002689
Chris Lattner390564e2008-04-07 06:49:41 +00002690 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002691 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002692
Steve Naroffa982c712008-09-29 18:10:17 +00002693 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002694 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002695 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002696
2697 // Treat block pointers as objects.
2698 if (getLangOptions().ObjC1 &&
2699 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2700 return Compatible;
2701 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002702 return Incompatible;
2703 }
2704
2705 if (isa<BlockPointerType>(lhsType)) {
2706 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002707 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002708
Steve Naroffa982c712008-09-29 18:10:17 +00002709 // Treat block pointers as objects.
2710 if (getLangOptions().ObjC1 &&
2711 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2712 return Compatible;
2713
Steve Naroff3454b6c2008-09-04 15:10:53 +00002714 if (rhsType->isBlockPointerType())
2715 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002716
Steve Naroff3454b6c2008-09-04 15:10:53 +00002717 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2718 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002719 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002720 }
Chris Lattner1853da22008-01-04 23:18:45 +00002721 return Incompatible;
2722 }
2723
Chris Lattner390564e2008-04-07 06:49:41 +00002724 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002725 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002726 if (lhsType == Context.BoolTy)
2727 return Compatible;
2728
2729 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002730 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002731
Mike Stump9afab102009-02-19 03:04:26 +00002732 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002733 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002734
2735 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002736 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002737 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002738 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002739 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002740
Chris Lattner1853da22008-01-04 23:18:45 +00002741 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002742 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002743 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002744 }
2745 return Incompatible;
2746}
2747
Chris Lattner005ed752008-01-04 18:04:52 +00002748Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002749Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002750 if (getLangOptions().CPlusPlus) {
2751 if (!lhsType->isRecordType()) {
2752 // C++ 5.17p3: If the left operand is not of class type, the
2753 // expression is implicitly converted (C++ 4) to the
2754 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002755 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2756 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002757 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002758 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002759 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002760 }
2761
2762 // FIXME: Currently, we fall through and treat C++ classes like C
2763 // structures.
2764 }
2765
Steve Naroffcdee22d2007-11-27 17:58:44 +00002766 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2767 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002768 if ((lhsType->isPointerType() ||
2769 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002770 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002771 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002772 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002773 return Compatible;
2774 }
Mike Stump9afab102009-02-19 03:04:26 +00002775
Chris Lattner5f505bf2007-10-16 02:55:40 +00002776 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002777 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002778 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002779 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002780 //
Mike Stump9afab102009-02-19 03:04:26 +00002781 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002782 if (!lhsType->isReferenceType())
2783 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002784
Chris Lattner005ed752008-01-04 18:04:52 +00002785 Sema::AssignConvertType result =
2786 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002787
Steve Naroff0f32f432007-08-24 22:33:52 +00002788 // C99 6.5.16.1p2: The value of the right operand is converted to the
2789 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002790 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2791 // so that we can use references in built-in functions even in C.
2792 // The getNonReferenceType() call makes sure that the resulting expression
2793 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002794 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002795 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002796 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002797}
2798
Chris Lattner005ed752008-01-04 18:04:52 +00002799Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002800Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2801 return CheckAssignmentConstraints(lhsType, rhsType);
2802}
2803
Chris Lattner1eafdea2008-11-18 01:30:42 +00002804QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002805 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002806 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002807 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002808 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002809}
2810
Mike Stump9afab102009-02-19 03:04:26 +00002811inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002812 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002813 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002814 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002815 QualType lhsType =
2816 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2817 QualType rhsType =
2818 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002819
Nate Begemanc5f0f652008-07-14 18:02:46 +00002820 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002821 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002822 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002823
Nate Begemanc5f0f652008-07-14 18:02:46 +00002824 // Handle the case of a vector & extvector type of the same size and element
2825 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002826 if (getLangOptions().LaxVectorConversions) {
2827 // FIXME: Should we warn here?
2828 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002829 if (const VectorType *RV = rhsType->getAsVectorType())
2830 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002831 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002832 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002833 }
2834 }
2835 }
Mike Stump9afab102009-02-19 03:04:26 +00002836
Nate Begemanc5f0f652008-07-14 18:02:46 +00002837 // If the lhs is an extended vector and the rhs is a scalar of the same type
2838 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002839 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002840 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002841
2842 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002843 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2844 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002845 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002846 return lhsType;
2847 }
2848 }
2849
Nate Begemanc5f0f652008-07-14 18:02:46 +00002850 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002851 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002852 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002853 QualType eltType = V->getElementType();
2854
Mike Stump9afab102009-02-19 03:04:26 +00002855 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002856 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2857 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002858 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002859 return rhsType;
2860 }
2861 }
2862
Chris Lattner4b009652007-07-25 00:24:17 +00002863 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002864 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002865 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002866 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002867 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002868}
2869
Chris Lattner4b009652007-07-25 00:24:17 +00002870inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002871 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002872{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002873 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002874 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002875
Steve Naroff8f708362007-08-24 19:07:16 +00002876 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002877
Chris Lattner4b009652007-07-25 00:24:17 +00002878 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002879 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002880 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002881}
2882
2883inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002884 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002885{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002886 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2887 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2888 return CheckVectorOperands(Loc, lex, rex);
2889 return InvalidOperands(Loc, lex, rex);
2890 }
Chris Lattner4b009652007-07-25 00:24:17 +00002891
Steve Naroff8f708362007-08-24 19:07:16 +00002892 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002893
Chris Lattner4b009652007-07-25 00:24:17 +00002894 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002895 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002896 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002897}
2898
2899inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00002900 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002901{
2902 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002903 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002904
Steve Naroff8f708362007-08-24 19:07:16 +00002905 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002906
Chris Lattner4b009652007-07-25 00:24:17 +00002907 // handle the common case first (both operands are arithmetic).
2908 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002909 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002910
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002911 // Put any potential pointer into PExp
2912 Expr* PExp = lex, *IExp = rex;
2913 if (IExp->getType()->isPointerType())
2914 std::swap(PExp, IExp);
2915
2916 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2917 if (IExp->getType()->isIntegerType()) {
2918 // Check for arithmetic on pointers to incomplete types
2919 if (!PTy->getPointeeType()->isObjectType()) {
2920 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002921 if (getLangOptions().CPlusPlus) {
2922 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2923 << lex->getSourceRange() << rex->getSourceRange();
2924 return QualType();
2925 }
2926
2927 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002928 Diag(Loc, diag::ext_gnu_void_ptr)
2929 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002930 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002931 if (getLangOptions().CPlusPlus) {
2932 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2933 << lex->getType() << lex->getSourceRange();
2934 return QualType();
2935 }
2936
2937 // GNU extension: arithmetic on pointer to function
2938 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002939 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002940 } else {
Mike Stump9afab102009-02-19 03:04:26 +00002941 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002942 diag::err_typecheck_arithmetic_incomplete_type,
2943 lex->getSourceRange(), SourceRange(),
2944 lex->getType());
2945 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002946 }
2947 }
2948 return PExp->getType();
2949 }
2950 }
2951
Chris Lattner1eafdea2008-11-18 01:30:42 +00002952 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002953}
2954
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002955// C99 6.5.6
2956QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002957 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002958 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002959 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002960
Steve Naroff8f708362007-08-24 19:07:16 +00002961 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002962
Chris Lattnerf6da2912007-12-09 21:53:25 +00002963 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00002964
Chris Lattnerf6da2912007-12-09 21:53:25 +00002965 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002966 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002967 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00002968
Chris Lattnerf6da2912007-12-09 21:53:25 +00002969 // Either ptr - int or ptr - ptr.
2970 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002971 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002972
Chris Lattnerf6da2912007-12-09 21:53:25 +00002973 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002974 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002975 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002976 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002977 Diag(Loc, diag::ext_gnu_void_ptr)
2978 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002979 } else if (lpointee->isFunctionType()) {
2980 if (getLangOptions().CPlusPlus) {
2981 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2982 << lex->getType() << lex->getSourceRange();
2983 return QualType();
2984 }
2985
2986 // GNU extension: arithmetic on pointer to function
2987 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2988 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002989 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002990 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002991 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002992 return QualType();
2993 }
2994 }
2995
2996 // The result type of a pointer-int computation is the pointer type.
2997 if (rex->getType()->isIntegerType())
2998 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002999
Chris Lattnerf6da2912007-12-09 21:53:25 +00003000 // Handle pointer-pointer subtractions.
3001 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003002 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003003
Chris Lattnerf6da2912007-12-09 21:53:25 +00003004 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00003005 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003006 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003007 if (rpointee->isVoidType()) {
3008 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00003009 Diag(Loc, diag::ext_gnu_void_ptr)
3010 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00003011 } else if (rpointee->isFunctionType()) {
3012 if (getLangOptions().CPlusPlus) {
3013 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3014 << rex->getType() << rex->getSourceRange();
3015 return QualType();
3016 }
Mike Stump9afab102009-02-19 03:04:26 +00003017
Douglas Gregorf93eda12009-01-23 19:03:35 +00003018 // GNU extension: arithmetic on pointer to function
3019 if (!lpointee->isFunctionType())
3020 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3021 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003022 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003023 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003024 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003025 return QualType();
3026 }
3027 }
Mike Stump9afab102009-02-19 03:04:26 +00003028
Chris Lattnerf6da2912007-12-09 21:53:25 +00003029 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003030 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003031 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003032 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003033 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003034 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003035 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003036 return QualType();
3037 }
Mike Stump9afab102009-02-19 03:04:26 +00003038
Chris Lattnerf6da2912007-12-09 21:53:25 +00003039 return Context.getPointerDiffType();
3040 }
3041 }
Mike Stump9afab102009-02-19 03:04:26 +00003042
Chris Lattner1eafdea2008-11-18 01:30:42 +00003043 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003044}
3045
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003046// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003047QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003048 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003049 // C99 6.5.7p2: Each of the operands shall have integer type.
3050 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003051 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003052
Chris Lattner2c8bff72007-12-12 05:47:28 +00003053 // Shifts don't perform usual arithmetic conversions, they just do integer
3054 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003055 if (!isCompAssign)
3056 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003057 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003058
Chris Lattner2c8bff72007-12-12 05:47:28 +00003059 // "The type of the result is that of the promoted left operand."
3060 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003061}
3062
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003063// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003064QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003065 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003066 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003067 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003068
Chris Lattner254f3bc2007-08-26 01:18:55 +00003069 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003070 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3071 UsualArithmeticConversions(lex, rex);
3072 else {
3073 UsualUnaryConversions(lex);
3074 UsualUnaryConversions(rex);
3075 }
Chris Lattner4b009652007-07-25 00:24:17 +00003076 QualType lType = lex->getType();
3077 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003078
Ted Kremenek486509e2007-10-29 17:13:39 +00003079 // For non-floating point types, check for self-comparisons of the form
3080 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3081 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003082 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003083 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3084 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003085 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003086 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003087 }
Mike Stump9afab102009-02-19 03:04:26 +00003088
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003089 // The result of comparisons is 'bool' in C++, 'int' in C.
3090 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3091
Chris Lattner254f3bc2007-08-26 01:18:55 +00003092 if (isRelational) {
3093 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003094 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003095 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003096 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003097 if (lType->isFloatingType()) {
3098 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003099 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003100 }
Mike Stump9afab102009-02-19 03:04:26 +00003101
Chris Lattner254f3bc2007-08-26 01:18:55 +00003102 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003103 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003104 }
Mike Stump9afab102009-02-19 03:04:26 +00003105
Chris Lattner22be8422007-08-26 01:10:14 +00003106 bool LHSIsNull = lex->isNullPointerConstant(Context);
3107 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003108
Chris Lattner254f3bc2007-08-26 01:18:55 +00003109 // All of the following pointer related warnings are GCC extensions, except
3110 // when handling null pointer constants. One day, we can consider making them
3111 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003112 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003113 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003114 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003115 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003116 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003117
Steve Naroff3b435622007-11-13 14:57:38 +00003118 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003119 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3120 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003121 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003122 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003123 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003124 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003125 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003126 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003127 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003128 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003129 // Handle block pointer types.
3130 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3131 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3132 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003133
Steve Naroff3454b6c2008-09-04 15:10:53 +00003134 if (!LHSIsNull && !RHSIsNull &&
3135 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003136 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003137 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003138 }
3139 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003140 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003141 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003142 // Allow block pointers to be compared with null pointer constants.
3143 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3144 (lType->isPointerType() && rType->isBlockPointerType())) {
3145 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003146 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003147 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003148 }
3149 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003150 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003151 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003152
Steve Naroff936c4362008-06-03 14:04:54 +00003153 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003154 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003155 const PointerType *LPT = lType->getAsPointerType();
3156 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003157 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003158 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003159 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003160 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003161
Steve Naroff030fcda2008-11-17 19:49:16 +00003162 if (!LPtrToVoid && !RPtrToVoid &&
3163 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003164 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003165 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003166 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003167 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003168 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003169 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003170 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003171 }
Steve Naroff936c4362008-06-03 14:04:54 +00003172 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3173 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003174 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003175 } else {
3176 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003177 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003178 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003179 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003180 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003181 }
Steve Naroff936c4362008-06-03 14:04:54 +00003182 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003183 }
Mike Stump9afab102009-02-19 03:04:26 +00003184 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003185 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003186 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003187 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003188 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003189 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003190 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003191 }
Mike Stump9afab102009-02-19 03:04:26 +00003192 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003193 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003194 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003195 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003196 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003197 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003198 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003199 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003200 // Handle block pointers.
3201 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3202 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003203 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003204 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003205 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003206 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003207 }
3208 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3209 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003210 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003211 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003212 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003213 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003214 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003215 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003216}
3217
Nate Begemanc5f0f652008-07-14 18:02:46 +00003218/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003219/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003220/// like a scalar comparison, a vector comparison produces a vector of integer
3221/// types.
3222QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003223 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003224 bool isRelational) {
3225 // Check to make sure we're operating on vectors of the same type and width,
3226 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003227 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003228 if (vType.isNull())
3229 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003230
Nate Begemanc5f0f652008-07-14 18:02:46 +00003231 QualType lType = lex->getType();
3232 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003233
Nate Begemanc5f0f652008-07-14 18:02:46 +00003234 // For non-floating point types, check for self-comparisons of the form
3235 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3236 // often indicate logic errors in the program.
3237 if (!lType->isFloatingType()) {
3238 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3239 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3240 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003241 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003242 }
Mike Stump9afab102009-02-19 03:04:26 +00003243
Nate Begemanc5f0f652008-07-14 18:02:46 +00003244 // Check for comparisons of floating point operands using != and ==.
3245 if (!isRelational && lType->isFloatingType()) {
3246 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003247 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003248 }
Mike Stump9afab102009-02-19 03:04:26 +00003249
Nate Begemanc5f0f652008-07-14 18:02:46 +00003250 // Return the type for the comparison, which is the same as vector type for
3251 // integer vectors, or an integer type of identical size and number of
3252 // elements for floating point vectors.
3253 if (lType->isIntegerType())
3254 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003255
Nate Begemanc5f0f652008-07-14 18:02:46 +00003256 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003257 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003258 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003259 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003260 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3261 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3262
Mike Stump9afab102009-02-19 03:04:26 +00003263 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003264 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003265 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3266}
3267
Chris Lattner4b009652007-07-25 00:24:17 +00003268inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003269 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003270{
3271 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003272 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003273
Steve Naroff8f708362007-08-24 19:07:16 +00003274 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003275
Chris Lattner4b009652007-07-25 00:24:17 +00003276 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003277 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003278 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003279}
3280
3281inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003282 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003283{
3284 UsualUnaryConversions(lex);
3285 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003286
Eli Friedmanbea3f842008-05-13 20:16:47 +00003287 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003288 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003289 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003290}
3291
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003292/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3293/// is a read-only property; return true if so. A readonly property expression
3294/// depends on various declarations and thus must be treated specially.
3295///
Mike Stump9afab102009-02-19 03:04:26 +00003296static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003297{
3298 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3299 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3300 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3301 QualType BaseType = PropExpr->getBase()->getType();
3302 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003303 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003304 PTy->getPointeeType()->getAsObjCInterfaceType())
3305 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3306 if (S.isPropertyReadonly(PDecl, IFace))
3307 return true;
3308 }
3309 }
3310 return false;
3311}
3312
Chris Lattner4c2642c2008-11-18 01:22:49 +00003313/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3314/// emit an error and return true. If so, return false.
3315static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003316 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3317 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3318 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003319 if (IsLV == Expr::MLV_Valid)
3320 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003321
Chris Lattner4c2642c2008-11-18 01:22:49 +00003322 unsigned Diag = 0;
3323 bool NeedType = false;
3324 switch (IsLV) { // C99 6.5.16p2
3325 default: assert(0 && "Unknown result from isModifiableLvalue!");
3326 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003327 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003328 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3329 NeedType = true;
3330 break;
Mike Stump9afab102009-02-19 03:04:26 +00003331 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003332 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3333 NeedType = true;
3334 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003335 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003336 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3337 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003338 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003339 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3340 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003341 case Expr::MLV_IncompleteType:
3342 case Expr::MLV_IncompleteVoidType:
Mike Stump9afab102009-02-19 03:04:26 +00003343 return S.DiagnoseIncompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003344 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3345 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003346 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003347 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3348 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003349 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003350 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3351 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003352 case Expr::MLV_ReadonlyProperty:
3353 Diag = diag::error_readonly_property_assignment;
3354 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003355 case Expr::MLV_NoSetterProperty:
3356 Diag = diag::error_nosetter_property_assignment;
3357 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003358 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003359
Chris Lattner4c2642c2008-11-18 01:22:49 +00003360 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003361 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003362 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003363 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003364 return true;
3365}
3366
3367
3368
3369// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003370QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3371 SourceLocation Loc,
3372 QualType CompoundType) {
3373 // Verify that LHS is a modifiable lvalue, and emit error if not.
3374 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003375 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003376
3377 QualType LHSType = LHS->getType();
3378 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003379
Chris Lattner005ed752008-01-04 18:04:52 +00003380 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003381 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003382 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003383 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003384 // Special case of NSObject attributes on c-style pointer types.
3385 if (ConvTy == IncompatiblePointer &&
3386 ((Context.isObjCNSObjectType(LHSType) &&
3387 Context.isObjCObjectPointerType(RHSType)) ||
3388 (Context.isObjCNSObjectType(RHSType) &&
3389 Context.isObjCObjectPointerType(LHSType))))
3390 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003391
Chris Lattner34c85082008-08-21 18:04:13 +00003392 // If the RHS is a unary plus or minus, check to see if they = and + are
3393 // right next to each other. If so, the user may have typo'd "x =+ 4"
3394 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003395 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003396 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3397 RHSCheck = ICE->getSubExpr();
3398 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3399 if ((UO->getOpcode() == UnaryOperator::Plus ||
3400 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003401 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003402 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003403 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003404 Diag(Loc, diag::warn_not_compound_assign)
3405 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3406 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003407 }
3408 } else {
3409 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003410 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003411 }
Chris Lattner005ed752008-01-04 18:04:52 +00003412
Chris Lattner1eafdea2008-11-18 01:30:42 +00003413 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3414 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003415 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003416
Chris Lattner4b009652007-07-25 00:24:17 +00003417 // C99 6.5.16p3: The type of an assignment expression is the type of the
3418 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003419 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003420 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3421 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003422 // C++ 5.17p1: the type of the assignment expression is that of its left
3423 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003424 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003425}
3426
Chris Lattner1eafdea2008-11-18 01:30:42 +00003427// C99 6.5.17
3428QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3429 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003430
Chris Lattner03c430f2008-07-25 20:54:07 +00003431 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003432 DefaultFunctionArrayConversion(RHS);
3433 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003434}
3435
3436/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3437/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003438QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3439 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003440 if (Op->isTypeDependent())
3441 return Context.DependentTy;
3442
Chris Lattnere65182c2008-11-21 07:05:48 +00003443 QualType ResType = Op->getType();
3444 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003445
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003446 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3447 // Decrement of bool is not allowed.
3448 if (!isInc) {
3449 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3450 return QualType();
3451 }
3452 // Increment of bool sets it to true, but is deprecated.
3453 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3454 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003455 // OK!
3456 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3457 // C99 6.5.2.4p2, 6.5.6p2
3458 if (PT->getPointeeType()->isObjectType()) {
3459 // Pointer to object is ok!
3460 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003461 if (getLangOptions().CPlusPlus) {
3462 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3463 << Op->getSourceRange();
3464 return QualType();
3465 }
3466
3467 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003468 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003469 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003470 if (getLangOptions().CPlusPlus) {
3471 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3472 << Op->getType() << Op->getSourceRange();
3473 return QualType();
3474 }
3475
3476 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003477 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003478 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003479 } else {
Mike Stump9afab102009-02-19 03:04:26 +00003480 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003481 diag::err_typecheck_arithmetic_incomplete_type,
3482 Op->getSourceRange(), SourceRange(),
3483 ResType);
3484 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003485 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003486 } else if (ResType->isComplexType()) {
3487 // C99 does not support ++/-- on complex types, we allow as an extension.
3488 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003489 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003490 } else {
3491 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003492 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003493 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003494 }
Mike Stump9afab102009-02-19 03:04:26 +00003495 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003496 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003497 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003498 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003499 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003500}
3501
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003502/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003503/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003504/// where the declaration is needed for type checking. We only need to
3505/// handle cases when the expression references a function designator
3506/// or is an lvalue. Here are some examples:
3507/// - &(x) => x
3508/// - &*****f => f for f a function designator.
3509/// - &s.xx => s
3510/// - &s.zz[1].yy -> s, if zz is an array
3511/// - *(x + 1) -> x, if x is an array
3512/// - &"123"[2] -> 0
3513/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003514static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003515 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003516 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003517 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003518 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003519 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003520 // Fields cannot be declared with a 'register' storage class.
3521 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003522 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003523 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003524 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003525 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003526 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003527
Douglas Gregord2baafd2008-10-21 16:13:35 +00003528 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003529 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003530 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003531 return 0;
3532 else
3533 return VD;
3534 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003535 case Stmt::UnaryOperatorClass: {
3536 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003537
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003538 switch(UO->getOpcode()) {
3539 case UnaryOperator::Deref: {
3540 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003541 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3542 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3543 if (!VD || VD->getType()->isPointerType())
3544 return 0;
3545 return VD;
3546 }
3547 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003548 }
3549 case UnaryOperator::Real:
3550 case UnaryOperator::Imag:
3551 case UnaryOperator::Extension:
3552 return getPrimaryDecl(UO->getSubExpr());
3553 default:
3554 return 0;
3555 }
3556 }
3557 case Stmt::BinaryOperatorClass: {
3558 BinaryOperator *BO = cast<BinaryOperator>(E);
3559
3560 // Handle cases involving pointer arithmetic. The result of an
3561 // Assign or AddAssign is not an lvalue so they can be ignored.
3562
3563 // (x + n) or (n + x) => x
3564 if (BO->getOpcode() == BinaryOperator::Add) {
3565 if (BO->getLHS()->getType()->isPointerType()) {
3566 return getPrimaryDecl(BO->getLHS());
3567 } else if (BO->getRHS()->getType()->isPointerType()) {
3568 return getPrimaryDecl(BO->getRHS());
3569 }
3570 }
3571
3572 return 0;
3573 }
Chris Lattner4b009652007-07-25 00:24:17 +00003574 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003575 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003576 case Stmt::ImplicitCastExprClass:
3577 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003578 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003579 default:
3580 return 0;
3581 }
3582}
3583
3584/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003585/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003586/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003587/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003588/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003589/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003590/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003591QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003592 if (op->isTypeDependent())
3593 return Context.DependentTy;
3594
Steve Naroff9c6c3592008-01-13 17:10:08 +00003595 if (getLangOptions().C99) {
3596 // Implement C99-only parts of addressof rules.
3597 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3598 if (uOp->getOpcode() == UnaryOperator::Deref)
3599 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3600 // (assuming the deref expression is valid).
3601 return uOp->getSubExpr()->getType();
3602 }
3603 // Technically, there should be a check for array subscript
3604 // expressions here, but the result of one is always an lvalue anyway.
3605 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003606 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003607 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003608
Chris Lattner4b009652007-07-25 00:24:17 +00003609 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003610 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3611 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003612 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3613 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003614 return QualType();
3615 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003616 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003617 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3618 if (Field->isBitField()) {
3619 Diag(OpLoc, diag::err_typecheck_address_of)
3620 << "bit-field" << op->getSourceRange();
3621 return QualType();
3622 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003623 }
3624 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003625 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3626 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003627 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003628 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003629 return QualType();
3630 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003631 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003632 // with the register storage-class specifier.
3633 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3634 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003635 Diag(OpLoc, diag::err_typecheck_address_of)
3636 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003637 return QualType();
3638 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003639 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003640 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003641 } else if (isa<FieldDecl>(dcl)) {
3642 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003643 // Could be a pointer to member, though, if there is an explicit
3644 // scope qualifier for the class.
3645 if (isa<QualifiedDeclRefExpr>(op)) {
3646 DeclContext *Ctx = dcl->getDeclContext();
3647 if (Ctx && Ctx->isRecord())
3648 return Context.getMemberPointerType(op->getType(),
3649 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3650 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003651 } else if (isa<FunctionDecl>(dcl)) {
3652 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003653 // As above.
3654 if (isa<QualifiedDeclRefExpr>(op)) {
3655 DeclContext *Ctx = dcl->getDeclContext();
3656 if (Ctx && Ctx->isRecord())
3657 return Context.getMemberPointerType(op->getType(),
3658 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3659 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003660 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003661 else
Chris Lattner4b009652007-07-25 00:24:17 +00003662 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003663 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003664
Chris Lattner4b009652007-07-25 00:24:17 +00003665 // If the operand has type "type", the result has type "pointer to type".
3666 return Context.getPointerType(op->getType());
3667}
3668
Chris Lattnerda5c0872008-11-23 09:13:29 +00003669QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003670 if (Op->isTypeDependent())
3671 return Context.DependentTy;
3672
Chris Lattnerda5c0872008-11-23 09:13:29 +00003673 UsualUnaryConversions(Op);
3674 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003675
Chris Lattnerda5c0872008-11-23 09:13:29 +00003676 // Note that per both C89 and C99, this is always legal, even if ptype is an
3677 // incomplete type or void. It would be possible to warn about dereferencing
3678 // a void pointer, but it's completely well-defined, and such a warning is
3679 // unlikely to catch any mistakes.
3680 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003681 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003682
Chris Lattner77d52da2008-11-20 06:06:08 +00003683 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003684 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003685 return QualType();
3686}
3687
3688static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3689 tok::TokenKind Kind) {
3690 BinaryOperator::Opcode Opc;
3691 switch (Kind) {
3692 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003693 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3694 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003695 case tok::star: Opc = BinaryOperator::Mul; break;
3696 case tok::slash: Opc = BinaryOperator::Div; break;
3697 case tok::percent: Opc = BinaryOperator::Rem; break;
3698 case tok::plus: Opc = BinaryOperator::Add; break;
3699 case tok::minus: Opc = BinaryOperator::Sub; break;
3700 case tok::lessless: Opc = BinaryOperator::Shl; break;
3701 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3702 case tok::lessequal: Opc = BinaryOperator::LE; break;
3703 case tok::less: Opc = BinaryOperator::LT; break;
3704 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3705 case tok::greater: Opc = BinaryOperator::GT; break;
3706 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3707 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3708 case tok::amp: Opc = BinaryOperator::And; break;
3709 case tok::caret: Opc = BinaryOperator::Xor; break;
3710 case tok::pipe: Opc = BinaryOperator::Or; break;
3711 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3712 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3713 case tok::equal: Opc = BinaryOperator::Assign; break;
3714 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3715 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3716 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3717 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3718 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3719 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3720 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3721 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3722 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3723 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3724 case tok::comma: Opc = BinaryOperator::Comma; break;
3725 }
3726 return Opc;
3727}
3728
3729static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3730 tok::TokenKind Kind) {
3731 UnaryOperator::Opcode Opc;
3732 switch (Kind) {
3733 default: assert(0 && "Unknown unary op!");
3734 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3735 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3736 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3737 case tok::star: Opc = UnaryOperator::Deref; break;
3738 case tok::plus: Opc = UnaryOperator::Plus; break;
3739 case tok::minus: Opc = UnaryOperator::Minus; break;
3740 case tok::tilde: Opc = UnaryOperator::Not; break;
3741 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003742 case tok::kw___real: Opc = UnaryOperator::Real; break;
3743 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3744 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3745 }
3746 return Opc;
3747}
3748
Douglas Gregord7f915e2008-11-06 23:29:22 +00003749/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3750/// operator @p Opc at location @c TokLoc. This routine only supports
3751/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003752Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3753 unsigned Op,
3754 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003755 QualType ResultTy; // Result type of the binary operator.
3756 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3757 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3758
3759 switch (Opc) {
3760 default:
3761 assert(0 && "Unknown binary expr!");
3762 case BinaryOperator::Assign:
3763 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3764 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003765 case BinaryOperator::PtrMemD:
3766 case BinaryOperator::PtrMemI:
3767 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3768 Opc == BinaryOperator::PtrMemI);
3769 break;
3770 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003771 case BinaryOperator::Div:
3772 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3773 break;
3774 case BinaryOperator::Rem:
3775 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3776 break;
3777 case BinaryOperator::Add:
3778 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3779 break;
3780 case BinaryOperator::Sub:
3781 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3782 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003783 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003784 case BinaryOperator::Shr:
3785 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3786 break;
3787 case BinaryOperator::LE:
3788 case BinaryOperator::LT:
3789 case BinaryOperator::GE:
3790 case BinaryOperator::GT:
3791 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3792 break;
3793 case BinaryOperator::EQ:
3794 case BinaryOperator::NE:
3795 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3796 break;
3797 case BinaryOperator::And:
3798 case BinaryOperator::Xor:
3799 case BinaryOperator::Or:
3800 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3801 break;
3802 case BinaryOperator::LAnd:
3803 case BinaryOperator::LOr:
3804 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3805 break;
3806 case BinaryOperator::MulAssign:
3807 case BinaryOperator::DivAssign:
3808 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3809 if (!CompTy.isNull())
3810 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3811 break;
3812 case BinaryOperator::RemAssign:
3813 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3814 if (!CompTy.isNull())
3815 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3816 break;
3817 case BinaryOperator::AddAssign:
3818 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3819 if (!CompTy.isNull())
3820 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3821 break;
3822 case BinaryOperator::SubAssign:
3823 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3824 if (!CompTy.isNull())
3825 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3826 break;
3827 case BinaryOperator::ShlAssign:
3828 case BinaryOperator::ShrAssign:
3829 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3830 if (!CompTy.isNull())
3831 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3832 break;
3833 case BinaryOperator::AndAssign:
3834 case BinaryOperator::XorAssign:
3835 case BinaryOperator::OrAssign:
3836 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3837 if (!CompTy.isNull())
3838 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3839 break;
3840 case BinaryOperator::Comma:
3841 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3842 break;
3843 }
3844 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003845 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003846 if (CompTy.isNull())
3847 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3848 else
3849 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00003850 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003851}
3852
Chris Lattner4b009652007-07-25 00:24:17 +00003853// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003854Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3855 tok::TokenKind Kind,
3856 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003857 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003858 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003859
Steve Naroff87d58b42007-09-16 03:34:24 +00003860 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3861 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003862
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003863 // If either expression is type-dependent, just build the AST.
3864 // FIXME: We'll need to perform some caching of the result of name
3865 // lookup for operator+.
3866 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003867 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3868 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003869 Context.DependentTy,
3870 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003871 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003872 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3873 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003874 }
3875
Sebastian Redl95216a62009-02-07 00:15:38 +00003876 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003877 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3878 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003879 // If this is one of the assignment operators, we only perform
3880 // overload resolution if the left-hand side is a class or
3881 // enumeration type (C++ [expr.ass]p3).
3882 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3883 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3884 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3885 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003886
Douglas Gregord7f915e2008-11-06 23:29:22 +00003887 // Determine which overloaded operator we're dealing with.
3888 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003889 // Overloading .* is not possible.
3890 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003891 OO_Star, OO_Slash, OO_Percent,
3892 OO_Plus, OO_Minus,
3893 OO_LessLess, OO_GreaterGreater,
3894 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3895 OO_EqualEqual, OO_ExclaimEqual,
3896 OO_Amp,
3897 OO_Caret,
3898 OO_Pipe,
3899 OO_AmpAmp,
3900 OO_PipePipe,
3901 OO_Equal, OO_StarEqual,
3902 OO_SlashEqual, OO_PercentEqual,
3903 OO_PlusEqual, OO_MinusEqual,
3904 OO_LessLessEqual, OO_GreaterGreaterEqual,
3905 OO_AmpEqual, OO_CaretEqual,
3906 OO_PipeEqual,
3907 OO_Comma
3908 };
3909 OverloadedOperatorKind OverOp = OverOps[Opc];
3910
Mike Stump9afab102009-02-19 03:04:26 +00003911 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor5ed15042008-11-18 23:14:02 +00003912 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003913 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003914 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003915 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3916 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003917
3918 // Perform overload resolution.
3919 OverloadCandidateSet::iterator Best;
3920 switch (BestViableFunction(CandidateSet, Best)) {
3921 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003922 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003923 FunctionDecl *FnDecl = Best->Function;
3924
Douglas Gregor70d26122008-11-12 17:17:38 +00003925 if (FnDecl) {
3926 // We matched an overloaded operator. Build a call to that
3927 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003928
Douglas Gregor70d26122008-11-12 17:17:38 +00003929 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3931 if (PerformObjectArgumentInitialization(lhs, Method) ||
3932 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3933 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003934 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003935 } else {
3936 // Convert the arguments.
3937 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3938 "passing") ||
3939 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3940 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003941 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003942 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003943
Douglas Gregor70d26122008-11-12 17:17:38 +00003944 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003945 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003946 = FnDecl->getType()->getAsFunctionType()->getResultType();
3947 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003948
Douglas Gregor70d26122008-11-12 17:17:38 +00003949 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003950 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3951 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003952 UsualUnaryConversions(FnExpr);
3953
Mike Stump9afab102009-02-19 03:04:26 +00003954 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003955 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003956 } else {
3957 // We matched a built-in operator. Convert the arguments, then
3958 // break out so that we will build the appropriate built-in
3959 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003960 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3961 Best->Conversions[0], "passing") ||
3962 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3963 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003964 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003965
3966 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003967 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003968 }
3969
3970 case OR_No_Viable_Function:
3971 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003972 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003973 break;
3974
3975 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003976 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3977 << BinaryOperator::getOpcodeStr(Opc)
3978 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003979 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003980 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00003981
3982 case OR_Deleted:
3983 Diag(TokLoc, diag::err_ovl_deleted_oper)
3984 << Best->Function->isDeleted()
3985 << BinaryOperator::getOpcodeStr(Opc)
3986 << lhs->getSourceRange() << rhs->getSourceRange();
3987 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3988 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003989 }
3990
Douglas Gregor70d26122008-11-12 17:17:38 +00003991 // Either we found no viable overloaded operator or we matched a
3992 // built-in operator. In either case, fall through to trying to
3993 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003994 }
3995
Douglas Gregord7f915e2008-11-06 23:29:22 +00003996 // Build a built-in binary operation.
3997 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003998}
3999
4000// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00004001Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4002 tok::TokenKind Op, ExprArg input) {
4003 // FIXME: Input is modified later, but smart pointer not reassigned.
4004 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004005 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004006
4007 if (getLangOptions().CPlusPlus &&
Mike Stump9afab102009-02-19 03:04:26 +00004008 (Input->getType()->isRecordType()
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004009 || Input->getType()->isEnumeralType())) {
4010 // Determine which overloaded operator we're dealing with.
4011 static const OverloadedOperatorKind OverOps[] = {
4012 OO_None, OO_None,
4013 OO_PlusPlus, OO_MinusMinus,
4014 OO_Amp, OO_Star,
4015 OO_Plus, OO_Minus,
4016 OO_Tilde, OO_Exclaim,
4017 OO_None, OO_None,
Mike Stump9afab102009-02-19 03:04:26 +00004018 OO_None,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004019 OO_None
4020 };
4021 OverloadedOperatorKind OverOp = OverOps[Opc];
4022
Mike Stump9afab102009-02-19 03:04:26 +00004023 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004024 // to the candidate set.
4025 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00004026 if (OverOp != OO_None &&
4027 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4028 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004029
4030 // Perform overload resolution.
4031 OverloadCandidateSet::iterator Best;
4032 switch (BestViableFunction(CandidateSet, Best)) {
4033 case OR_Success: {
4034 // We found a built-in operator or an overloaded operator.
4035 FunctionDecl *FnDecl = Best->Function;
4036
4037 if (FnDecl) {
4038 // We matched an overloaded operator. Build a call to that
4039 // operator.
4040
4041 // Convert the arguments.
4042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4043 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004044 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004045 } else {
4046 // Convert the arguments.
Mike Stump9afab102009-02-19 03:04:26 +00004047 if (PerformCopyInitialization(Input,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004048 FnDecl->getParamDecl(0)->getType(),
4049 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004050 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004051 }
4052
4053 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004054 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004055 = FnDecl->getType()->getAsFunctionType()->getResultType();
4056 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004057
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004058 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00004059 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004060 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004061 UsualUnaryConversions(FnExpr);
4062
Sebastian Redl8b769972009-01-19 00:08:26 +00004063 input.release();
Mike Stump9afab102009-02-19 03:04:26 +00004064 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4065 1, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004066 } else {
4067 // We matched a built-in operator. Convert the arguments, then
4068 // break out so that we will build the appropriate built-in
4069 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004070 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4071 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004072 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004073
4074 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004075 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004076 }
4077
4078 case OR_No_Viable_Function:
4079 // No viable function; fall through to handling this as a
4080 // built-in operator, which will produce an error message for us.
4081 break;
4082
4083 case OR_Ambiguous:
4084 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4085 << UnaryOperator::getOpcodeStr(Opc)
4086 << Input->getSourceRange();
4087 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004088 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004089
4090 case OR_Deleted:
4091 Diag(OpLoc, diag::err_ovl_deleted_oper)
4092 << Best->Function->isDeleted()
4093 << UnaryOperator::getOpcodeStr(Opc)
4094 << Input->getSourceRange();
4095 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4096 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004097 }
4098
4099 // Either we found no viable overloaded operator or we matched a
4100 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004101 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004102 }
4103
Chris Lattner4b009652007-07-25 00:24:17 +00004104 QualType resultType;
4105 switch (Opc) {
4106 default:
4107 assert(0 && "Unimplemented unary expr!");
4108 case UnaryOperator::PreInc:
4109 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004110 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4111 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004112 break;
Mike Stump9afab102009-02-19 03:04:26 +00004113 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004114 resultType = CheckAddressOfOperand(Input, OpLoc);
4115 break;
Mike Stump9afab102009-02-19 03:04:26 +00004116 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004117 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004118 resultType = CheckIndirectionOperand(Input, OpLoc);
4119 break;
4120 case UnaryOperator::Plus:
4121 case UnaryOperator::Minus:
4122 UsualUnaryConversions(Input);
4123 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004124 if (resultType->isDependentType())
4125 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004126 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4127 break;
4128 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4129 resultType->isEnumeralType())
4130 break;
4131 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4132 Opc == UnaryOperator::Plus &&
4133 resultType->isPointerType())
4134 break;
4135
Sebastian Redl8b769972009-01-19 00:08:26 +00004136 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4137 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004138 case UnaryOperator::Not: // bitwise complement
4139 UsualUnaryConversions(Input);
4140 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004141 if (resultType->isDependentType())
4142 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004143 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4144 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4145 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004146 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004147 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004148 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004149 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4150 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004151 break;
4152 case UnaryOperator::LNot: // logical negation
4153 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4154 DefaultFunctionArrayConversion(Input);
4155 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004156 if (resultType->isDependentType())
4157 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004158 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004159 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4160 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004161 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004162 // In C++, it's bool. C++ 5.3.1p8
4163 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004164 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004165 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004166 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004167 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004168 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004169 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004170 resultType = Input->getType();
4171 break;
4172 }
4173 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004174 return ExprError();
4175 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004176 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004177}
4178
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004179/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stump9afab102009-02-19 03:04:26 +00004180Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004181 SourceLocation LabLoc,
4182 IdentifierInfo *LabelII) {
4183 // Look up the record for this label identifier.
Steve Naroff313c4162009-02-28 16:48:43 +00004184 llvm::DenseMap<IdentifierInfo*, Action::StmtTy*>::iterator I =
4185 ActiveScope->LabelMap.find(LabelII);
Mike Stump9afab102009-02-19 03:04:26 +00004186
Steve Naroff313c4162009-02-28 16:48:43 +00004187 LabelStmt *LabelDecl;
4188
Daniel Dunbar879788d2008-08-04 16:51:22 +00004189 // If we haven't seen this label yet, create a forward reference. It
4190 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff313c4162009-02-28 16:48:43 +00004191 if (I == ActiveScope->LabelMap.end()) {
Steve Naroff774e4152009-01-21 00:14:39 +00004192 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004193
Steve Naroff313c4162009-02-28 16:48:43 +00004194 ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl));
4195 } else
4196 LabelDecl = static_cast<LabelStmt *>(I->second);
4197
Chris Lattner4b009652007-07-25 00:24:17 +00004198 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004199 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4200 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004201}
4202
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004203Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004204 SourceLocation RPLoc) { // "({..})"
4205 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4206 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4207 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4208
Eli Friedmanbc941e12009-01-24 23:09:00 +00004209 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4210 if (isFileScope) {
4211 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4212 }
4213
Chris Lattner4b009652007-07-25 00:24:17 +00004214 // FIXME: there are a variety of strange constraints to enforce here, for
4215 // example, it is not possible to goto into a stmt expression apparently.
4216 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004217
Chris Lattner4b009652007-07-25 00:24:17 +00004218 // FIXME: the last statement in the compount stmt has its value used. We
4219 // should not warn about it being unused.
4220
4221 // If there are sub stmts in the compound stmt, take the type of the last one
4222 // as the type of the stmtexpr.
4223 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004224
Chris Lattner200964f2008-07-26 19:51:01 +00004225 if (!Compound->body_empty()) {
4226 Stmt *LastStmt = Compound->body_back();
4227 // If LastStmt is a label, skip down through into the body.
4228 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4229 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004230
Chris Lattner200964f2008-07-26 19:51:01 +00004231 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004232 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004233 }
Mike Stump9afab102009-02-19 03:04:26 +00004234
Steve Naroff774e4152009-01-21 00:14:39 +00004235 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004236}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004237
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004238Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4239 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004240 SourceLocation TypeLoc,
4241 TypeTy *argty,
4242 OffsetOfComponent *CompPtr,
4243 unsigned NumComponents,
4244 SourceLocation RPLoc) {
4245 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4246 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004247
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004248 bool Dependent = ArgTy->isDependentType();
4249
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004250 // We must have at least one component that refers to the type, and the first
4251 // one is known to be a field designator. Verify that the ArgTy represents
4252 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004253 if (!Dependent && !ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004254 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stump9afab102009-02-19 03:04:26 +00004255
Eli Friedman342d9432009-02-27 06:44:11 +00004256 // Otherwise, create a null pointer as the base, and iteratively process
4257 // the offsetof designators.
4258 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4259 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
4260 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
4261 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004262
Chris Lattnerb37522e2007-08-31 21:49:13 +00004263 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4264 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004265 // FIXME: This diagnostic isn't actually visible because the location is in
4266 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004267 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004268 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4269 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004270
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004271 if (!Dependent) {
4272 // FIXME: Dependent case loses a lot of information here. And probably
4273 // leaks like a sieve.
4274 for (unsigned i = 0; i != NumComponents; ++i) {
4275 const OffsetOfComponent &OC = CompPtr[i];
4276 if (OC.isBrackets) {
4277 // Offset of an array sub-field. TODO: Should we allow vector elements?
4278 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4279 if (!AT) {
4280 Res->Destroy(Context);
4281 return Diag(OC.LocEnd, diag::err_offsetof_array_type)
4282 << Res->getType();
4283 }
4284
4285 // FIXME: C++: Verify that operator[] isn't overloaded.
4286
Eli Friedman342d9432009-02-27 06:44:11 +00004287 // Promote the array so it looks more like a normal array subscript
4288 // expression.
4289 DefaultFunctionArrayConversion(Res);
4290
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004291 // C99 6.5.2.1p1
4292 Expr *Idx = static_cast<Expr*>(OC.U.E);
4293 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4294 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4295 << Idx->getSourceRange();
4296
4297 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4298 OC.LocEnd);
4299 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004300 }
Mike Stump9afab102009-02-19 03:04:26 +00004301
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004302 const RecordType *RC = Res->getType()->getAsRecordType();
4303 if (!RC) {
4304 Res->Destroy(Context);
4305 return Diag(OC.LocEnd, diag::err_offsetof_record_type)
4306 << Res->getType();
4307 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004308
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004309 // Get the decl corresponding to this.
4310 RecordDecl *RD = RC->getDecl();
4311 FieldDecl *MemberDecl
4312 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4313 LookupMemberName)
4314 .getAsDecl());
4315 if (!MemberDecl)
4316 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4317 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004318
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004319 // FIXME: C++: Verify that MemberDecl isn't a static field.
4320 // FIXME: Verify that MemberDecl isn't a bitfield.
4321 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4322 // matter here.
4323 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004324 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004325 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004326 }
Mike Stump9afab102009-02-19 03:04:26 +00004327
4328 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff774e4152009-01-21 00:14:39 +00004329 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004330}
4331
4332
Mike Stump9afab102009-02-19 03:04:26 +00004333Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004334 TypeTy *arg1, TypeTy *arg2,
4335 SourceLocation RPLoc) {
4336 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4337 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004338
Steve Naroff63bad2d2007-08-01 22:05:33 +00004339 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004340
4341 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff774e4152009-01-21 00:14:39 +00004342 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004343}
4344
Mike Stump9afab102009-02-19 03:04:26 +00004345Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004346 ExprTy *expr1, ExprTy *expr2,
4347 SourceLocation RPLoc) {
4348 Expr *CondExpr = static_cast<Expr*>(cond);
4349 Expr *LHSExpr = static_cast<Expr*>(expr1);
4350 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stump9afab102009-02-19 03:04:26 +00004351
Steve Naroff93c53012007-08-03 21:21:27 +00004352 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4353
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004354 QualType resType;
4355 if (CondExpr->isValueDependent()) {
4356 resType = Context.DependentTy;
4357 } else {
4358 // The conditional expression is required to be a constant expression.
4359 llvm::APSInt condEval(32);
4360 SourceLocation ExpLoc;
4361 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4362 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4363 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004364
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004365 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4366 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4367 }
4368
Mike Stump9afab102009-02-19 03:04:26 +00004369 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00004370 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004371}
4372
Steve Naroff52a81c02008-09-03 18:15:37 +00004373//===----------------------------------------------------------------------===//
4374// Clang Extensions.
4375//===----------------------------------------------------------------------===//
4376
4377/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004378void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004379 // Analyze block parameters.
4380 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004381
Steve Naroff52a81c02008-09-03 18:15:37 +00004382 // Add BSI to CurBlock.
4383 BSI->PrevBlockInfo = CurBlock;
4384 CurBlock = BSI;
Steve Naroff313c4162009-02-28 16:48:43 +00004385 ActiveScope = BlockScope;
Mike Stump9afab102009-02-19 03:04:26 +00004386
Steve Naroff52a81c02008-09-03 18:15:37 +00004387 BSI->ReturnType = 0;
4388 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004389 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004390
Steve Naroff52059382008-10-10 01:28:17 +00004391 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004392 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004393}
4394
Mike Stumpc1fddff2009-02-04 22:31:32 +00004395void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4396 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4397
4398 if (ParamInfo.getNumTypeObjects() == 0
4399 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4400 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4401
4402 // The type is entirely optional as well, if none, use DependentTy.
4403 if (T.isNull())
4404 T = Context.DependentTy;
4405
4406 // The parameter list is optional, if there was none, assume ().
4407 if (!T->isFunctionType())
4408 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4409
4410 CurBlock->hasPrototype = true;
4411 CurBlock->isVariadic = false;
4412 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4413 .getTypePtr();
4414
4415 if (!RetTy->isDependentType())
4416 CurBlock->ReturnType = RetTy;
4417 return;
4418 }
4419
Steve Naroff52a81c02008-09-03 18:15:37 +00004420 // Analyze arguments to block.
4421 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4422 "Not a function declarator!");
4423 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004424
Steve Naroff52059382008-10-10 01:28:17 +00004425 CurBlock->hasPrototype = FTI.hasPrototype;
4426 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004427
Steve Naroff52a81c02008-09-03 18:15:37 +00004428 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4429 // no arguments, not a function that takes a single void argument.
4430 if (FTI.hasPrototype &&
4431 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4432 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4433 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4434 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004435 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004436 } else if (FTI.hasPrototype) {
4437 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004438 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4439 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004440 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4441
4442 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4443 .getTypePtr();
4444
4445 if (!RetTy->isDependentType())
4446 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004447 }
Steve Naroff52059382008-10-10 01:28:17 +00004448 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004449
Steve Naroff52059382008-10-10 01:28:17 +00004450 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4451 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4452 // If this has an identifier, add it to the scope stack.
4453 if ((*AI)->getIdentifier())
4454 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004455}
4456
4457/// ActOnBlockError - If there is an error parsing a block, this callback
4458/// is invoked to pop the information about the block from the action impl.
4459void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4460 // Ensure that CurBlock is deleted.
4461 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004462
Steve Naroff52a81c02008-09-03 18:15:37 +00004463 // Pop off CurBlock, handle nested blocks.
4464 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004465
Steve Naroff52a81c02008-09-03 18:15:37 +00004466 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stump9afab102009-02-19 03:04:26 +00004467
Steve Naroff52a81c02008-09-03 18:15:37 +00004468}
4469
4470/// ActOnBlockStmtExpr - This is called when the body of a block statement
4471/// literal was successfully completed. ^(int x){...}
4472Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4473 Scope *CurScope) {
4474 // Ensure that CurBlock is deleted.
4475 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004476 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004477
Steve Naroff52059382008-10-10 01:28:17 +00004478 PopDeclContext();
4479
Steve Naroff5cd38432009-02-28 21:01:15 +00004480 // Before poping CurBlock, set ActiveScope to this scopes parent.
4481 ActiveScope = CurBlock->TheScope->getParent();
4482
Steve Naroff52a81c02008-09-03 18:15:37 +00004483 // Pop off CurBlock, handle nested blocks.
4484 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004485
Steve Naroff52a81c02008-09-03 18:15:37 +00004486 QualType RetTy = Context.VoidTy;
4487 if (BSI->ReturnType)
4488 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004489
Steve Naroff52a81c02008-09-03 18:15:37 +00004490 llvm::SmallVector<QualType, 8> ArgTypes;
4491 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4492 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004493
Steve Naroff52a81c02008-09-03 18:15:37 +00004494 QualType BlockTy;
4495 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004496 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004497 else
4498 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004499 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004500
Steve Naroff52a81c02008-09-03 18:15:37 +00004501 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004502
Steve Naroff95029d92008-10-08 18:44:00 +00004503 BSI->TheDecl->setBody(Body.take());
Mike Stumpae93d652009-02-19 22:01:56 +00004504 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff52a81c02008-09-03 18:15:37 +00004505}
4506
Anders Carlsson36760332007-10-15 20:28:48 +00004507Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4508 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004509 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004510 Expr *E = static_cast<Expr*>(expr);
4511 QualType T = QualType::getFromOpaquePtr(type);
4512
4513 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004514
4515 // Get the va_list type
4516 QualType VaListType = Context.getBuiltinVaListType();
4517 // Deal with implicit array decay; for example, on x86-64,
4518 // va_list is an array, but it's supposed to decay to
4519 // a pointer for va_arg.
4520 if (VaListType->isArrayType())
4521 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004522 // Make sure the input expression also decays appropriately.
4523 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004524
4525 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004526 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004527 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004528 << E->getType() << E->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004529
Anders Carlsson36760332007-10-15 20:28:48 +00004530 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004531
Steve Naroff774e4152009-01-21 00:14:39 +00004532 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004533}
4534
Douglas Gregorad4b3792008-11-29 04:51:27 +00004535Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4536 // The type of __null will be int or long, depending on the size of
4537 // pointers on the target.
4538 QualType Ty;
4539 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4540 Ty = Context.IntTy;
4541 else
4542 Ty = Context.LongTy;
4543
Steve Naroff774e4152009-01-21 00:14:39 +00004544 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004545}
4546
Chris Lattner005ed752008-01-04 18:04:52 +00004547bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4548 SourceLocation Loc,
4549 QualType DstType, QualType SrcType,
4550 Expr *SrcExpr, const char *Flavor) {
4551 // Decode the result (notice that AST's are still created for extensions).
4552 bool isInvalid = false;
4553 unsigned DiagKind;
4554 switch (ConvTy) {
4555 default: assert(0 && "Unknown conversion type");
4556 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004557 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004558 DiagKind = diag::ext_typecheck_convert_pointer_int;
4559 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004560 case IntToPointer:
4561 DiagKind = diag::ext_typecheck_convert_int_pointer;
4562 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004563 case IncompatiblePointer:
4564 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4565 break;
4566 case FunctionVoidPointer:
4567 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4568 break;
4569 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004570 // If the qualifiers lost were because we were applying the
4571 // (deprecated) C++ conversion from a string literal to a char*
4572 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4573 // Ideally, this check would be performed in
4574 // CheckPointerTypesForAssignment. However, that would require a
4575 // bit of refactoring (so that the second argument is an
4576 // expression, rather than a type), which should be done as part
4577 // of a larger effort to fix CheckPointerTypesForAssignment for
4578 // C++ semantics.
4579 if (getLangOptions().CPlusPlus &&
4580 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4581 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004582 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4583 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004584 case IntToBlockPointer:
4585 DiagKind = diag::err_int_to_block_pointer;
4586 break;
4587 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004588 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004589 break;
Steve Naroff19608432008-10-14 22:18:38 +00004590 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004591 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004592 // it can give a more specific diagnostic.
4593 DiagKind = diag::warn_incompatible_qualified_id;
4594 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004595 case IncompatibleVectors:
4596 DiagKind = diag::warn_incompatible_vectors;
4597 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004598 case Incompatible:
4599 DiagKind = diag::err_typecheck_convert_incompatible;
4600 isInvalid = true;
4601 break;
4602 }
Mike Stump9afab102009-02-19 03:04:26 +00004603
Chris Lattner271d4c22008-11-24 05:29:24 +00004604 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4605 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004606 return isInvalid;
4607}
Anders Carlssond5201b92008-11-30 19:50:32 +00004608
4609bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4610{
4611 Expr::EvalResult EvalResult;
4612
Mike Stump9afab102009-02-19 03:04:26 +00004613 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004614 EvalResult.HasSideEffects) {
4615 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4616
4617 if (EvalResult.Diag) {
4618 // We only show the note if it's not the usual "invalid subexpression"
4619 // or if it's actually in a subexpression.
4620 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4621 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4622 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4623 }
Mike Stump9afab102009-02-19 03:04:26 +00004624
Anders Carlssond5201b92008-11-30 19:50:32 +00004625 return true;
4626 }
4627
4628 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004629 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004630 E->getSourceRange();
4631
4632 // Print the reason it's not a constant.
4633 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4634 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4635 }
Mike Stump9afab102009-02-19 03:04:26 +00004636
Anders Carlssond5201b92008-11-30 19:50:32 +00004637 if (Result)
4638 *Result = EvalResult.Val.getInt();
4639 return false;
4640}